1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
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
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
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/>. */
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. */
33 #include "coretypes.h"
38 #include "hard-reg-set.h"
39 #include "basic-block.h"
40 #include "insn-config.h"
55 #include "tree-flow.h"
57 #include "tree-dump.h"
58 #include "tree-pass.h"
60 #include "tree-scalar-evolution.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 PROV_VERY_UNLIKELY should be small enough so basic block predicted
71 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
72 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
73 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
74 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
75 #define PROB_ALWAYS (REG_BR_PROB_BASE)
77 static void combine_predictions_for_insn (rtx, basic_block);
78 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
79 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
80 static void compute_function_frequency (void);
81 static void choose_function_section (void);
82 static bool can_predict_insn_p (const_rtx);
84 /* Information we hold about each branch predictor.
85 Filled using information from predict.def. */
89 const char *const name; /* Name used in the debugging dumps. */
90 const int hitrate; /* Expected hitrate used by
91 predict_insn_def call. */
95 /* Use given predictor without Dempster-Shaffer theory if it matches
96 using first_match heuristics. */
97 #define PRED_FLAG_FIRST_MATCH 1
99 /* Recompute hitrate in percent to our representation. */
101 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
103 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
104 static const struct predictor_info predictor_info[]= {
105 #include "predict.def"
107 /* Upper bound on predictors. */
112 /* Return TRUE if frequency FREQ is considered to be hot. */
115 maybe_hot_frequency_p (int freq)
117 if (!profile_info || !flag_branch_probabilities)
119 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
121 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
124 if (profile_status == PROFILE_ABSENT)
126 if (freq < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
131 /* Return TRUE if frequency FREQ is considered to be hot. */
134 maybe_hot_count_p (gcov_type count)
136 if (profile_status != PROFILE_READ)
138 /* Code executed at most once is not hot. */
139 if (profile_info->runs >= count)
142 > profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION));
145 /* Return true in case BB can be CPU intensive and should be optimized
146 for maximal performance. */
149 maybe_hot_bb_p (const_basic_block bb)
151 if (profile_status == PROFILE_READ)
152 return maybe_hot_count_p (bb->count);
153 return maybe_hot_frequency_p (bb->frequency);
156 /* Return true if the call can be hot. */
159 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
161 if (profile_info && flag_branch_probabilities
163 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
165 if (lookup_attribute ("cold", DECL_ATTRIBUTES (edge->callee->decl))
166 || lookup_attribute ("cold", DECL_ATTRIBUTES (edge->caller->decl)))
168 if (lookup_attribute ("hot", DECL_ATTRIBUTES (edge->caller->decl)))
170 if (flag_guess_branch_prob
171 && edge->frequency <= (CGRAPH_FREQ_BASE
172 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
177 /* Return true in case BB can be CPU intensive and should be optimized
178 for maximal performance. */
181 maybe_hot_edge_p (edge e)
183 if (profile_status == PROFILE_READ)
184 return maybe_hot_count_p (e->count);
185 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
188 /* Return true in case BB is probably never executed. */
190 probably_never_executed_bb_p (const_basic_block bb)
192 if (profile_info && flag_branch_probabilities)
193 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
194 if ((!profile_info || !flag_branch_probabilities)
195 && cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
200 /* Return true when current function should always be optimized for size. */
203 optimize_function_for_size_p (struct function *fun)
205 return (optimize_size
206 || (fun && (fun->function_frequency
207 == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)));
210 /* Return true when current function should always be optimized for speed. */
213 optimize_function_for_speed_p (struct function *fun)
215 return !optimize_function_for_size_p (fun);
218 /* Return TRUE when BB should be optimized for size. */
221 optimize_bb_for_size_p (const_basic_block bb)
223 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
226 /* Return TRUE when BB should be optimized for speed. */
229 optimize_bb_for_speed_p (const_basic_block bb)
231 return !optimize_bb_for_size_p (bb);
234 /* Return TRUE when BB should be optimized for size. */
237 optimize_edge_for_size_p (edge e)
239 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
242 /* Return TRUE when BB should be optimized for speed. */
245 optimize_edge_for_speed_p (edge e)
247 return !optimize_edge_for_size_p (e);
250 /* Return TRUE when BB should be optimized for size. */
253 optimize_insn_for_size_p (void)
255 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
258 /* Return TRUE when BB should be optimized for speed. */
261 optimize_insn_for_speed_p (void)
263 return !optimize_insn_for_size_p ();
266 /* Return TRUE when LOOP should be optimized for size. */
269 optimize_loop_for_size_p (struct loop *loop)
271 return optimize_bb_for_size_p (loop->header);
274 /* Return TRUE when LOOP should be optimized for speed. */
277 optimize_loop_for_speed_p (struct loop *loop)
279 return optimize_bb_for_speed_p (loop->header);
282 /* Return TRUE when LOOP nest should be optimized for speed. */
285 optimize_loop_nest_for_speed_p (struct loop *loop)
287 struct loop *l = loop;
288 if (optimize_loop_for_speed_p (loop))
291 while (l && l != loop)
293 if (optimize_loop_for_speed_p (l))
301 while (l != loop && !l->next)
310 /* Return TRUE when LOOP nest should be optimized for size. */
313 optimize_loop_nest_for_size_p (struct loop *loop)
315 return !optimize_loop_nest_for_speed_p (loop);
318 /* Return true when edge E is likely to be well predictable by branch
322 predictable_edge_p (edge e)
324 if (profile_status == PROFILE_ABSENT)
327 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
328 || (REG_BR_PROB_BASE - e->probability
329 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
335 /* Set RTL expansion for BB profile. */
338 rtl_profile_for_bb (basic_block bb)
340 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
343 /* Set RTL expansion for edge profile. */
346 rtl_profile_for_edge (edge e)
348 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
351 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
353 default_rtl_profile (void)
355 crtl->maybe_hot_insn_p = true;
358 /* Return true if the one of outgoing edges is already predicted by
362 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
365 if (!INSN_P (BB_END (bb)))
367 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
368 if (REG_NOTE_KIND (note) == REG_BR_PRED
369 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
374 /* This map contains for a basic block the list of predictions for the
377 static struct pointer_map_t *bb_predictions;
379 /* Return true if the one of outgoing edges is already predicted by
383 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
385 struct edge_prediction *i;
386 void **preds = pointer_map_contains (bb_predictions, bb);
391 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
392 if (i->ep_predictor == predictor)
397 /* Return true when the probability of edge is reliable.
399 The profile guessing code is good at predicting branch outcome (ie.
400 taken/not taken), that is predicted right slightly over 75% of time.
401 It is however notoriously poor on predicting the probability itself.
402 In general the profile appear a lot flatter (with probabilities closer
403 to 50%) than the reality so it is bad idea to use it to drive optimization
404 such as those disabling dynamic branch prediction for well predictable
407 There are two exceptions - edges leading to noreturn edges and edges
408 predicted by number of iterations heuristics are predicted well. This macro
409 should be able to distinguish those, but at the moment it simply check for
410 noreturn heuristic that is only one giving probability over 99% or bellow
411 1%. In future we might want to propagate reliability information across the
412 CFG if we find this information useful on multiple places. */
414 probability_reliable_p (int prob)
416 return (profile_status == PROFILE_READ
417 || (profile_status == PROFILE_GUESSED
418 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
421 /* Same predicate as above, working on edges. */
423 edge_probability_reliable_p (const_edge e)
425 return probability_reliable_p (e->probability);
428 /* Same predicate as edge_probability_reliable_p, working on notes. */
430 br_prob_note_reliable_p (const_rtx note)
432 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
433 return probability_reliable_p (INTVAL (XEXP (note, 0)));
437 predict_insn (rtx insn, enum br_predictor predictor, int probability)
439 gcc_assert (any_condjump_p (insn));
440 if (!flag_guess_branch_prob)
443 add_reg_note (insn, REG_BR_PRED,
444 gen_rtx_CONCAT (VOIDmode,
445 GEN_INT ((int) predictor),
446 GEN_INT ((int) probability)));
449 /* Predict insn by given predictor. */
452 predict_insn_def (rtx insn, enum br_predictor predictor,
453 enum prediction taken)
455 int probability = predictor_info[(int) predictor].hitrate;
458 probability = REG_BR_PROB_BASE - probability;
460 predict_insn (insn, predictor, probability);
463 /* Predict edge E with given probability if possible. */
466 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
469 last_insn = BB_END (e->src);
471 /* We can store the branch prediction information only about
472 conditional jumps. */
473 if (!any_condjump_p (last_insn))
476 /* We always store probability of branching. */
477 if (e->flags & EDGE_FALLTHRU)
478 probability = REG_BR_PROB_BASE - probability;
480 predict_insn (last_insn, predictor, probability);
483 /* Predict edge E with the given PROBABILITY. */
485 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
487 gcc_assert (profile_status != PROFILE_GUESSED);
488 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
489 && flag_guess_branch_prob && optimize)
491 struct edge_prediction *i = XNEW (struct edge_prediction);
492 void **preds = pointer_map_insert (bb_predictions, e->src);
494 i->ep_next = (struct edge_prediction *) *preds;
496 i->ep_probability = probability;
497 i->ep_predictor = predictor;
502 /* Remove all predictions on given basic block that are attached
505 remove_predictions_associated_with_edge (edge e)
512 preds = pointer_map_contains (bb_predictions, e->src);
516 struct edge_prediction **prediction = (struct edge_prediction **) preds;
517 struct edge_prediction *next;
521 if ((*prediction)->ep_edge == e)
523 next = (*prediction)->ep_next;
528 prediction = &((*prediction)->ep_next);
533 /* Clears the list of predictions stored for BB. */
536 clear_bb_predictions (basic_block bb)
538 void **preds = pointer_map_contains (bb_predictions, bb);
539 struct edge_prediction *pred, *next;
544 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
546 next = pred->ep_next;
552 /* Return true when we can store prediction on insn INSN.
553 At the moment we represent predictions only on conditional
554 jumps, not at computed jump or other complicated cases. */
556 can_predict_insn_p (const_rtx insn)
558 return (JUMP_P (insn)
559 && any_condjump_p (insn)
560 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
563 /* Predict edge E by given predictor if possible. */
566 predict_edge_def (edge e, enum br_predictor predictor,
567 enum prediction taken)
569 int probability = predictor_info[(int) predictor].hitrate;
572 probability = REG_BR_PROB_BASE - probability;
574 predict_edge (e, predictor, probability);
577 /* Invert all branch predictions or probability notes in the INSN. This needs
578 to be done each time we invert the condition used by the jump. */
581 invert_br_probabilities (rtx insn)
585 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
586 if (REG_NOTE_KIND (note) == REG_BR_PROB)
587 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
588 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
589 XEXP (XEXP (note, 0), 1)
590 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
593 /* Dump information about the branch prediction to the output file. */
596 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
597 basic_block bb, int used)
605 FOR_EACH_EDGE (e, ei, bb->succs)
606 if (! (e->flags & EDGE_FALLTHRU))
609 fprintf (file, " %s heuristics%s: %.1f%%",
610 predictor_info[predictor].name,
611 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
615 fprintf (file, " exec ");
616 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
619 fprintf (file, " hit ");
620 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
621 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
625 fprintf (file, "\n");
628 /* We can not predict the probabilities of outgoing edges of bb. Set them
629 evenly and hope for the best. */
631 set_even_probabilities (basic_block bb)
637 FOR_EACH_EDGE (e, ei, bb->succs)
638 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
640 FOR_EACH_EDGE (e, ei, bb->succs)
641 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
642 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
647 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
648 note if not already present. Remove now useless REG_BR_PRED notes. */
651 combine_predictions_for_insn (rtx insn, basic_block bb)
656 int best_probability = PROB_EVEN;
657 enum br_predictor best_predictor = END_PREDICTORS;
658 int combined_probability = REG_BR_PROB_BASE / 2;
660 bool first_match = false;
663 if (!can_predict_insn_p (insn))
665 set_even_probabilities (bb);
669 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
670 pnote = ®_NOTES (insn);
672 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
675 /* We implement "first match" heuristics and use probability guessed
676 by predictor with smallest index. */
677 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
678 if (REG_NOTE_KIND (note) == REG_BR_PRED)
680 enum br_predictor predictor = ((enum br_predictor)
681 INTVAL (XEXP (XEXP (note, 0), 0)));
682 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
685 if (best_predictor > predictor)
686 best_probability = probability, best_predictor = predictor;
688 d = (combined_probability * probability
689 + (REG_BR_PROB_BASE - combined_probability)
690 * (REG_BR_PROB_BASE - probability));
692 /* Use FP math to avoid overflows of 32bit integers. */
694 /* If one probability is 0% and one 100%, avoid division by zero. */
695 combined_probability = REG_BR_PROB_BASE / 2;
697 combined_probability = (((double) combined_probability) * probability
698 * REG_BR_PROB_BASE / d + 0.5);
701 /* Decide which heuristic to use. In case we didn't match anything,
702 use no_prediction heuristic, in case we did match, use either
703 first match or Dempster-Shaffer theory depending on the flags. */
705 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
709 dump_prediction (dump_file, PRED_NO_PREDICTION,
710 combined_probability, bb, true);
713 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
715 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
720 combined_probability = best_probability;
721 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
725 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
727 enum br_predictor predictor = ((enum br_predictor)
728 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
729 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
731 dump_prediction (dump_file, predictor, probability, bb,
732 !first_match || best_predictor == predictor);
733 *pnote = XEXP (*pnote, 1);
736 pnote = &XEXP (*pnote, 1);
741 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
743 /* Save the prediction into CFG in case we are seeing non-degenerated
745 if (!single_succ_p (bb))
747 BRANCH_EDGE (bb)->probability = combined_probability;
748 FALLTHRU_EDGE (bb)->probability
749 = REG_BR_PROB_BASE - combined_probability;
752 else if (!single_succ_p (bb))
754 int prob = INTVAL (XEXP (prob_note, 0));
756 BRANCH_EDGE (bb)->probability = prob;
757 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
760 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
763 /* Combine predictions into single probability and store them into CFG.
764 Remove now useless prediction entries. */
767 combine_predictions_for_bb (basic_block bb)
769 int best_probability = PROB_EVEN;
770 enum br_predictor best_predictor = END_PREDICTORS;
771 int combined_probability = REG_BR_PROB_BASE / 2;
773 bool first_match = false;
775 struct edge_prediction *pred;
777 edge e, first = NULL, second = NULL;
781 FOR_EACH_EDGE (e, ei, bb->succs)
782 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
785 if (first && !second)
791 /* When there is no successor or only one choice, prediction is easy.
793 We are lazy for now and predict only basic blocks with two outgoing
794 edges. It is possible to predict generic case too, but we have to
795 ignore first match heuristics and do more involved combining. Implement
800 set_even_probabilities (bb);
801 clear_bb_predictions (bb);
803 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
809 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
811 preds = pointer_map_contains (bb_predictions, bb);
814 /* We implement "first match" heuristics and use probability guessed
815 by predictor with smallest index. */
816 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
818 enum br_predictor predictor = pred->ep_predictor;
819 int probability = pred->ep_probability;
821 if (pred->ep_edge != first)
822 probability = REG_BR_PROB_BASE - probability;
825 /* First match heuristics would be widly confused if we predicted
827 if (best_predictor > predictor)
829 struct edge_prediction *pred2;
830 int prob = probability;
832 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
833 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
835 int probability2 = pred->ep_probability;
837 if (pred2->ep_edge != first)
838 probability2 = REG_BR_PROB_BASE - probability2;
840 if ((probability < REG_BR_PROB_BASE / 2) !=
841 (probability2 < REG_BR_PROB_BASE / 2))
844 /* If the same predictor later gave better result, go for it! */
845 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
846 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
850 best_probability = prob, best_predictor = predictor;
853 d = (combined_probability * probability
854 + (REG_BR_PROB_BASE - combined_probability)
855 * (REG_BR_PROB_BASE - probability));
857 /* Use FP math to avoid overflows of 32bit integers. */
859 /* If one probability is 0% and one 100%, avoid division by zero. */
860 combined_probability = REG_BR_PROB_BASE / 2;
862 combined_probability = (((double) combined_probability)
864 * REG_BR_PROB_BASE / d + 0.5);
868 /* Decide which heuristic to use. In case we didn't match anything,
869 use no_prediction heuristic, in case we did match, use either
870 first match or Dempster-Shaffer theory depending on the flags. */
872 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
876 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
879 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
881 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
886 combined_probability = best_probability;
887 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
891 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
893 enum br_predictor predictor = pred->ep_predictor;
894 int probability = pred->ep_probability;
896 if (pred->ep_edge != EDGE_SUCC (bb, 0))
897 probability = REG_BR_PROB_BASE - probability;
898 dump_prediction (dump_file, predictor, probability, bb,
899 !first_match || best_predictor == predictor);
902 clear_bb_predictions (bb);
906 first->probability = combined_probability;
907 second->probability = REG_BR_PROB_BASE - combined_probability;
911 /* Predict edge probabilities by exploiting loop structure. */
919 /* Try to predict out blocks in a loop that are not part of a
921 FOR_EACH_LOOP (li, loop, 0)
923 basic_block bb, *bbs;
925 VEC (edge, heap) *exits;
926 struct tree_niter_desc niter_desc;
929 exits = get_loop_exit_edges (loop);
930 n_exits = VEC_length (edge, exits);
932 for (j = 0; VEC_iterate (edge, exits, j, ex); j++)
935 HOST_WIDE_INT nitercst;
936 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
938 enum br_predictor predictor;
940 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
941 niter = niter_desc.niter;
942 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
943 niter = loop_niter_by_eval (loop, ex);
945 if (TREE_CODE (niter) == INTEGER_CST)
947 if (host_integerp (niter, 1)
948 && compare_tree_int (niter, max-1) == -1)
949 nitercst = tree_low_cst (niter, 1) + 1;
952 predictor = PRED_LOOP_ITERATIONS;
954 /* If we have just one exit and we can derive some information about
955 the number of iterations of the loop from the statements inside
956 the loop, use it to predict this exit. */
957 else if (n_exits == 1)
959 nitercst = estimated_loop_iterations_int (loop, false);
965 predictor = PRED_LOOP_ITERATIONS_GUESSED;
970 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
971 predict_edge (ex, predictor, probability);
973 VEC_free (edge, heap, exits);
975 bbs = get_loop_body (loop);
977 for (j = 0; j < loop->num_nodes; j++)
979 int header_found = 0;
985 /* Bypass loop heuristics on continue statement. These
986 statements construct loops via "non-loop" constructs
987 in the source language and are better to be handled
989 if (predicted_by_p (bb, PRED_CONTINUE))
992 /* Loop branch heuristics - predict an edge back to a
993 loop's head as taken. */
994 if (bb == loop->latch)
996 e = find_edge (loop->latch, loop->header);
1000 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1004 /* Loop exit heuristics - predict an edge exiting the loop if the
1005 conditional has no loop header successors as not taken. */
1007 /* If we already used more reliable loop exit predictors, do not
1008 bother with PRED_LOOP_EXIT. */
1009 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1010 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1012 /* For loop with many exits we don't want to predict all exits
1013 with the pretty large probability, because if all exits are
1014 considered in row, the loop would be predicted to iterate
1015 almost never. The code to divide probability by number of
1016 exits is very rough. It should compute the number of exits
1017 taken in each patch through function (not the overall number
1018 of exits that might be a lot higher for loops with wide switch
1019 statements in them) and compute n-th square root.
1021 We limit the minimal probability by 2% to avoid
1022 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1023 as this was causing regression in perl benchmark containing such
1026 int probability = ((REG_BR_PROB_BASE
1027 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1029 if (probability < HITRATE (2))
1030 probability = HITRATE (2);
1031 FOR_EACH_EDGE (e, ei, bb->succs)
1032 if (e->dest->index < NUM_FIXED_BLOCKS
1033 || !flow_bb_inside_loop_p (loop, e->dest))
1034 predict_edge (e, PRED_LOOP_EXIT, probability);
1038 /* Free basic blocks from get_loop_body. */
1043 /* Attempt to predict probabilities of BB outgoing edges using local
1046 bb_estimate_probability_locally (basic_block bb)
1048 rtx last_insn = BB_END (bb);
1051 if (! can_predict_insn_p (last_insn))
1053 cond = get_condition (last_insn, NULL, false, false);
1057 /* Try "pointer heuristic."
1058 A comparison ptr == 0 is predicted as false.
1059 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1060 if (COMPARISON_P (cond)
1061 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1062 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1064 if (GET_CODE (cond) == EQ)
1065 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1066 else if (GET_CODE (cond) == NE)
1067 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1071 /* Try "opcode heuristic."
1072 EQ tests are usually false and NE tests are usually true. Also,
1073 most quantities are positive, so we can make the appropriate guesses
1074 about signed comparisons against zero. */
1075 switch (GET_CODE (cond))
1078 /* Unconditional branch. */
1079 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1080 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1085 /* Floating point comparisons appears to behave in a very
1086 unpredictable way because of special role of = tests in
1088 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1090 /* Comparisons with 0 are often used for booleans and there is
1091 nothing useful to predict about them. */
1092 else if (XEXP (cond, 1) == const0_rtx
1093 || XEXP (cond, 0) == const0_rtx)
1096 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1101 /* Floating point comparisons appears to behave in a very
1102 unpredictable way because of special role of = tests in
1104 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1106 /* Comparisons with 0 are often used for booleans and there is
1107 nothing useful to predict about them. */
1108 else if (XEXP (cond, 1) == const0_rtx
1109 || XEXP (cond, 0) == const0_rtx)
1112 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1116 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1120 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1125 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1126 || XEXP (cond, 1) == constm1_rtx)
1127 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1132 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1133 || XEXP (cond, 1) == constm1_rtx)
1134 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1142 /* Set edge->probability for each successor edge of BB. */
1144 guess_outgoing_edge_probabilities (basic_block bb)
1146 bb_estimate_probability_locally (bb);
1147 combine_predictions_for_insn (BB_END (bb), bb);
1150 static tree expr_expected_value (tree, bitmap);
1152 /* Helper function for expr_expected_value. */
1155 expr_expected_value_1 (tree type, tree op0, enum tree_code code, tree op1, bitmap visited)
1159 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1161 if (TREE_CONSTANT (op0))
1164 if (code != SSA_NAME)
1167 def = SSA_NAME_DEF_STMT (op0);
1169 /* If we were already here, break the infinite cycle. */
1170 if (bitmap_bit_p (visited, SSA_NAME_VERSION (op0)))
1172 bitmap_set_bit (visited, SSA_NAME_VERSION (op0));
1174 if (gimple_code (def) == GIMPLE_PHI)
1176 /* All the arguments of the PHI node must have the same constant
1178 int i, n = gimple_phi_num_args (def);
1179 tree val = NULL, new_val;
1181 for (i = 0; i < n; i++)
1183 tree arg = PHI_ARG_DEF (def, i);
1185 /* If this PHI has itself as an argument, we cannot
1186 determine the string length of this argument. However,
1187 if we can find an expected constant value for the other
1188 PHI args then we can still be sure that this is
1189 likely a constant. So be optimistic and just
1190 continue with the next argument. */
1191 if (arg == PHI_RESULT (def))
1194 new_val = expr_expected_value (arg, visited);
1199 else if (!operand_equal_p (val, new_val, false))
1204 if (is_gimple_assign (def))
1206 if (gimple_assign_lhs (def) != op0)
1209 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1210 gimple_assign_rhs1 (def),
1211 gimple_assign_rhs_code (def),
1212 gimple_assign_rhs2 (def),
1216 if (is_gimple_call (def))
1218 tree decl = gimple_call_fndecl (def);
1221 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1222 && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
1226 if (gimple_call_num_args (def) != 2)
1228 val = gimple_call_arg (def, 0);
1229 if (TREE_CONSTANT (val))
1231 return gimple_call_arg (def, 1);
1238 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1241 op0 = expr_expected_value (op0, visited);
1244 op1 = expr_expected_value (op1, visited);
1247 res = fold_build2 (code, type, op0, op1);
1248 if (TREE_CONSTANT (res))
1252 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1255 op0 = expr_expected_value (op0, visited);
1258 res = fold_build1 (code, type, op0);
1259 if (TREE_CONSTANT (res))
1266 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1267 The function is used by builtin_expect branch predictor so the evidence
1268 must come from this construct and additional possible constant folding.
1270 We may want to implement more involved value guess (such as value range
1271 propagation based prediction), but such tricks shall go to new
1275 expr_expected_value (tree expr, bitmap visited)
1277 enum tree_code code;
1280 if (TREE_CONSTANT (expr))
1283 extract_ops_from_tree (expr, &code, &op0, &op1);
1284 return expr_expected_value_1 (TREE_TYPE (expr),
1285 op0, code, op1, visited);
1289 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1290 we no longer need. */
1292 strip_predict_hints (void)
1300 gimple_stmt_iterator bi;
1301 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1303 gimple stmt = gsi_stmt (bi);
1305 if (gimple_code (stmt) == GIMPLE_PREDICT)
1307 gsi_remove (&bi, true);
1310 else if (gimple_code (stmt) == GIMPLE_CALL)
1312 tree fndecl = gimple_call_fndecl (stmt);
1315 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1316 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1317 && gimple_call_num_args (stmt) == 2)
1319 var = gimple_call_lhs (stmt);
1320 ass_stmt = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1322 gsi_replace (&bi, ass_stmt, true);
1331 /* Predict using opcode of the last statement in basic block. */
1333 tree_predict_by_opcode (basic_block bb)
1335 gimple stmt = last_stmt (bb);
1344 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1346 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1347 if (then_edge->flags & EDGE_TRUE_VALUE)
1349 op0 = gimple_cond_lhs (stmt);
1350 op1 = gimple_cond_rhs (stmt);
1351 cmp = gimple_cond_code (stmt);
1352 type = TREE_TYPE (op0);
1353 visited = BITMAP_ALLOC (NULL);
1354 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1355 BITMAP_FREE (visited);
1358 if (integer_zerop (val))
1359 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1361 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1364 /* Try "pointer heuristic."
1365 A comparison ptr == 0 is predicted as false.
1366 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1367 if (POINTER_TYPE_P (type))
1370 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1371 else if (cmp == NE_EXPR)
1372 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1376 /* Try "opcode heuristic."
1377 EQ tests are usually false and NE tests are usually true. Also,
1378 most quantities are positive, so we can make the appropriate guesses
1379 about signed comparisons against zero. */
1384 /* Floating point comparisons appears to behave in a very
1385 unpredictable way because of special role of = tests in
1387 if (FLOAT_TYPE_P (type))
1389 /* Comparisons with 0 are often used for booleans and there is
1390 nothing useful to predict about them. */
1391 else if (integer_zerop (op0) || integer_zerop (op1))
1394 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1399 /* Floating point comparisons appears to behave in a very
1400 unpredictable way because of special role of = tests in
1402 if (FLOAT_TYPE_P (type))
1404 /* Comparisons with 0 are often used for booleans and there is
1405 nothing useful to predict about them. */
1406 else if (integer_zerop (op0)
1407 || integer_zerop (op1))
1410 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1414 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1417 case UNORDERED_EXPR:
1418 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1423 if (integer_zerop (op1)
1424 || integer_onep (op1)
1425 || integer_all_onesp (op1)
1428 || real_minus_onep (op1))
1429 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1434 if (integer_zerop (op1)
1435 || integer_onep (op1)
1436 || integer_all_onesp (op1)
1439 || real_minus_onep (op1))
1440 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1448 /* Try to guess whether the value of return means error code. */
1450 static enum br_predictor
1451 return_prediction (tree val, enum prediction *prediction)
1455 return PRED_NO_PREDICTION;
1456 /* Different heuristics for pointers and scalars. */
1457 if (POINTER_TYPE_P (TREE_TYPE (val)))
1459 /* NULL is usually not returned. */
1460 if (integer_zerop (val))
1462 *prediction = NOT_TAKEN;
1463 return PRED_NULL_RETURN;
1466 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1468 /* Negative return values are often used to indicate
1470 if (TREE_CODE (val) == INTEGER_CST
1471 && tree_int_cst_sgn (val) < 0)
1473 *prediction = NOT_TAKEN;
1474 return PRED_NEGATIVE_RETURN;
1476 /* Constant return values seems to be commonly taken.
1477 Zero/one often represent booleans so exclude them from the
1479 if (TREE_CONSTANT (val)
1480 && (!integer_zerop (val) && !integer_onep (val)))
1482 *prediction = TAKEN;
1483 return PRED_CONST_RETURN;
1486 return PRED_NO_PREDICTION;
1489 /* Find the basic block with return expression and look up for possible
1490 return value trying to apply RETURN_PREDICTION heuristics. */
1492 apply_return_prediction (void)
1494 gimple return_stmt = NULL;
1498 int phi_num_args, i;
1499 enum br_predictor pred;
1500 enum prediction direction;
1503 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1505 return_stmt = last_stmt (e->src);
1507 && gimple_code (return_stmt) == GIMPLE_RETURN)
1512 return_val = gimple_return_retval (return_stmt);
1515 if (TREE_CODE (return_val) != SSA_NAME
1516 || !SSA_NAME_DEF_STMT (return_val)
1517 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1519 phi = SSA_NAME_DEF_STMT (return_val);
1520 phi_num_args = gimple_phi_num_args (phi);
1521 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1523 /* Avoid the degenerate case where all return values form the function
1524 belongs to same category (ie they are all positive constants)
1525 so we can hardly say something about them. */
1526 for (i = 1; i < phi_num_args; i++)
1527 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1529 if (i != phi_num_args)
1530 for (i = 0; i < phi_num_args; i++)
1532 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1533 if (pred != PRED_NO_PREDICTION)
1534 predict_paths_leading_to (gimple_phi_arg_edge (phi, i)->src, pred,
1539 /* Look for basic block that contains unlikely to happen events
1540 (such as noreturn calls) and mark all paths leading to execution
1541 of this basic blocks as unlikely. */
1544 tree_bb_level_predictions (void)
1547 bool has_return_edges = false;
1551 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1552 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
1554 has_return_edges = true;
1558 apply_return_prediction ();
1562 gimple_stmt_iterator gsi;
1564 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1566 gimple stmt = gsi_stmt (gsi);
1569 if (is_gimple_call (stmt))
1571 if ((gimple_call_flags (stmt) & ECF_NORETURN)
1572 && has_return_edges)
1573 predict_paths_leading_to (bb, PRED_NORETURN,
1575 decl = gimple_call_fndecl (stmt);
1577 && lookup_attribute ("cold",
1578 DECL_ATTRIBUTES (decl)))
1579 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
1582 else if (gimple_code (stmt) == GIMPLE_PREDICT)
1584 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
1585 gimple_predict_outcome (stmt));
1586 /* Keep GIMPLE_PREDICT around so early inlining will propagate
1587 hints to callers. */
1593 #ifdef ENABLE_CHECKING
1595 /* Callback for pointer_map_traverse, asserts that the pointer map is
1599 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
1600 void *data ATTRIBUTE_UNUSED)
1602 gcc_assert (!*value);
1607 /* Predict branch probabilities and estimate profile for basic block BB. */
1610 tree_estimate_probability_bb (basic_block bb)
1616 FOR_EACH_EDGE (e, ei, bb->succs)
1618 /* Predict early returns to be probable, as we've already taken
1619 care for error returns and other cases are often used for
1620 fast paths through function.
1622 Since we've already removed the return statements, we are
1623 looking for CFG like:
1633 if (e->dest != bb->next_bb
1634 && e->dest != EXIT_BLOCK_PTR
1635 && single_succ_p (e->dest)
1636 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
1637 && (last = last_stmt (e->dest)) != NULL
1638 && gimple_code (last) == GIMPLE_RETURN)
1643 if (single_succ_p (bb))
1645 FOR_EACH_EDGE (e1, ei1, bb->preds)
1646 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1647 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1648 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
1649 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1652 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
1653 && !predicted_by_p (e->src, PRED_CONST_RETURN)
1654 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
1655 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1658 /* Look for block we are guarding (ie we dominate it,
1659 but it doesn't postdominate us). */
1660 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1661 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1662 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1664 gimple_stmt_iterator bi;
1666 /* The call heuristic claims that a guarded function call
1667 is improbable. This is because such calls are often used
1668 to signal exceptional situations such as printing error
1670 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
1673 gimple stmt = gsi_stmt (bi);
1674 if (is_gimple_call (stmt)
1675 /* Constant and pure calls are hardly used to signalize
1676 something exceptional. */
1677 && gimple_has_side_effects (stmt))
1679 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1685 tree_predict_by_opcode (bb);
1688 /* Predict branch probabilities and estimate profile of the tree CFG.
1689 This function can be called from the loop optimizers to recompute
1690 the profile information. */
1693 tree_estimate_probability (void)
1697 add_noreturn_fake_exit_edges ();
1698 connect_infinite_loops_to_exit ();
1699 /* We use loop_niter_by_eval, which requires that the loops have
1701 create_preheaders (CP_SIMPLE_PREHEADERS);
1702 calculate_dominance_info (CDI_POST_DOMINATORS);
1704 bb_predictions = pointer_map_create ();
1705 tree_bb_level_predictions ();
1706 record_loop_exits ();
1708 if (number_of_loops () > 1)
1712 tree_estimate_probability_bb (bb);
1715 combine_predictions_for_bb (bb);
1717 #ifdef ENABLE_CHECKING
1718 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
1720 pointer_map_destroy (bb_predictions);
1721 bb_predictions = NULL;
1723 estimate_bb_frequencies ();
1724 free_dominance_info (CDI_POST_DOMINATORS);
1725 remove_fake_exit_edges ();
1728 /* Predict branch probabilities and estimate profile of the tree CFG.
1729 This is the driver function for PASS_PROFILE. */
1732 tree_estimate_probability_driver (void)
1736 loop_optimizer_init (0);
1737 if (dump_file && (dump_flags & TDF_DETAILS))
1738 flow_loops_dump (dump_file, NULL, 0);
1740 mark_irreducible_loops ();
1742 nb_loops = number_of_loops ();
1746 tree_estimate_probability ();
1751 loop_optimizer_finalize ();
1752 if (dump_file && (dump_flags & TDF_DETAILS))
1753 gimple_dump_cfg (dump_file, dump_flags);
1754 if (profile_status == PROFILE_ABSENT)
1755 profile_status = PROFILE_GUESSED;
1759 /* Predict edges to successors of CUR whose sources are not postdominated by
1760 BB by PRED and recurse to all postdominators. */
1763 predict_paths_for_bb (basic_block cur, basic_block bb,
1764 enum br_predictor pred,
1765 enum prediction taken)
1771 /* We are looking for all edges forming edge cut induced by
1772 set of all blocks postdominated by BB. */
1773 FOR_EACH_EDGE (e, ei, cur->preds)
1774 if (e->src->index >= NUM_FIXED_BLOCKS
1775 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
1777 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
1778 predict_edge_def (e, pred, taken);
1780 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
1782 son = next_dom_son (CDI_POST_DOMINATORS, son))
1783 predict_paths_for_bb (son, bb, pred, taken);
1786 /* Sets branch probabilities according to PREDiction and
1790 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
1791 enum prediction taken)
1793 predict_paths_for_bb (bb, bb, pred, taken);
1796 /* This is used to carry information about basic blocks. It is
1797 attached to the AUX field of the standard CFG block. */
1799 typedef struct block_info_def
1801 /* Estimated frequency of execution of basic_block. */
1804 /* To keep queue of basic blocks to process. */
1807 /* Number of predecessors we need to visit first. */
1811 /* Similar information for edges. */
1812 typedef struct edge_info_def
1814 /* In case edge is a loopback edge, the probability edge will be reached
1815 in case header is. Estimated number of iterations of the loop can be
1816 then computed as 1 / (1 - back_edge_prob). */
1817 sreal back_edge_prob;
1818 /* True if the edge is a loopback edge in the natural loop. */
1819 unsigned int back_edge:1;
1822 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1823 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1825 /* Helper function for estimate_bb_frequencies.
1826 Propagate the frequencies in blocks marked in
1827 TOVISIT, starting in HEAD. */
1830 propagate_freq (basic_block head, bitmap tovisit)
1839 /* For each basic block we need to visit count number of his predecessors
1840 we need to visit first. */
1841 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
1846 /* The outermost "loop" includes the exit block, which we can not
1847 look up via BASIC_BLOCK. Detect this and use EXIT_BLOCK_PTR
1848 directly. Do the same for the entry block. */
1849 bb = BASIC_BLOCK (i);
1851 FOR_EACH_EDGE (e, ei, bb->preds)
1853 bool visit = bitmap_bit_p (tovisit, e->src->index);
1855 if (visit && !(e->flags & EDGE_DFS_BACK))
1857 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
1859 "Irreducible region hit, ignoring edge to %i->%i\n",
1860 e->src->index, bb->index);
1862 BLOCK_INFO (bb)->npredecessors = count;
1865 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1867 for (bb = head; bb; bb = nextbb)
1870 sreal cyclic_probability, frequency;
1872 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1873 memcpy (&frequency, &real_zero, sizeof (real_zero));
1875 nextbb = BLOCK_INFO (bb)->next;
1876 BLOCK_INFO (bb)->next = NULL;
1878 /* Compute frequency of basic block. */
1881 #ifdef ENABLE_CHECKING
1882 FOR_EACH_EDGE (e, ei, bb->preds)
1883 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
1884 || (e->flags & EDGE_DFS_BACK));
1887 FOR_EACH_EDGE (e, ei, bb->preds)
1888 if (EDGE_INFO (e)->back_edge)
1890 sreal_add (&cyclic_probability, &cyclic_probability,
1891 &EDGE_INFO (e)->back_edge_prob);
1893 else if (!(e->flags & EDGE_DFS_BACK))
1897 /* frequency += (e->probability
1898 * BLOCK_INFO (e->src)->frequency /
1899 REG_BR_PROB_BASE); */
1901 sreal_init (&tmp, e->probability, 0);
1902 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1903 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1904 sreal_add (&frequency, &frequency, &tmp);
1907 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1909 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1910 sizeof (frequency));
1914 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1916 memcpy (&cyclic_probability, &real_almost_one,
1917 sizeof (real_almost_one));
1920 /* BLOCK_INFO (bb)->frequency = frequency
1921 / (1 - cyclic_probability) */
1923 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1924 sreal_div (&BLOCK_INFO (bb)->frequency,
1925 &frequency, &cyclic_probability);
1929 bitmap_clear_bit (tovisit, bb->index);
1931 e = find_edge (bb, head);
1936 /* EDGE_INFO (e)->back_edge_prob
1937 = ((e->probability * BLOCK_INFO (bb)->frequency)
1938 / REG_BR_PROB_BASE); */
1940 sreal_init (&tmp, e->probability, 0);
1941 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1942 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1943 &tmp, &real_inv_br_prob_base);
1946 /* Propagate to successor blocks. */
1947 FOR_EACH_EDGE (e, ei, bb->succs)
1948 if (!(e->flags & EDGE_DFS_BACK)
1949 && BLOCK_INFO (e->dest)->npredecessors)
1951 BLOCK_INFO (e->dest)->npredecessors--;
1952 if (!BLOCK_INFO (e->dest)->npredecessors)
1957 BLOCK_INFO (last)->next = e->dest;
1965 /* Estimate probabilities of loopback edges in loops at same nest level. */
1968 estimate_loops_at_level (struct loop *first_loop)
1972 for (loop = first_loop; loop; loop = loop->next)
1977 bitmap tovisit = BITMAP_ALLOC (NULL);
1979 estimate_loops_at_level (loop->inner);
1981 /* Find current loop back edge and mark it. */
1982 e = loop_latch_edge (loop);
1983 EDGE_INFO (e)->back_edge = 1;
1985 bbs = get_loop_body (loop);
1986 for (i = 0; i < loop->num_nodes; i++)
1987 bitmap_set_bit (tovisit, bbs[i]->index);
1989 propagate_freq (loop->header, tovisit);
1990 BITMAP_FREE (tovisit);
1994 /* Propagates frequencies through structure of loops. */
1997 estimate_loops (void)
1999 bitmap tovisit = BITMAP_ALLOC (NULL);
2002 /* Start by estimating the frequencies in the loops. */
2003 if (number_of_loops () > 1)
2004 estimate_loops_at_level (current_loops->tree_root->inner);
2006 /* Now propagate the frequencies through all the blocks. */
2009 bitmap_set_bit (tovisit, bb->index);
2011 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2012 BITMAP_FREE (tovisit);
2015 /* Convert counts measured by profile driven feedback to frequencies.
2016 Return nonzero iff there was any nonzero execution count. */
2019 counts_to_freqs (void)
2021 gcov_type count_max, true_count_max = 0;
2025 true_count_max = MAX (bb->count, true_count_max);
2027 count_max = MAX (true_count_max, 1);
2028 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2029 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2031 return true_count_max;
2034 /* Return true if function is likely to be expensive, so there is no point to
2035 optimize performance of prologue, epilogue or do inlining at the expense
2036 of code size growth. THRESHOLD is the limit of number of instructions
2037 function can execute at average to be still considered not expensive. */
2040 expensive_function_p (int threshold)
2042 unsigned int sum = 0;
2046 /* We can not compute accurately for large thresholds due to scaled
2048 gcc_assert (threshold <= BB_FREQ_MAX);
2050 /* Frequencies are out of range. This either means that function contains
2051 internal loop executing more than BB_FREQ_MAX times or profile feedback
2052 is available and function has not been executed at all. */
2053 if (ENTRY_BLOCK_PTR->frequency == 0)
2056 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2057 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2062 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
2063 insn = NEXT_INSN (insn))
2064 if (active_insn_p (insn))
2066 sum += bb->frequency;
2075 /* Estimate basic blocks frequency by given branch probabilities. */
2078 estimate_bb_frequencies (void)
2083 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2085 static int real_values_initialized = 0;
2087 if (!real_values_initialized)
2089 real_values_initialized = 1;
2090 sreal_init (&real_zero, 0, 0);
2091 sreal_init (&real_one, 1, 0);
2092 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2093 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2094 sreal_init (&real_one_half, 1, -1);
2095 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2096 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2099 mark_dfs_back_edges ();
2101 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2103 /* Set up block info for each basic block. */
2104 alloc_aux_for_blocks (sizeof (struct block_info_def));
2105 alloc_aux_for_edges (sizeof (struct edge_info_def));
2106 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2111 FOR_EACH_EDGE (e, ei, bb->succs)
2113 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2114 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2115 &EDGE_INFO (e)->back_edge_prob,
2116 &real_inv_br_prob_base);
2120 /* First compute probabilities locally for each loop from innermost
2121 to outermost to examine probabilities for back edges. */
2124 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2126 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2127 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2129 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2130 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2134 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2135 sreal_add (&tmp, &tmp, &real_one_half);
2136 bb->frequency = sreal_to_int (&tmp);
2139 free_aux_for_blocks ();
2140 free_aux_for_edges ();
2142 compute_function_frequency ();
2143 if (flag_reorder_functions)
2144 choose_function_section ();
2147 /* Decide whether function is hot, cold or unlikely executed. */
2149 compute_function_frequency (void)
2153 if (!profile_info || !flag_branch_probabilities)
2155 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2157 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
2158 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2160 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2163 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
2166 if (maybe_hot_bb_p (bb))
2168 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2171 if (!probably_never_executed_bb_p (bb))
2172 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
2176 /* Choose appropriate section for the function. */
2178 choose_function_section (void)
2180 if (DECL_SECTION_NAME (current_function_decl)
2181 || !targetm.have_named_sections
2182 /* Theoretically we can split the gnu.linkonce text section too,
2183 but this requires more work as the frequency needs to match
2184 for all generated objects so we need to merge the frequency
2185 of all instances. For now just never set frequency for these. */
2186 || DECL_ONE_ONLY (current_function_decl))
2189 /* If we are doing the partitioning optimization, let the optimization
2190 choose the correct section into which to put things. */
2192 if (flag_reorder_blocks_and_partition)
2195 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
2196 DECL_SECTION_NAME (current_function_decl) =
2197 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
2198 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
2199 DECL_SECTION_NAME (current_function_decl) =
2200 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
2201 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
2205 gate_estimate_probability (void)
2207 return flag_guess_branch_prob;
2210 /* Build PREDICT_EXPR. */
2212 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2214 tree t = build1 (PREDICT_EXPR, void_type_node,
2215 build_int_cst (NULL, predictor));
2216 SET_PREDICT_EXPR_OUTCOME (t, taken);
2221 predictor_name (enum br_predictor predictor)
2223 return predictor_info[predictor].name;
2226 struct gimple_opt_pass pass_profile =
2230 "profile", /* name */
2231 gate_estimate_probability, /* gate */
2232 tree_estimate_probability_driver, /* execute */
2235 0, /* static_pass_number */
2236 TV_BRANCH_PROB, /* tv_id */
2237 PROP_cfg, /* properties_required */
2238 0, /* properties_provided */
2239 0, /* properties_destroyed */
2240 0, /* todo_flags_start */
2241 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2245 struct gimple_opt_pass pass_strip_predict_hints =
2251 strip_predict_hints, /* execute */
2254 0, /* static_pass_number */
2255 TV_BRANCH_PROB, /* tv_id */
2256 PROP_cfg, /* properties_required */
2257 0, /* properties_provided */
2258 0, /* properties_destroyed */
2259 0, /* todo_flags_start */
2260 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */