exp_ch3.adb (Build_Array_Init_Proc): Clarify comment related to creating dummy init...
[official-gcc.git] / gcc / predict.c
blobe90b95c068332f0ac39cb8618e60cbf420001f8b
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
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"
62 #include "pointer-set.h"
64 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
65 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
66 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
67 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
69 /* Random guesstimation given names. */
70 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 100 - 1)
71 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
72 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
73 #define PROB_ALWAYS (REG_BR_PROB_BASE)
75 static void combine_predictions_for_insn (rtx, basic_block);
76 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
77 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
78 static void compute_function_frequency (void);
79 static void choose_function_section (void);
80 static bool can_predict_insn_p (const_rtx);
82 /* Information we hold about each branch predictor.
83 Filled using information from predict.def. */
85 struct predictor_info
87 const char *const name; /* Name used in the debugging dumps. */
88 const int hitrate; /* Expected hitrate used by
89 predict_insn_def call. */
90 const int flags;
93 /* Use given predictor without Dempster-Shaffer theory if it matches
94 using first_match heuristics. */
95 #define PRED_FLAG_FIRST_MATCH 1
97 /* Recompute hitrate in percent to our representation. */
99 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
101 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
102 static const struct predictor_info predictor_info[]= {
103 #include "predict.def"
105 /* Upper bound on predictors. */
106 {NULL, 0, 0}
108 #undef DEF_PREDICTOR
110 /* Return TRUE if frequency FREQ is considered to be hot. */
111 static bool
112 maybe_hot_frequency_p (int freq)
114 if (!profile_info || !flag_branch_probabilities)
116 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
117 return false;
118 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
119 return true;
121 if (profile_status == PROFILE_ABSENT)
122 return true;
123 if (freq < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
124 return false;
125 return true;
128 /* Return true in case BB can be CPU intensive and should be optimized
129 for maximal performance. */
131 bool
132 maybe_hot_bb_p (const_basic_block bb)
134 if (profile_info && flag_branch_probabilities
135 && (bb->count
136 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
137 return false;
138 return maybe_hot_frequency_p (bb->frequency);
141 /* Return true in case BB can be CPU intensive and should be optimized
142 for maximal performance. */
144 bool
145 maybe_hot_edge_p (edge e)
147 if (profile_info && flag_branch_probabilities
148 && (e->count
149 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
150 return false;
151 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
154 /* Return true in case BB is cold and should be optimized for size. */
156 bool
157 probably_cold_bb_p (const_basic_block bb)
159 if (profile_info && flag_branch_probabilities
160 && (bb->count
161 < profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
162 return true;
163 if ((!profile_info || !flag_branch_probabilities)
164 && cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
165 return true;
166 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
167 return true;
168 return false;
171 /* Return true in case BB is probably never executed. */
172 bool
173 probably_never_executed_bb_p (const_basic_block bb)
175 if (profile_info && flag_branch_probabilities)
176 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
177 if ((!profile_info || !flag_branch_probabilities)
178 && cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
179 return true;
180 return false;
183 /* Return true when current function should always be optimized for size. */
185 static bool
186 always_optimize_for_size_p (void)
188 return (optimize_size
189 || cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED);
192 /* Return TRUE when BB should be optimized for size. */
194 bool
195 optimize_bb_for_size_p (basic_block bb)
197 return always_optimize_for_size_p () || !maybe_hot_bb_p (bb);
200 /* Return TRUE when BB should be optimized for speed. */
202 bool
203 optimize_bb_for_speed_p (basic_block bb)
205 return !optimize_bb_for_size_p (bb);
208 /* Return TRUE when BB should be optimized for size. */
210 bool
211 optimize_edge_for_size_p (edge e)
213 return always_optimize_for_size_p () || !maybe_hot_edge_p (e);
216 /* Return TRUE when BB should be optimized for speed. */
218 bool
219 optimize_edge_for_speed_p (edge e)
221 return !optimize_edge_for_size_p (e);
224 /* Return TRUE when BB should be optimized for size. */
226 bool
227 optimize_insn_for_size_p (void)
229 return always_optimize_for_size_p () || !crtl->maybe_hot_insn_p;
232 /* Return TRUE when BB should be optimized for speed. */
234 bool
235 optimize_insn_for_speed_p (void)
237 return !optimize_insn_for_size_p ();
240 /* Set RTL expansion for BB profile. */
242 void
243 rtl_profile_for_bb (basic_block bb)
245 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
248 /* Set RTL expansion for edge profile. */
250 void
251 rtl_profile_for_edge (edge e)
253 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
256 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
257 void
258 default_rtl_profile (void)
260 crtl->maybe_hot_insn_p = true;
263 /* Return true if the one of outgoing edges is already predicted by
264 PREDICTOR. */
266 bool
267 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
269 rtx note;
270 if (!INSN_P (BB_END (bb)))
271 return false;
272 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
273 if (REG_NOTE_KIND (note) == REG_BR_PRED
274 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
275 return true;
276 return false;
279 /* This map contains for a basic block the list of predictions for the
280 outgoing edges. */
282 static struct pointer_map_t *bb_predictions;
284 /* Return true if the one of outgoing edges is already predicted by
285 PREDICTOR. */
287 bool
288 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
290 struct edge_prediction *i;
291 void **preds = pointer_map_contains (bb_predictions, bb);
293 if (!preds)
294 return false;
296 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
297 if (i->ep_predictor == predictor)
298 return true;
299 return false;
302 /* Return true when the probability of edge is reliable.
304 The profile guessing code is good at predicting branch outcome (ie.
305 taken/not taken), that is predicted right slightly over 75% of time.
306 It is however notoriously poor on predicting the probability itself.
307 In general the profile appear a lot flatter (with probabilities closer
308 to 50%) than the reality so it is bad idea to use it to drive optimization
309 such as those disabling dynamic branch prediction for well predictable
310 branches.
312 There are two exceptions - edges leading to noreturn edges and edges
313 predicted by number of iterations heuristics are predicted well. This macro
314 should be able to distinguish those, but at the moment it simply check for
315 noreturn heuristic that is only one giving probability over 99% or bellow
316 1%. In future we might want to propagate reliability information across the
317 CFG if we find this information useful on multiple places. */
318 static bool
319 probability_reliable_p (int prob)
321 return (profile_status == PROFILE_READ
322 || (profile_status == PROFILE_GUESSED
323 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
326 /* Same predicate as above, working on edges. */
327 bool
328 edge_probability_reliable_p (const_edge e)
330 return probability_reliable_p (e->probability);
333 /* Same predicate as edge_probability_reliable_p, working on notes. */
334 bool
335 br_prob_note_reliable_p (const_rtx note)
337 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
338 return probability_reliable_p (INTVAL (XEXP (note, 0)));
341 static void
342 predict_insn (rtx insn, enum br_predictor predictor, int probability)
344 gcc_assert (any_condjump_p (insn));
345 if (!flag_guess_branch_prob)
346 return;
348 add_reg_note (insn, REG_BR_PRED,
349 gen_rtx_CONCAT (VOIDmode,
350 GEN_INT ((int) predictor),
351 GEN_INT ((int) probability)));
354 /* Predict insn by given predictor. */
356 void
357 predict_insn_def (rtx insn, enum br_predictor predictor,
358 enum prediction taken)
360 int probability = predictor_info[(int) predictor].hitrate;
362 if (taken != TAKEN)
363 probability = REG_BR_PROB_BASE - probability;
365 predict_insn (insn, predictor, probability);
368 /* Predict edge E with given probability if possible. */
370 void
371 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
373 rtx last_insn;
374 last_insn = BB_END (e->src);
376 /* We can store the branch prediction information only about
377 conditional jumps. */
378 if (!any_condjump_p (last_insn))
379 return;
381 /* We always store probability of branching. */
382 if (e->flags & EDGE_FALLTHRU)
383 probability = REG_BR_PROB_BASE - probability;
385 predict_insn (last_insn, predictor, probability);
388 /* Predict edge E with the given PROBABILITY. */
389 void
390 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
392 gcc_assert (profile_status != PROFILE_GUESSED);
393 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
394 && flag_guess_branch_prob && optimize)
396 struct edge_prediction *i = XNEW (struct edge_prediction);
397 void **preds = pointer_map_insert (bb_predictions, e->src);
399 i->ep_next = (struct edge_prediction *) *preds;
400 *preds = i;
401 i->ep_probability = probability;
402 i->ep_predictor = predictor;
403 i->ep_edge = e;
407 /* Remove all predictions on given basic block that are attached
408 to edge E. */
409 void
410 remove_predictions_associated_with_edge (edge e)
412 void **preds;
414 if (!bb_predictions)
415 return;
417 preds = pointer_map_contains (bb_predictions, e->src);
419 if (preds)
421 struct edge_prediction **prediction = (struct edge_prediction **) preds;
422 struct edge_prediction *next;
424 while (*prediction)
426 if ((*prediction)->ep_edge == e)
428 next = (*prediction)->ep_next;
429 free (*prediction);
430 *prediction = next;
432 else
433 prediction = &((*prediction)->ep_next);
438 /* Clears the list of predictions stored for BB. */
440 static void
441 clear_bb_predictions (basic_block bb)
443 void **preds = pointer_map_contains (bb_predictions, bb);
444 struct edge_prediction *pred, *next;
446 if (!preds)
447 return;
449 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
451 next = pred->ep_next;
452 free (pred);
454 *preds = NULL;
457 /* Return true when we can store prediction on insn INSN.
458 At the moment we represent predictions only on conditional
459 jumps, not at computed jump or other complicated cases. */
460 static bool
461 can_predict_insn_p (const_rtx insn)
463 return (JUMP_P (insn)
464 && any_condjump_p (insn)
465 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
468 /* Predict edge E by given predictor if possible. */
470 void
471 predict_edge_def (edge e, enum br_predictor predictor,
472 enum prediction taken)
474 int probability = predictor_info[(int) predictor].hitrate;
476 if (taken != TAKEN)
477 probability = REG_BR_PROB_BASE - probability;
479 predict_edge (e, predictor, probability);
482 /* Invert all branch predictions or probability notes in the INSN. This needs
483 to be done each time we invert the condition used by the jump. */
485 void
486 invert_br_probabilities (rtx insn)
488 rtx note;
490 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
491 if (REG_NOTE_KIND (note) == REG_BR_PROB)
492 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
493 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
494 XEXP (XEXP (note, 0), 1)
495 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
498 /* Dump information about the branch prediction to the output file. */
500 static void
501 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
502 basic_block bb, int used)
504 edge e;
505 edge_iterator ei;
507 if (!file)
508 return;
510 FOR_EACH_EDGE (e, ei, bb->succs)
511 if (! (e->flags & EDGE_FALLTHRU))
512 break;
514 fprintf (file, " %s heuristics%s: %.1f%%",
515 predictor_info[predictor].name,
516 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
518 if (bb->count)
520 fprintf (file, " exec ");
521 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
522 if (e)
524 fprintf (file, " hit ");
525 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
526 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
530 fprintf (file, "\n");
533 /* We can not predict the probabilities of outgoing edges of bb. Set them
534 evenly and hope for the best. */
535 static void
536 set_even_probabilities (basic_block bb)
538 int nedges = 0;
539 edge e;
540 edge_iterator ei;
542 FOR_EACH_EDGE (e, ei, bb->succs)
543 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
544 nedges ++;
545 FOR_EACH_EDGE (e, ei, bb->succs)
546 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
547 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
548 else
549 e->probability = 0;
552 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
553 note if not already present. Remove now useless REG_BR_PRED notes. */
555 static void
556 combine_predictions_for_insn (rtx insn, basic_block bb)
558 rtx prob_note;
559 rtx *pnote;
560 rtx note;
561 int best_probability = PROB_EVEN;
562 int best_predictor = END_PREDICTORS;
563 int combined_probability = REG_BR_PROB_BASE / 2;
564 int d;
565 bool first_match = false;
566 bool found = false;
568 if (!can_predict_insn_p (insn))
570 set_even_probabilities (bb);
571 return;
574 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
575 pnote = &REG_NOTES (insn);
576 if (dump_file)
577 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
578 bb->index);
580 /* We implement "first match" heuristics and use probability guessed
581 by predictor with smallest index. */
582 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
583 if (REG_NOTE_KIND (note) == REG_BR_PRED)
585 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
586 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
588 found = true;
589 if (best_predictor > predictor)
590 best_probability = probability, best_predictor = predictor;
592 d = (combined_probability * probability
593 + (REG_BR_PROB_BASE - combined_probability)
594 * (REG_BR_PROB_BASE - probability));
596 /* Use FP math to avoid overflows of 32bit integers. */
597 if (d == 0)
598 /* If one probability is 0% and one 100%, avoid division by zero. */
599 combined_probability = REG_BR_PROB_BASE / 2;
600 else
601 combined_probability = (((double) combined_probability) * probability
602 * REG_BR_PROB_BASE / d + 0.5);
605 /* Decide which heuristic to use. In case we didn't match anything,
606 use no_prediction heuristic, in case we did match, use either
607 first match or Dempster-Shaffer theory depending on the flags. */
609 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
610 first_match = true;
612 if (!found)
613 dump_prediction (dump_file, PRED_NO_PREDICTION,
614 combined_probability, bb, true);
615 else
617 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
618 bb, !first_match);
619 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
620 bb, first_match);
623 if (first_match)
624 combined_probability = best_probability;
625 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
627 while (*pnote)
629 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
631 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
632 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
634 dump_prediction (dump_file, predictor, probability, bb,
635 !first_match || best_predictor == predictor);
636 *pnote = XEXP (*pnote, 1);
638 else
639 pnote = &XEXP (*pnote, 1);
642 if (!prob_note)
644 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
646 /* Save the prediction into CFG in case we are seeing non-degenerated
647 conditional jump. */
648 if (!single_succ_p (bb))
650 BRANCH_EDGE (bb)->probability = combined_probability;
651 FALLTHRU_EDGE (bb)->probability
652 = REG_BR_PROB_BASE - combined_probability;
655 else if (!single_succ_p (bb))
657 int prob = INTVAL (XEXP (prob_note, 0));
659 BRANCH_EDGE (bb)->probability = prob;
660 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
662 else
663 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
666 /* Combine predictions into single probability and store them into CFG.
667 Remove now useless prediction entries. */
669 static void
670 combine_predictions_for_bb (basic_block bb)
672 int best_probability = PROB_EVEN;
673 int best_predictor = END_PREDICTORS;
674 int combined_probability = REG_BR_PROB_BASE / 2;
675 int d;
676 bool first_match = false;
677 bool found = false;
678 struct edge_prediction *pred;
679 int nedges = 0;
680 edge e, first = NULL, second = NULL;
681 edge_iterator ei;
682 void **preds;
684 FOR_EACH_EDGE (e, ei, bb->succs)
685 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
687 nedges ++;
688 if (first && !second)
689 second = e;
690 if (!first)
691 first = e;
694 /* When there is no successor or only one choice, prediction is easy.
696 We are lazy for now and predict only basic blocks with two outgoing
697 edges. It is possible to predict generic case too, but we have to
698 ignore first match heuristics and do more involved combining. Implement
699 this later. */
700 if (nedges != 2)
702 if (!bb->count)
703 set_even_probabilities (bb);
704 clear_bb_predictions (bb);
705 if (dump_file)
706 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
707 nedges, bb->index);
708 return;
711 if (dump_file)
712 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
714 preds = pointer_map_contains (bb_predictions, bb);
715 if (preds)
717 /* We implement "first match" heuristics and use probability guessed
718 by predictor with smallest index. */
719 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
721 int predictor = pred->ep_predictor;
722 int probability = pred->ep_probability;
724 if (pred->ep_edge != first)
725 probability = REG_BR_PROB_BASE - probability;
727 found = true;
728 if (best_predictor > predictor)
729 best_probability = probability, best_predictor = predictor;
731 d = (combined_probability * probability
732 + (REG_BR_PROB_BASE - combined_probability)
733 * (REG_BR_PROB_BASE - probability));
735 /* Use FP math to avoid overflows of 32bit integers. */
736 if (d == 0)
737 /* If one probability is 0% and one 100%, avoid division by zero. */
738 combined_probability = REG_BR_PROB_BASE / 2;
739 else
740 combined_probability = (((double) combined_probability)
741 * probability
742 * REG_BR_PROB_BASE / d + 0.5);
746 /* Decide which heuristic to use. In case we didn't match anything,
747 use no_prediction heuristic, in case we did match, use either
748 first match or Dempster-Shaffer theory depending on the flags. */
750 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
751 first_match = true;
753 if (!found)
754 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
755 else
757 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
758 !first_match);
759 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
760 first_match);
763 if (first_match)
764 combined_probability = best_probability;
765 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
767 if (preds)
769 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
771 int predictor = pred->ep_predictor;
772 int probability = pred->ep_probability;
774 if (pred->ep_edge != EDGE_SUCC (bb, 0))
775 probability = REG_BR_PROB_BASE - probability;
776 dump_prediction (dump_file, predictor, probability, bb,
777 !first_match || best_predictor == predictor);
780 clear_bb_predictions (bb);
782 if (!bb->count)
784 first->probability = combined_probability;
785 second->probability = REG_BR_PROB_BASE - combined_probability;
789 /* Predict edge probabilities by exploiting loop structure. */
791 static void
792 predict_loops (void)
794 loop_iterator li;
795 struct loop *loop;
797 scev_initialize ();
799 /* Try to predict out blocks in a loop that are not part of a
800 natural loop. */
801 FOR_EACH_LOOP (li, loop, 0)
803 basic_block bb, *bbs;
804 unsigned j, n_exits;
805 VEC (edge, heap) *exits;
806 struct tree_niter_desc niter_desc;
807 edge ex;
809 exits = get_loop_exit_edges (loop);
810 n_exits = VEC_length (edge, exits);
812 for (j = 0; VEC_iterate (edge, exits, j, ex); j++)
814 tree niter = NULL;
815 HOST_WIDE_INT nitercst;
816 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
817 int probability;
818 enum br_predictor predictor;
820 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
821 niter = niter_desc.niter;
822 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
823 niter = loop_niter_by_eval (loop, ex);
825 if (TREE_CODE (niter) == INTEGER_CST)
827 if (host_integerp (niter, 1)
828 && compare_tree_int (niter, max-1) == -1)
829 nitercst = tree_low_cst (niter, 1) + 1;
830 else
831 nitercst = max;
832 predictor = PRED_LOOP_ITERATIONS;
834 /* If we have just one exit and we can derive some information about
835 the number of iterations of the loop from the statements inside
836 the loop, use it to predict this exit. */
837 else if (n_exits == 1)
839 nitercst = estimated_loop_iterations_int (loop, false);
840 if (nitercst < 0)
841 continue;
842 if (nitercst > max)
843 nitercst = max;
845 predictor = PRED_LOOP_ITERATIONS_GUESSED;
847 else
848 continue;
850 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
851 predict_edge (ex, predictor, probability);
853 VEC_free (edge, heap, exits);
855 bbs = get_loop_body (loop);
857 for (j = 0; j < loop->num_nodes; j++)
859 int header_found = 0;
860 edge e;
861 edge_iterator ei;
863 bb = bbs[j];
865 /* Bypass loop heuristics on continue statement. These
866 statements construct loops via "non-loop" constructs
867 in the source language and are better to be handled
868 separately. */
869 if (predicted_by_p (bb, PRED_CONTINUE))
870 continue;
872 /* Loop branch heuristics - predict an edge back to a
873 loop's head as taken. */
874 if (bb == loop->latch)
876 e = find_edge (loop->latch, loop->header);
877 if (e)
879 header_found = 1;
880 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
884 /* Loop exit heuristics - predict an edge exiting the loop if the
885 conditional has no loop header successors as not taken. */
886 if (!header_found
887 /* If we already used more reliable loop exit predictors, do not
888 bother with PRED_LOOP_EXIT. */
889 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
890 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
892 /* For loop with many exits we don't want to predict all exits
893 with the pretty large probability, because if all exits are
894 considered in row, the loop would be predicted to iterate
895 almost never. The code to divide probability by number of
896 exits is very rough. It should compute the number of exits
897 taken in each patch through function (not the overall number
898 of exits that might be a lot higher for loops with wide switch
899 statements in them) and compute n-th square root.
901 We limit the minimal probability by 2% to avoid
902 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
903 as this was causing regression in perl benchmark containing such
904 a wide loop. */
906 int probability = ((REG_BR_PROB_BASE
907 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
908 / n_exits);
909 if (probability < HITRATE (2))
910 probability = HITRATE (2);
911 FOR_EACH_EDGE (e, ei, bb->succs)
912 if (e->dest->index < NUM_FIXED_BLOCKS
913 || !flow_bb_inside_loop_p (loop, e->dest))
914 predict_edge (e, PRED_LOOP_EXIT, probability);
918 /* Free basic blocks from get_loop_body. */
919 free (bbs);
922 scev_finalize ();
925 /* Attempt to predict probabilities of BB outgoing edges using local
926 properties. */
927 static void
928 bb_estimate_probability_locally (basic_block bb)
930 rtx last_insn = BB_END (bb);
931 rtx cond;
933 if (! can_predict_insn_p (last_insn))
934 return;
935 cond = get_condition (last_insn, NULL, false, false);
936 if (! cond)
937 return;
939 /* Try "pointer heuristic."
940 A comparison ptr == 0 is predicted as false.
941 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
942 if (COMPARISON_P (cond)
943 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
944 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
946 if (GET_CODE (cond) == EQ)
947 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
948 else if (GET_CODE (cond) == NE)
949 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
951 else
953 /* Try "opcode heuristic."
954 EQ tests are usually false and NE tests are usually true. Also,
955 most quantities are positive, so we can make the appropriate guesses
956 about signed comparisons against zero. */
957 switch (GET_CODE (cond))
959 case CONST_INT:
960 /* Unconditional branch. */
961 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
962 cond == const0_rtx ? NOT_TAKEN : TAKEN);
963 break;
965 case EQ:
966 case UNEQ:
967 /* Floating point comparisons appears to behave in a very
968 unpredictable way because of special role of = tests in
969 FP code. */
970 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
972 /* Comparisons with 0 are often used for booleans and there is
973 nothing useful to predict about them. */
974 else if (XEXP (cond, 1) == const0_rtx
975 || XEXP (cond, 0) == const0_rtx)
977 else
978 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
979 break;
981 case NE:
982 case LTGT:
983 /* Floating point comparisons appears to behave in a very
984 unpredictable way because of special role of = tests in
985 FP code. */
986 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
988 /* Comparisons with 0 are often used for booleans and there is
989 nothing useful to predict about them. */
990 else if (XEXP (cond, 1) == const0_rtx
991 || XEXP (cond, 0) == const0_rtx)
993 else
994 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
995 break;
997 case ORDERED:
998 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
999 break;
1001 case UNORDERED:
1002 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1003 break;
1005 case LE:
1006 case LT:
1007 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1008 || XEXP (cond, 1) == constm1_rtx)
1009 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1010 break;
1012 case GE:
1013 case GT:
1014 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1015 || XEXP (cond, 1) == constm1_rtx)
1016 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1017 break;
1019 default:
1020 break;
1024 /* Set edge->probability for each successor edge of BB. */
1025 void
1026 guess_outgoing_edge_probabilities (basic_block bb)
1028 bb_estimate_probability_locally (bb);
1029 combine_predictions_for_insn (BB_END (bb), bb);
1032 static tree expr_expected_value (tree, bitmap);
1034 /* Helper function for expr_expected_value. */
1036 static tree
1037 expr_expected_value_1 (tree type, tree op0, enum tree_code code, tree op1, bitmap visited)
1039 gimple def;
1041 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1043 if (TREE_CONSTANT (op0))
1044 return op0;
1046 if (code != SSA_NAME)
1047 return NULL_TREE;
1049 def = SSA_NAME_DEF_STMT (op0);
1051 /* If we were already here, break the infinite cycle. */
1052 if (bitmap_bit_p (visited, SSA_NAME_VERSION (op0)))
1053 return NULL;
1054 bitmap_set_bit (visited, SSA_NAME_VERSION (op0));
1056 if (gimple_code (def) == GIMPLE_PHI)
1058 /* All the arguments of the PHI node must have the same constant
1059 length. */
1060 int i, n = gimple_phi_num_args (def);
1061 tree val = NULL, new_val;
1063 for (i = 0; i < n; i++)
1065 tree arg = PHI_ARG_DEF (def, i);
1067 /* If this PHI has itself as an argument, we cannot
1068 determine the string length of this argument. However,
1069 if we can find an expected constant value for the other
1070 PHI args then we can still be sure that this is
1071 likely a constant. So be optimistic and just
1072 continue with the next argument. */
1073 if (arg == PHI_RESULT (def))
1074 continue;
1076 new_val = expr_expected_value (arg, visited);
1077 if (!new_val)
1078 return NULL;
1079 if (!val)
1080 val = new_val;
1081 else if (!operand_equal_p (val, new_val, false))
1082 return NULL;
1084 return val;
1086 if (is_gimple_assign (def))
1088 if (gimple_assign_lhs (def) != op0)
1089 return NULL;
1091 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1092 gimple_assign_rhs1 (def),
1093 gimple_assign_rhs_code (def),
1094 gimple_assign_rhs2 (def),
1095 visited);
1098 if (is_gimple_call (def))
1100 tree decl = gimple_call_fndecl (def);
1101 if (!decl)
1102 return NULL;
1103 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1104 && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
1106 tree val;
1108 if (gimple_call_num_args (def) != 2)
1109 return NULL;
1110 val = gimple_call_arg (def, 0);
1111 if (TREE_CONSTANT (val))
1112 return val;
1113 return gimple_call_arg (def, 1);
1117 return NULL;
1120 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1122 tree res;
1123 op0 = expr_expected_value (op0, visited);
1124 if (!op0)
1125 return NULL;
1126 op1 = expr_expected_value (op1, visited);
1127 if (!op1)
1128 return NULL;
1129 res = fold_build2 (code, type, op0, op1);
1130 if (TREE_CONSTANT (res))
1131 return res;
1132 return NULL;
1134 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1136 tree res;
1137 op0 = expr_expected_value (op0, visited);
1138 if (!op0)
1139 return NULL;
1140 res = fold_build1 (code, type, op0);
1141 if (TREE_CONSTANT (res))
1142 return res;
1143 return NULL;
1145 return NULL;
1148 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1149 The function is used by builtin_expect branch predictor so the evidence
1150 must come from this construct and additional possible constant folding.
1152 We may want to implement more involved value guess (such as value range
1153 propagation based prediction), but such tricks shall go to new
1154 implementation. */
1156 static tree
1157 expr_expected_value (tree expr, bitmap visited)
1159 enum tree_code code;
1160 tree op0, op1;
1162 if (TREE_CONSTANT (expr))
1163 return expr;
1165 extract_ops_from_tree (expr, &code, &op0, &op1);
1166 return expr_expected_value_1 (TREE_TYPE (expr),
1167 op0, code, op1, visited);
1171 /* Get rid of all builtin_expect calls we no longer need. */
1172 static void
1173 strip_builtin_expect (void)
1175 basic_block bb;
1176 gimple ass_stmt;
1177 tree var;
1179 FOR_EACH_BB (bb)
1181 gimple_stmt_iterator bi;
1182 for (bi = gsi_start_bb (bb); !gsi_end_p (bi); gsi_next (&bi))
1184 gimple stmt = gsi_stmt (bi);
1185 tree fndecl;
1187 if (gimple_code (stmt) != GIMPLE_CALL)
1188 continue;
1190 fndecl = gimple_call_fndecl (stmt);
1192 if (fndecl
1193 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1194 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1195 && gimple_call_num_args (stmt) == 2)
1197 var = gimple_call_lhs (stmt);
1198 ass_stmt = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1200 gsi_replace (&bi, ass_stmt, true);
1206 /* Predict using opcode of the last statement in basic block. */
1207 static void
1208 tree_predict_by_opcode (basic_block bb)
1210 gimple stmt = last_stmt (bb);
1211 edge then_edge;
1212 tree op0, op1;
1213 tree type;
1214 tree val;
1215 enum tree_code cmp;
1216 bitmap visited;
1217 edge_iterator ei;
1219 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1220 return;
1221 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1222 if (then_edge->flags & EDGE_TRUE_VALUE)
1223 break;
1224 op0 = gimple_cond_lhs (stmt);
1225 op1 = gimple_cond_rhs (stmt);
1226 cmp = gimple_cond_code (stmt);
1227 type = TREE_TYPE (op0);
1228 visited = BITMAP_ALLOC (NULL);
1229 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1230 BITMAP_FREE (visited);
1231 if (val)
1233 if (integer_zerop (val))
1234 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1235 else
1236 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1237 return;
1239 /* Try "pointer heuristic."
1240 A comparison ptr == 0 is predicted as false.
1241 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1242 if (POINTER_TYPE_P (type))
1244 if (cmp == EQ_EXPR)
1245 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1246 else if (cmp == NE_EXPR)
1247 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1249 else
1251 /* Try "opcode heuristic."
1252 EQ tests are usually false and NE tests are usually true. Also,
1253 most quantities are positive, so we can make the appropriate guesses
1254 about signed comparisons against zero. */
1255 switch (cmp)
1257 case EQ_EXPR:
1258 case UNEQ_EXPR:
1259 /* Floating point comparisons appears to behave in a very
1260 unpredictable way because of special role of = tests in
1261 FP code. */
1262 if (FLOAT_TYPE_P (type))
1264 /* Comparisons with 0 are often used for booleans and there is
1265 nothing useful to predict about them. */
1266 else if (integer_zerop (op0) || integer_zerop (op1))
1268 else
1269 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1270 break;
1272 case NE_EXPR:
1273 case LTGT_EXPR:
1274 /* Floating point comparisons appears to behave in a very
1275 unpredictable way because of special role of = tests in
1276 FP code. */
1277 if (FLOAT_TYPE_P (type))
1279 /* Comparisons with 0 are often used for booleans and there is
1280 nothing useful to predict about them. */
1281 else if (integer_zerop (op0)
1282 || integer_zerop (op1))
1284 else
1285 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1286 break;
1288 case ORDERED_EXPR:
1289 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1290 break;
1292 case UNORDERED_EXPR:
1293 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1294 break;
1296 case LE_EXPR:
1297 case LT_EXPR:
1298 if (integer_zerop (op1)
1299 || integer_onep (op1)
1300 || integer_all_onesp (op1)
1301 || real_zerop (op1)
1302 || real_onep (op1)
1303 || real_minus_onep (op1))
1304 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1305 break;
1307 case GE_EXPR:
1308 case GT_EXPR:
1309 if (integer_zerop (op1)
1310 || integer_onep (op1)
1311 || integer_all_onesp (op1)
1312 || real_zerop (op1)
1313 || real_onep (op1)
1314 || real_minus_onep (op1))
1315 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1316 break;
1318 default:
1319 break;
1323 /* Try to guess whether the value of return means error code. */
1325 static enum br_predictor
1326 return_prediction (tree val, enum prediction *prediction)
1328 /* VOID. */
1329 if (!val)
1330 return PRED_NO_PREDICTION;
1331 /* Different heuristics for pointers and scalars. */
1332 if (POINTER_TYPE_P (TREE_TYPE (val)))
1334 /* NULL is usually not returned. */
1335 if (integer_zerop (val))
1337 *prediction = NOT_TAKEN;
1338 return PRED_NULL_RETURN;
1341 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1343 /* Negative return values are often used to indicate
1344 errors. */
1345 if (TREE_CODE (val) == INTEGER_CST
1346 && tree_int_cst_sgn (val) < 0)
1348 *prediction = NOT_TAKEN;
1349 return PRED_NEGATIVE_RETURN;
1351 /* Constant return values seems to be commonly taken.
1352 Zero/one often represent booleans so exclude them from the
1353 heuristics. */
1354 if (TREE_CONSTANT (val)
1355 && (!integer_zerop (val) && !integer_onep (val)))
1357 *prediction = TAKEN;
1358 return PRED_CONST_RETURN;
1361 return PRED_NO_PREDICTION;
1364 /* Find the basic block with return expression and look up for possible
1365 return value trying to apply RETURN_PREDICTION heuristics. */
1366 static void
1367 apply_return_prediction (void)
1369 gimple return_stmt = NULL;
1370 tree return_val;
1371 edge e;
1372 gimple phi;
1373 int phi_num_args, i;
1374 enum br_predictor pred;
1375 enum prediction direction;
1376 edge_iterator ei;
1378 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1380 return_stmt = last_stmt (e->src);
1381 if (return_stmt
1382 && gimple_code (return_stmt) == GIMPLE_RETURN)
1383 break;
1385 if (!e)
1386 return;
1387 return_val = gimple_return_retval (return_stmt);
1388 if (!return_val)
1389 return;
1390 if (TREE_CODE (return_val) != SSA_NAME
1391 || !SSA_NAME_DEF_STMT (return_val)
1392 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1393 return;
1394 phi = SSA_NAME_DEF_STMT (return_val);
1395 phi_num_args = gimple_phi_num_args (phi);
1396 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1398 /* Avoid the degenerate case where all return values form the function
1399 belongs to same category (ie they are all positive constants)
1400 so we can hardly say something about them. */
1401 for (i = 1; i < phi_num_args; i++)
1402 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1403 break;
1404 if (i != phi_num_args)
1405 for (i = 0; i < phi_num_args; i++)
1407 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1408 if (pred != PRED_NO_PREDICTION)
1409 predict_paths_leading_to (gimple_phi_arg_edge (phi, i)->src, pred,
1410 direction);
1414 /* Look for basic block that contains unlikely to happen events
1415 (such as noreturn calls) and mark all paths leading to execution
1416 of this basic blocks as unlikely. */
1418 static void
1419 tree_bb_level_predictions (void)
1421 basic_block bb;
1423 apply_return_prediction ();
1425 FOR_EACH_BB (bb)
1427 gimple_stmt_iterator gsi;
1429 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
1431 gimple stmt = gsi_stmt (gsi);
1432 tree decl;
1434 if (is_gimple_call (stmt))
1436 if (gimple_call_flags (stmt) & ECF_NORETURN)
1437 predict_paths_leading_to (bb, PRED_NORETURN,
1438 NOT_TAKEN);
1439 decl = gimple_call_fndecl (stmt);
1440 if (decl
1441 && lookup_attribute ("cold",
1442 DECL_ATTRIBUTES (decl)))
1443 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
1444 NOT_TAKEN);
1446 else if (gimple_code (stmt) == GIMPLE_PREDICT)
1448 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
1449 gimple_predict_outcome (stmt));
1450 gsi_remove (&gsi, true);
1451 continue;
1454 gsi_next (&gsi);
1459 #ifdef ENABLE_CHECKING
1461 /* Callback for pointer_map_traverse, asserts that the pointer map is
1462 empty. */
1464 static bool
1465 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
1466 void *data ATTRIBUTE_UNUSED)
1468 gcc_assert (!*value);
1469 return false;
1471 #endif
1473 /* Predict branch probabilities and estimate profile of the tree CFG. */
1474 static unsigned int
1475 tree_estimate_probability (void)
1477 basic_block bb;
1479 loop_optimizer_init (0);
1480 if (dump_file && (dump_flags & TDF_DETAILS))
1481 flow_loops_dump (dump_file, NULL, 0);
1483 add_noreturn_fake_exit_edges ();
1484 connect_infinite_loops_to_exit ();
1485 /* We use loop_niter_by_eval, which requires that the loops have
1486 preheaders. */
1487 create_preheaders (CP_SIMPLE_PREHEADERS);
1488 calculate_dominance_info (CDI_POST_DOMINATORS);
1490 bb_predictions = pointer_map_create ();
1491 tree_bb_level_predictions ();
1493 mark_irreducible_loops ();
1494 record_loop_exits ();
1495 if (number_of_loops () > 1)
1496 predict_loops ();
1498 FOR_EACH_BB (bb)
1500 edge e;
1501 edge_iterator ei;
1503 FOR_EACH_EDGE (e, ei, bb->succs)
1505 /* Predict early returns to be probable, as we've already taken
1506 care for error returns and other cases are often used for
1507 fast paths through function.
1509 Since we've already removed the return statements, we are
1510 looking for CFG like:
1512 if (conditional)
1515 goto return_block
1517 some other blocks
1518 return_block:
1519 return_stmt. */
1520 if (e->dest != bb->next_bb
1521 && e->dest != EXIT_BLOCK_PTR
1522 && single_succ_p (e->dest)
1523 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
1524 && gimple_code (last_stmt (e->dest)) == GIMPLE_RETURN)
1526 edge e1;
1527 edge_iterator ei1;
1529 if (single_succ_p (bb))
1531 FOR_EACH_EDGE (e1, ei1, bb->preds)
1532 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1533 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1534 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
1535 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1537 else
1538 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
1539 && !predicted_by_p (e->src, PRED_CONST_RETURN)
1540 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
1541 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1544 /* Look for block we are guarding (ie we dominate it,
1545 but it doesn't postdominate us). */
1546 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1547 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1548 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1550 gimple_stmt_iterator bi;
1552 /* The call heuristic claims that a guarded function call
1553 is improbable. This is because such calls are often used
1554 to signal exceptional situations such as printing error
1555 messages. */
1556 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
1557 gsi_next (&bi))
1559 gimple stmt = gsi_stmt (bi);
1560 if (is_gimple_call (stmt)
1561 /* Constant and pure calls are hardly used to signalize
1562 something exceptional. */
1563 && gimple_has_side_effects (stmt))
1565 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1566 break;
1571 tree_predict_by_opcode (bb);
1573 FOR_EACH_BB (bb)
1574 combine_predictions_for_bb (bb);
1576 #ifdef ENABLE_CHECKING
1577 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
1578 #endif
1579 pointer_map_destroy (bb_predictions);
1580 bb_predictions = NULL;
1582 strip_builtin_expect ();
1583 estimate_bb_frequencies ();
1584 free_dominance_info (CDI_POST_DOMINATORS);
1585 remove_fake_exit_edges ();
1586 loop_optimizer_finalize ();
1587 if (dump_file && (dump_flags & TDF_DETAILS))
1588 gimple_dump_cfg (dump_file, dump_flags);
1589 if (profile_status == PROFILE_ABSENT)
1590 profile_status = PROFILE_GUESSED;
1591 return 0;
1594 /* Predict edges to successors of CUR whose sources are not postdominated by
1595 BB by PRED and recurse to all postdominators. */
1597 static void
1598 predict_paths_for_bb (basic_block cur, basic_block bb,
1599 enum br_predictor pred,
1600 enum prediction taken)
1602 edge e;
1603 edge_iterator ei;
1604 basic_block son;
1606 /* We are looking for all edges forming edge cut induced by
1607 set of all blocks postdominated by BB. */
1608 FOR_EACH_EDGE (e, ei, cur->preds)
1609 if (e->src->index >= NUM_FIXED_BLOCKS
1610 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
1612 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
1613 predict_edge_def (e, pred, taken);
1615 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
1616 son;
1617 son = next_dom_son (CDI_POST_DOMINATORS, son))
1618 predict_paths_for_bb (son, bb, pred, taken);
1621 /* Sets branch probabilities according to PREDiction and
1622 FLAGS. */
1624 static void
1625 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
1626 enum prediction taken)
1628 predict_paths_for_bb (bb, bb, pred, taken);
1631 /* This is used to carry information about basic blocks. It is
1632 attached to the AUX field of the standard CFG block. */
1634 typedef struct block_info_def
1636 /* Estimated frequency of execution of basic_block. */
1637 sreal frequency;
1639 /* To keep queue of basic blocks to process. */
1640 basic_block next;
1642 /* Number of predecessors we need to visit first. */
1643 int npredecessors;
1644 } *block_info;
1646 /* Similar information for edges. */
1647 typedef struct edge_info_def
1649 /* In case edge is a loopback edge, the probability edge will be reached
1650 in case header is. Estimated number of iterations of the loop can be
1651 then computed as 1 / (1 - back_edge_prob). */
1652 sreal back_edge_prob;
1653 /* True if the edge is a loopback edge in the natural loop. */
1654 unsigned int back_edge:1;
1655 } *edge_info;
1657 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1658 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1660 /* Helper function for estimate_bb_frequencies.
1661 Propagate the frequencies in blocks marked in
1662 TOVISIT, starting in HEAD. */
1664 static void
1665 propagate_freq (basic_block head, bitmap tovisit)
1667 basic_block bb;
1668 basic_block last;
1669 unsigned i;
1670 edge e;
1671 basic_block nextbb;
1672 bitmap_iterator bi;
1674 /* For each basic block we need to visit count number of his predecessors
1675 we need to visit first. */
1676 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
1678 edge_iterator ei;
1679 int count = 0;
1681 /* The outermost "loop" includes the exit block, which we can not
1682 look up via BASIC_BLOCK. Detect this and use EXIT_BLOCK_PTR
1683 directly. Do the same for the entry block. */
1684 bb = BASIC_BLOCK (i);
1686 FOR_EACH_EDGE (e, ei, bb->preds)
1688 bool visit = bitmap_bit_p (tovisit, e->src->index);
1690 if (visit && !(e->flags & EDGE_DFS_BACK))
1691 count++;
1692 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
1693 fprintf (dump_file,
1694 "Irreducible region hit, ignoring edge to %i->%i\n",
1695 e->src->index, bb->index);
1697 BLOCK_INFO (bb)->npredecessors = count;
1700 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1701 last = head;
1702 for (bb = head; bb; bb = nextbb)
1704 edge_iterator ei;
1705 sreal cyclic_probability, frequency;
1707 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1708 memcpy (&frequency, &real_zero, sizeof (real_zero));
1710 nextbb = BLOCK_INFO (bb)->next;
1711 BLOCK_INFO (bb)->next = NULL;
1713 /* Compute frequency of basic block. */
1714 if (bb != head)
1716 #ifdef ENABLE_CHECKING
1717 FOR_EACH_EDGE (e, ei, bb->preds)
1718 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
1719 || (e->flags & EDGE_DFS_BACK));
1720 #endif
1722 FOR_EACH_EDGE (e, ei, bb->preds)
1723 if (EDGE_INFO (e)->back_edge)
1725 sreal_add (&cyclic_probability, &cyclic_probability,
1726 &EDGE_INFO (e)->back_edge_prob);
1728 else if (!(e->flags & EDGE_DFS_BACK))
1730 sreal tmp;
1732 /* frequency += (e->probability
1733 * BLOCK_INFO (e->src)->frequency /
1734 REG_BR_PROB_BASE); */
1736 sreal_init (&tmp, e->probability, 0);
1737 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1738 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1739 sreal_add (&frequency, &frequency, &tmp);
1742 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1744 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1745 sizeof (frequency));
1747 else
1749 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1751 memcpy (&cyclic_probability, &real_almost_one,
1752 sizeof (real_almost_one));
1755 /* BLOCK_INFO (bb)->frequency = frequency
1756 / (1 - cyclic_probability) */
1758 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1759 sreal_div (&BLOCK_INFO (bb)->frequency,
1760 &frequency, &cyclic_probability);
1764 bitmap_clear_bit (tovisit, bb->index);
1766 e = find_edge (bb, head);
1767 if (e)
1769 sreal tmp;
1771 /* EDGE_INFO (e)->back_edge_prob
1772 = ((e->probability * BLOCK_INFO (bb)->frequency)
1773 / REG_BR_PROB_BASE); */
1775 sreal_init (&tmp, e->probability, 0);
1776 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1777 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1778 &tmp, &real_inv_br_prob_base);
1781 /* Propagate to successor blocks. */
1782 FOR_EACH_EDGE (e, ei, bb->succs)
1783 if (!(e->flags & EDGE_DFS_BACK)
1784 && BLOCK_INFO (e->dest)->npredecessors)
1786 BLOCK_INFO (e->dest)->npredecessors--;
1787 if (!BLOCK_INFO (e->dest)->npredecessors)
1789 if (!nextbb)
1790 nextbb = e->dest;
1791 else
1792 BLOCK_INFO (last)->next = e->dest;
1794 last = e->dest;
1800 /* Estimate probabilities of loopback edges in loops at same nest level. */
1802 static void
1803 estimate_loops_at_level (struct loop *first_loop)
1805 struct loop *loop;
1807 for (loop = first_loop; loop; loop = loop->next)
1809 edge e;
1810 basic_block *bbs;
1811 unsigned i;
1812 bitmap tovisit = BITMAP_ALLOC (NULL);
1814 estimate_loops_at_level (loop->inner);
1816 /* Find current loop back edge and mark it. */
1817 e = loop_latch_edge (loop);
1818 EDGE_INFO (e)->back_edge = 1;
1820 bbs = get_loop_body (loop);
1821 for (i = 0; i < loop->num_nodes; i++)
1822 bitmap_set_bit (tovisit, bbs[i]->index);
1823 free (bbs);
1824 propagate_freq (loop->header, tovisit);
1825 BITMAP_FREE (tovisit);
1829 /* Propagates frequencies through structure of loops. */
1831 static void
1832 estimate_loops (void)
1834 bitmap tovisit = BITMAP_ALLOC (NULL);
1835 basic_block bb;
1837 /* Start by estimating the frequencies in the loops. */
1838 if (number_of_loops () > 1)
1839 estimate_loops_at_level (current_loops->tree_root->inner);
1841 /* Now propagate the frequencies through all the blocks. */
1842 FOR_ALL_BB (bb)
1844 bitmap_set_bit (tovisit, bb->index);
1846 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
1847 BITMAP_FREE (tovisit);
1850 /* Convert counts measured by profile driven feedback to frequencies.
1851 Return nonzero iff there was any nonzero execution count. */
1854 counts_to_freqs (void)
1856 gcov_type count_max, true_count_max = 0;
1857 basic_block bb;
1859 FOR_EACH_BB (bb)
1860 true_count_max = MAX (bb->count, true_count_max);
1862 count_max = MAX (true_count_max, 1);
1863 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1864 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1866 return true_count_max;
1869 /* Return true if function is likely to be expensive, so there is no point to
1870 optimize performance of prologue, epilogue or do inlining at the expense
1871 of code size growth. THRESHOLD is the limit of number of instructions
1872 function can execute at average to be still considered not expensive. */
1874 bool
1875 expensive_function_p (int threshold)
1877 unsigned int sum = 0;
1878 basic_block bb;
1879 unsigned int limit;
1881 /* We can not compute accurately for large thresholds due to scaled
1882 frequencies. */
1883 gcc_assert (threshold <= BB_FREQ_MAX);
1885 /* Frequencies are out of range. This either means that function contains
1886 internal loop executing more than BB_FREQ_MAX times or profile feedback
1887 is available and function has not been executed at all. */
1888 if (ENTRY_BLOCK_PTR->frequency == 0)
1889 return true;
1891 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1892 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1893 FOR_EACH_BB (bb)
1895 rtx insn;
1897 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
1898 insn = NEXT_INSN (insn))
1899 if (active_insn_p (insn))
1901 sum += bb->frequency;
1902 if (sum > limit)
1903 return true;
1907 return false;
1910 /* Estimate basic blocks frequency by given branch probabilities. */
1912 void
1913 estimate_bb_frequencies (void)
1915 basic_block bb;
1916 sreal freq_max;
1918 if (!flag_branch_probabilities || !counts_to_freqs ())
1920 static int real_values_initialized = 0;
1922 if (!real_values_initialized)
1924 real_values_initialized = 1;
1925 sreal_init (&real_zero, 0, 0);
1926 sreal_init (&real_one, 1, 0);
1927 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
1928 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
1929 sreal_init (&real_one_half, 1, -1);
1930 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
1931 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
1934 mark_dfs_back_edges ();
1936 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
1938 /* Set up block info for each basic block. */
1939 alloc_aux_for_blocks (sizeof (struct block_info_def));
1940 alloc_aux_for_edges (sizeof (struct edge_info_def));
1941 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1943 edge e;
1944 edge_iterator ei;
1946 FOR_EACH_EDGE (e, ei, bb->succs)
1948 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
1949 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1950 &EDGE_INFO (e)->back_edge_prob,
1951 &real_inv_br_prob_base);
1955 /* First compute probabilities locally for each loop from innermost
1956 to outermost to examine probabilities for back edges. */
1957 estimate_loops ();
1959 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1960 FOR_EACH_BB (bb)
1961 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
1962 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
1964 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
1965 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1967 sreal tmp;
1969 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
1970 sreal_add (&tmp, &tmp, &real_one_half);
1971 bb->frequency = sreal_to_int (&tmp);
1974 free_aux_for_blocks ();
1975 free_aux_for_edges ();
1977 compute_function_frequency ();
1978 if (flag_reorder_functions)
1979 choose_function_section ();
1982 /* Decide whether function is hot, cold or unlikely executed. */
1983 static void
1984 compute_function_frequency (void)
1986 basic_block bb;
1988 if (!profile_info || !flag_branch_probabilities)
1990 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
1991 != NULL)
1992 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1993 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
1994 != NULL)
1995 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1996 return;
1998 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1999 FOR_EACH_BB (bb)
2001 if (maybe_hot_bb_p (bb))
2003 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2004 return;
2006 if (!probably_never_executed_bb_p (bb))
2007 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
2011 /* Choose appropriate section for the function. */
2012 static void
2013 choose_function_section (void)
2015 if (DECL_SECTION_NAME (current_function_decl)
2016 || !targetm.have_named_sections
2017 /* Theoretically we can split the gnu.linkonce text section too,
2018 but this requires more work as the frequency needs to match
2019 for all generated objects so we need to merge the frequency
2020 of all instances. For now just never set frequency for these. */
2021 || DECL_ONE_ONLY (current_function_decl))
2022 return;
2024 /* If we are doing the partitioning optimization, let the optimization
2025 choose the correct section into which to put things. */
2027 if (flag_reorder_blocks_and_partition)
2028 return;
2030 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
2031 DECL_SECTION_NAME (current_function_decl) =
2032 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
2033 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
2034 DECL_SECTION_NAME (current_function_decl) =
2035 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
2036 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
2039 static bool
2040 gate_estimate_probability (void)
2042 return flag_guess_branch_prob;
2045 /* Build PREDICT_EXPR. */
2046 tree
2047 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2049 tree t = build1 (PREDICT_EXPR, void_type_node,
2050 build_int_cst (NULL, predictor));
2051 PREDICT_EXPR_OUTCOME (t) = taken;
2052 return t;
2055 const char *
2056 predictor_name (enum br_predictor predictor)
2058 return predictor_info[predictor].name;
2061 struct gimple_opt_pass pass_profile =
2064 GIMPLE_PASS,
2065 "profile", /* name */
2066 gate_estimate_probability, /* gate */
2067 tree_estimate_probability, /* execute */
2068 NULL, /* sub */
2069 NULL, /* next */
2070 0, /* static_pass_number */
2071 TV_BRANCH_PROB, /* tv_id */
2072 PROP_cfg, /* properties_required */
2073 0, /* properties_provided */
2074 0, /* properties_destroyed */
2075 0, /* todo_flags_start */
2076 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */