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
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_MAX
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 int 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 int predictor
= INTVAL (XEXP (XEXP (note
, 0), 0));
681 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
684 if (best_predictor
> predictor
)
685 best_probability
= probability
, best_predictor
= predictor
;
687 d
= (combined_probability
* probability
688 + (REG_BR_PROB_BASE
- combined_probability
)
689 * (REG_BR_PROB_BASE
- probability
));
691 /* Use FP math to avoid overflows of 32bit integers. */
693 /* If one probability is 0% and one 100%, avoid division by zero. */
694 combined_probability
= REG_BR_PROB_BASE
/ 2;
696 combined_probability
= (((double) combined_probability
) * probability
697 * REG_BR_PROB_BASE
/ d
+ 0.5);
700 /* Decide which heuristic to use. In case we didn't match anything,
701 use no_prediction heuristic, in case we did match, use either
702 first match or Dempster-Shaffer theory depending on the flags. */
704 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
708 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
709 combined_probability
, bb
, true);
712 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
714 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
719 combined_probability
= best_probability
;
720 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
724 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
726 int predictor
= INTVAL (XEXP (XEXP (*pnote
, 0), 0));
727 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
729 dump_prediction (dump_file
, predictor
, probability
, bb
,
730 !first_match
|| best_predictor
== predictor
);
731 *pnote
= XEXP (*pnote
, 1);
734 pnote
= &XEXP (*pnote
, 1);
739 add_reg_note (insn
, REG_BR_PROB
, GEN_INT (combined_probability
));
741 /* Save the prediction into CFG in case we are seeing non-degenerated
743 if (!single_succ_p (bb
))
745 BRANCH_EDGE (bb
)->probability
= combined_probability
;
746 FALLTHRU_EDGE (bb
)->probability
747 = REG_BR_PROB_BASE
- combined_probability
;
750 else if (!single_succ_p (bb
))
752 int prob
= INTVAL (XEXP (prob_note
, 0));
754 BRANCH_EDGE (bb
)->probability
= prob
;
755 FALLTHRU_EDGE (bb
)->probability
= REG_BR_PROB_BASE
- prob
;
758 single_succ_edge (bb
)->probability
= REG_BR_PROB_BASE
;
761 /* Combine predictions into single probability and store them into CFG.
762 Remove now useless prediction entries. */
765 combine_predictions_for_bb (basic_block bb
)
767 int best_probability
= PROB_EVEN
;
768 int best_predictor
= END_PREDICTORS
;
769 int combined_probability
= REG_BR_PROB_BASE
/ 2;
771 bool first_match
= false;
773 struct edge_prediction
*pred
;
775 edge e
, first
= NULL
, second
= NULL
;
779 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
780 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
783 if (first
&& !second
)
789 /* When there is no successor or only one choice, prediction is easy.
791 We are lazy for now and predict only basic blocks with two outgoing
792 edges. It is possible to predict generic case too, but we have to
793 ignore first match heuristics and do more involved combining. Implement
798 set_even_probabilities (bb
);
799 clear_bb_predictions (bb
);
801 fprintf (dump_file
, "%i edges in bb %i predicted to even probabilities\n",
807 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
809 preds
= pointer_map_contains (bb_predictions
, bb
);
812 /* We implement "first match" heuristics and use probability guessed
813 by predictor with smallest index. */
814 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
816 int predictor
= pred
->ep_predictor
;
817 int probability
= pred
->ep_probability
;
819 if (pred
->ep_edge
!= first
)
820 probability
= REG_BR_PROB_BASE
- probability
;
823 if (best_predictor
> predictor
)
824 best_probability
= probability
, best_predictor
= predictor
;
826 d
= (combined_probability
* probability
827 + (REG_BR_PROB_BASE
- combined_probability
)
828 * (REG_BR_PROB_BASE
- probability
));
830 /* Use FP math to avoid overflows of 32bit integers. */
832 /* If one probability is 0% and one 100%, avoid division by zero. */
833 combined_probability
= REG_BR_PROB_BASE
/ 2;
835 combined_probability
= (((double) combined_probability
)
837 * REG_BR_PROB_BASE
/ d
+ 0.5);
841 /* Decide which heuristic to use. In case we didn't match anything,
842 use no_prediction heuristic, in case we did match, use either
843 first match or Dempster-Shaffer theory depending on the flags. */
845 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
849 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
, true);
852 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
854 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
859 combined_probability
= best_probability
;
860 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
864 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
866 int predictor
= pred
->ep_predictor
;
867 int probability
= pred
->ep_probability
;
869 if (pred
->ep_edge
!= EDGE_SUCC (bb
, 0))
870 probability
= REG_BR_PROB_BASE
- probability
;
871 dump_prediction (dump_file
, predictor
, probability
, bb
,
872 !first_match
|| best_predictor
== predictor
);
875 clear_bb_predictions (bb
);
879 first
->probability
= combined_probability
;
880 second
->probability
= REG_BR_PROB_BASE
- combined_probability
;
884 /* Predict edge probabilities by exploiting loop structure. */
894 /* Try to predict out blocks in a loop that are not part of a
896 FOR_EACH_LOOP (li
, loop
, 0)
898 basic_block bb
, *bbs
;
900 VEC (edge
, heap
) *exits
;
901 struct tree_niter_desc niter_desc
;
904 exits
= get_loop_exit_edges (loop
);
905 n_exits
= VEC_length (edge
, exits
);
907 for (j
= 0; VEC_iterate (edge
, exits
, j
, ex
); j
++)
910 HOST_WIDE_INT nitercst
;
911 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
913 enum br_predictor predictor
;
915 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false))
916 niter
= niter_desc
.niter
;
917 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
918 niter
= loop_niter_by_eval (loop
, ex
);
920 if (TREE_CODE (niter
) == INTEGER_CST
)
922 if (host_integerp (niter
, 1)
923 && compare_tree_int (niter
, max
-1) == -1)
924 nitercst
= tree_low_cst (niter
, 1) + 1;
927 predictor
= PRED_LOOP_ITERATIONS
;
929 /* If we have just one exit and we can derive some information about
930 the number of iterations of the loop from the statements inside
931 the loop, use it to predict this exit. */
932 else if (n_exits
== 1)
934 nitercst
= estimated_loop_iterations_int (loop
, false);
940 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
945 probability
= ((REG_BR_PROB_BASE
+ nitercst
/ 2) / nitercst
);
946 predict_edge (ex
, predictor
, probability
);
948 VEC_free (edge
, heap
, exits
);
950 bbs
= get_loop_body (loop
);
952 for (j
= 0; j
< loop
->num_nodes
; j
++)
954 int header_found
= 0;
960 /* Bypass loop heuristics on continue statement. These
961 statements construct loops via "non-loop" constructs
962 in the source language and are better to be handled
964 if (predicted_by_p (bb
, PRED_CONTINUE
))
967 /* Loop branch heuristics - predict an edge back to a
968 loop's head as taken. */
969 if (bb
== loop
->latch
)
971 e
= find_edge (loop
->latch
, loop
->header
);
975 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
979 /* Loop exit heuristics - predict an edge exiting the loop if the
980 conditional has no loop header successors as not taken. */
982 /* If we already used more reliable loop exit predictors, do not
983 bother with PRED_LOOP_EXIT. */
984 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
985 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS
))
987 /* For loop with many exits we don't want to predict all exits
988 with the pretty large probability, because if all exits are
989 considered in row, the loop would be predicted to iterate
990 almost never. The code to divide probability by number of
991 exits is very rough. It should compute the number of exits
992 taken in each patch through function (not the overall number
993 of exits that might be a lot higher for loops with wide switch
994 statements in them) and compute n-th square root.
996 We limit the minimal probability by 2% to avoid
997 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
998 as this was causing regression in perl benchmark containing such
1001 int probability
= ((REG_BR_PROB_BASE
1002 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
1004 if (probability
< HITRATE (2))
1005 probability
= HITRATE (2);
1006 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1007 if (e
->dest
->index
< NUM_FIXED_BLOCKS
1008 || !flow_bb_inside_loop_p (loop
, e
->dest
))
1009 predict_edge (e
, PRED_LOOP_EXIT
, probability
);
1013 /* Free basic blocks from get_loop_body. */
1020 /* Attempt to predict probabilities of BB outgoing edges using local
1023 bb_estimate_probability_locally (basic_block bb
)
1025 rtx last_insn
= BB_END (bb
);
1028 if (! can_predict_insn_p (last_insn
))
1030 cond
= get_condition (last_insn
, NULL
, false, false);
1034 /* Try "pointer heuristic."
1035 A comparison ptr == 0 is predicted as false.
1036 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1037 if (COMPARISON_P (cond
)
1038 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
1039 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
1041 if (GET_CODE (cond
) == EQ
)
1042 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
1043 else if (GET_CODE (cond
) == NE
)
1044 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
1048 /* Try "opcode heuristic."
1049 EQ tests are usually false and NE tests are usually true. Also,
1050 most quantities are positive, so we can make the appropriate guesses
1051 about signed comparisons against zero. */
1052 switch (GET_CODE (cond
))
1055 /* Unconditional branch. */
1056 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
1057 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
1062 /* Floating point comparisons appears to behave in a very
1063 unpredictable way because of special role of = tests in
1065 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1067 /* Comparisons with 0 are often used for booleans and there is
1068 nothing useful to predict about them. */
1069 else if (XEXP (cond
, 1) == const0_rtx
1070 || XEXP (cond
, 0) == const0_rtx
)
1073 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
1078 /* Floating point comparisons appears to behave in a very
1079 unpredictable way because of special role of = tests in
1081 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1083 /* Comparisons with 0 are often used for booleans and there is
1084 nothing useful to predict about them. */
1085 else if (XEXP (cond
, 1) == const0_rtx
1086 || XEXP (cond
, 0) == const0_rtx
)
1089 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
1093 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
1097 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
1102 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1103 || XEXP (cond
, 1) == constm1_rtx
)
1104 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
1109 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1110 || XEXP (cond
, 1) == constm1_rtx
)
1111 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
1119 /* Set edge->probability for each successor edge of BB. */
1121 guess_outgoing_edge_probabilities (basic_block bb
)
1123 bb_estimate_probability_locally (bb
);
1124 combine_predictions_for_insn (BB_END (bb
), bb
);
1127 static tree
expr_expected_value (tree
, bitmap
);
1129 /* Helper function for expr_expected_value. */
1132 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
, tree op1
, bitmap visited
)
1136 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1138 if (TREE_CONSTANT (op0
))
1141 if (code
!= SSA_NAME
)
1144 def
= SSA_NAME_DEF_STMT (op0
);
1146 /* If we were already here, break the infinite cycle. */
1147 if (bitmap_bit_p (visited
, SSA_NAME_VERSION (op0
)))
1149 bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
));
1151 if (gimple_code (def
) == GIMPLE_PHI
)
1153 /* All the arguments of the PHI node must have the same constant
1155 int i
, n
= gimple_phi_num_args (def
);
1156 tree val
= NULL
, new_val
;
1158 for (i
= 0; i
< n
; i
++)
1160 tree arg
= PHI_ARG_DEF (def
, i
);
1162 /* If this PHI has itself as an argument, we cannot
1163 determine the string length of this argument. However,
1164 if we can find an expected constant value for the other
1165 PHI args then we can still be sure that this is
1166 likely a constant. So be optimistic and just
1167 continue with the next argument. */
1168 if (arg
== PHI_RESULT (def
))
1171 new_val
= expr_expected_value (arg
, visited
);
1176 else if (!operand_equal_p (val
, new_val
, false))
1181 if (is_gimple_assign (def
))
1183 if (gimple_assign_lhs (def
) != op0
)
1186 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
1187 gimple_assign_rhs1 (def
),
1188 gimple_assign_rhs_code (def
),
1189 gimple_assign_rhs2 (def
),
1193 if (is_gimple_call (def
))
1195 tree decl
= gimple_call_fndecl (def
);
1198 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
1199 && DECL_FUNCTION_CODE (decl
) == BUILT_IN_EXPECT
)
1203 if (gimple_call_num_args (def
) != 2)
1205 val
= gimple_call_arg (def
, 0);
1206 if (TREE_CONSTANT (val
))
1208 return gimple_call_arg (def
, 1);
1215 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
1218 op0
= expr_expected_value (op0
, visited
);
1221 op1
= expr_expected_value (op1
, visited
);
1224 res
= fold_build2 (code
, type
, op0
, op1
);
1225 if (TREE_CONSTANT (res
))
1229 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
1232 op0
= expr_expected_value (op0
, visited
);
1235 res
= fold_build1 (code
, type
, op0
);
1236 if (TREE_CONSTANT (res
))
1243 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1244 The function is used by builtin_expect branch predictor so the evidence
1245 must come from this construct and additional possible constant folding.
1247 We may want to implement more involved value guess (such as value range
1248 propagation based prediction), but such tricks shall go to new
1252 expr_expected_value (tree expr
, bitmap visited
)
1254 enum tree_code code
;
1257 if (TREE_CONSTANT (expr
))
1260 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1261 return expr_expected_value_1 (TREE_TYPE (expr
),
1262 op0
, code
, op1
, visited
);
1266 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1267 we no longer need. */
1269 strip_predict_hints (void)
1277 gimple_stmt_iterator bi
;
1278 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
);)
1280 gimple stmt
= gsi_stmt (bi
);
1282 if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1284 gsi_remove (&bi
, true);
1287 else if (gimple_code (stmt
) == GIMPLE_CALL
)
1289 tree fndecl
= gimple_call_fndecl (stmt
);
1292 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1293 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
1294 && gimple_call_num_args (stmt
) == 2)
1296 var
= gimple_call_lhs (stmt
);
1297 ass_stmt
= gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
1299 gsi_replace (&bi
, ass_stmt
, true);
1308 /* Predict using opcode of the last statement in basic block. */
1310 tree_predict_by_opcode (basic_block bb
)
1312 gimple stmt
= last_stmt (bb
);
1321 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1323 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1324 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1326 op0
= gimple_cond_lhs (stmt
);
1327 op1
= gimple_cond_rhs (stmt
);
1328 cmp
= gimple_cond_code (stmt
);
1329 type
= TREE_TYPE (op0
);
1330 visited
= BITMAP_ALLOC (NULL
);
1331 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, visited
);
1332 BITMAP_FREE (visited
);
1335 if (integer_zerop (val
))
1336 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, NOT_TAKEN
);
1338 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, TAKEN
);
1341 /* Try "pointer heuristic."
1342 A comparison ptr == 0 is predicted as false.
1343 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1344 if (POINTER_TYPE_P (type
))
1347 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
1348 else if (cmp
== NE_EXPR
)
1349 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
1353 /* Try "opcode heuristic."
1354 EQ tests are usually false and NE tests are usually true. Also,
1355 most quantities are positive, so we can make the appropriate guesses
1356 about signed comparisons against zero. */
1361 /* Floating point comparisons appears to behave in a very
1362 unpredictable way because of special role of = tests in
1364 if (FLOAT_TYPE_P (type
))
1366 /* Comparisons with 0 are often used for booleans and there is
1367 nothing useful to predict about them. */
1368 else if (integer_zerop (op0
) || integer_zerop (op1
))
1371 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
1376 /* Floating point comparisons appears to behave in a very
1377 unpredictable way because of special role of = tests in
1379 if (FLOAT_TYPE_P (type
))
1381 /* Comparisons with 0 are often used for booleans and there is
1382 nothing useful to predict about them. */
1383 else if (integer_zerop (op0
)
1384 || integer_zerop (op1
))
1387 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
1391 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
1394 case UNORDERED_EXPR
:
1395 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
1400 if (integer_zerop (op1
)
1401 || integer_onep (op1
)
1402 || integer_all_onesp (op1
)
1405 || real_minus_onep (op1
))
1406 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
1411 if (integer_zerop (op1
)
1412 || integer_onep (op1
)
1413 || integer_all_onesp (op1
)
1416 || real_minus_onep (op1
))
1417 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
1425 /* Try to guess whether the value of return means error code. */
1427 static enum br_predictor
1428 return_prediction (tree val
, enum prediction
*prediction
)
1432 return PRED_NO_PREDICTION
;
1433 /* Different heuristics for pointers and scalars. */
1434 if (POINTER_TYPE_P (TREE_TYPE (val
)))
1436 /* NULL is usually not returned. */
1437 if (integer_zerop (val
))
1439 *prediction
= NOT_TAKEN
;
1440 return PRED_NULL_RETURN
;
1443 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
1445 /* Negative return values are often used to indicate
1447 if (TREE_CODE (val
) == INTEGER_CST
1448 && tree_int_cst_sgn (val
) < 0)
1450 *prediction
= NOT_TAKEN
;
1451 return PRED_NEGATIVE_RETURN
;
1453 /* Constant return values seems to be commonly taken.
1454 Zero/one often represent booleans so exclude them from the
1456 if (TREE_CONSTANT (val
)
1457 && (!integer_zerop (val
) && !integer_onep (val
)))
1459 *prediction
= TAKEN
;
1460 return PRED_CONST_RETURN
;
1463 return PRED_NO_PREDICTION
;
1466 /* Find the basic block with return expression and look up for possible
1467 return value trying to apply RETURN_PREDICTION heuristics. */
1469 apply_return_prediction (void)
1471 gimple return_stmt
= NULL
;
1475 int phi_num_args
, i
;
1476 enum br_predictor pred
;
1477 enum prediction direction
;
1480 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
1482 return_stmt
= last_stmt (e
->src
);
1484 && gimple_code (return_stmt
) == GIMPLE_RETURN
)
1489 return_val
= gimple_return_retval (return_stmt
);
1492 if (TREE_CODE (return_val
) != SSA_NAME
1493 || !SSA_NAME_DEF_STMT (return_val
)
1494 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
1496 phi
= SSA_NAME_DEF_STMT (return_val
);
1497 phi_num_args
= gimple_phi_num_args (phi
);
1498 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
1500 /* Avoid the degenerate case where all return values form the function
1501 belongs to same category (ie they are all positive constants)
1502 so we can hardly say something about them. */
1503 for (i
= 1; i
< phi_num_args
; i
++)
1504 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
1506 if (i
!= phi_num_args
)
1507 for (i
= 0; i
< phi_num_args
; i
++)
1509 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
1510 if (pred
!= PRED_NO_PREDICTION
)
1511 predict_paths_leading_to (gimple_phi_arg_edge (phi
, i
)->src
, pred
,
1516 /* Look for basic block that contains unlikely to happen events
1517 (such as noreturn calls) and mark all paths leading to execution
1518 of this basic blocks as unlikely. */
1521 tree_bb_level_predictions (void)
1525 apply_return_prediction ();
1529 gimple_stmt_iterator gsi
;
1531 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
1533 gimple stmt
= gsi_stmt (gsi
);
1536 if (is_gimple_call (stmt
))
1538 if (gimple_call_flags (stmt
) & ECF_NORETURN
)
1539 predict_paths_leading_to (bb
, PRED_NORETURN
,
1541 decl
= gimple_call_fndecl (stmt
);
1543 && lookup_attribute ("cold",
1544 DECL_ATTRIBUTES (decl
)))
1545 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
1548 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1550 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
1551 gimple_predict_outcome (stmt
));
1552 /* Keep GIMPLE_PREDICT around so early inlining will propagate
1553 hints to callers. */
1559 #ifdef ENABLE_CHECKING
1561 /* Callback for pointer_map_traverse, asserts that the pointer map is
1565 assert_is_empty (const void *key ATTRIBUTE_UNUSED
, void **value
,
1566 void *data ATTRIBUTE_UNUSED
)
1568 gcc_assert (!*value
);
1573 /* Predict branch probabilities and estimate profile of the tree CFG. */
1575 tree_estimate_probability (void)
1579 loop_optimizer_init (0);
1580 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1581 flow_loops_dump (dump_file
, NULL
, 0);
1583 add_noreturn_fake_exit_edges ();
1584 connect_infinite_loops_to_exit ();
1585 /* We use loop_niter_by_eval, which requires that the loops have
1587 create_preheaders (CP_SIMPLE_PREHEADERS
);
1588 calculate_dominance_info (CDI_POST_DOMINATORS
);
1590 bb_predictions
= pointer_map_create ();
1591 tree_bb_level_predictions ();
1593 mark_irreducible_loops ();
1594 record_loop_exits ();
1595 if (number_of_loops () > 1)
1603 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1605 /* Predict early returns to be probable, as we've already taken
1606 care for error returns and other cases are often used for
1607 fast paths through function.
1609 Since we've already removed the return statements, we are
1610 looking for CFG like:
1620 if (e
->dest
!= bb
->next_bb
1621 && e
->dest
!= EXIT_BLOCK_PTR
1622 && single_succ_p (e
->dest
)
1623 && single_succ_edge (e
->dest
)->dest
== EXIT_BLOCK_PTR
1624 && gimple_code (last_stmt (e
->dest
)) == GIMPLE_RETURN
)
1629 if (single_succ_p (bb
))
1631 FOR_EACH_EDGE (e1
, ei1
, bb
->preds
)
1632 if (!predicted_by_p (e1
->src
, PRED_NULL_RETURN
)
1633 && !predicted_by_p (e1
->src
, PRED_CONST_RETURN
)
1634 && !predicted_by_p (e1
->src
, PRED_NEGATIVE_RETURN
))
1635 predict_edge_def (e1
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
1638 if (!predicted_by_p (e
->src
, PRED_NULL_RETURN
)
1639 && !predicted_by_p (e
->src
, PRED_CONST_RETURN
)
1640 && !predicted_by_p (e
->src
, PRED_NEGATIVE_RETURN
))
1641 predict_edge_def (e
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
1644 /* Look for block we are guarding (ie we dominate it,
1645 but it doesn't postdominate us). */
1646 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
1647 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
1648 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
1650 gimple_stmt_iterator bi
;
1652 /* The call heuristic claims that a guarded function call
1653 is improbable. This is because such calls are often used
1654 to signal exceptional situations such as printing error
1656 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
1659 gimple stmt
= gsi_stmt (bi
);
1660 if (is_gimple_call (stmt
)
1661 /* Constant and pure calls are hardly used to signalize
1662 something exceptional. */
1663 && gimple_has_side_effects (stmt
))
1665 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
1671 tree_predict_by_opcode (bb
);
1674 combine_predictions_for_bb (bb
);
1676 #ifdef ENABLE_CHECKING
1677 pointer_map_traverse (bb_predictions
, assert_is_empty
, NULL
);
1679 pointer_map_destroy (bb_predictions
);
1680 bb_predictions
= NULL
;
1682 estimate_bb_frequencies ();
1683 free_dominance_info (CDI_POST_DOMINATORS
);
1684 remove_fake_exit_edges ();
1685 loop_optimizer_finalize ();
1686 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1687 gimple_dump_cfg (dump_file
, dump_flags
);
1688 if (profile_status
== PROFILE_ABSENT
)
1689 profile_status
= PROFILE_GUESSED
;
1693 /* Predict edges to successors of CUR whose sources are not postdominated by
1694 BB by PRED and recurse to all postdominators. */
1697 predict_paths_for_bb (basic_block cur
, basic_block bb
,
1698 enum br_predictor pred
,
1699 enum prediction taken
)
1705 /* We are looking for all edges forming edge cut induced by
1706 set of all blocks postdominated by BB. */
1707 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
1708 if (e
->src
->index
>= NUM_FIXED_BLOCKS
1709 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
1711 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
1712 predict_edge_def (e
, pred
, taken
);
1714 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
1716 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
1717 predict_paths_for_bb (son
, bb
, pred
, taken
);
1720 /* Sets branch probabilities according to PREDiction and
1724 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
1725 enum prediction taken
)
1727 predict_paths_for_bb (bb
, bb
, pred
, taken
);
1730 /* This is used to carry information about basic blocks. It is
1731 attached to the AUX field of the standard CFG block. */
1733 typedef struct block_info_def
1735 /* Estimated frequency of execution of basic_block. */
1738 /* To keep queue of basic blocks to process. */
1741 /* Number of predecessors we need to visit first. */
1745 /* Similar information for edges. */
1746 typedef struct edge_info_def
1748 /* In case edge is a loopback edge, the probability edge will be reached
1749 in case header is. Estimated number of iterations of the loop can be
1750 then computed as 1 / (1 - back_edge_prob). */
1751 sreal back_edge_prob
;
1752 /* True if the edge is a loopback edge in the natural loop. */
1753 unsigned int back_edge
:1;
1756 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1757 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1759 /* Helper function for estimate_bb_frequencies.
1760 Propagate the frequencies in blocks marked in
1761 TOVISIT, starting in HEAD. */
1764 propagate_freq (basic_block head
, bitmap tovisit
)
1773 /* For each basic block we need to visit count number of his predecessors
1774 we need to visit first. */
1775 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
1780 /* The outermost "loop" includes the exit block, which we can not
1781 look up via BASIC_BLOCK. Detect this and use EXIT_BLOCK_PTR
1782 directly. Do the same for the entry block. */
1783 bb
= BASIC_BLOCK (i
);
1785 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1787 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
1789 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
1791 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
1793 "Irreducible region hit, ignoring edge to %i->%i\n",
1794 e
->src
->index
, bb
->index
);
1796 BLOCK_INFO (bb
)->npredecessors
= count
;
1799 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
1801 for (bb
= head
; bb
; bb
= nextbb
)
1804 sreal cyclic_probability
, frequency
;
1806 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
1807 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
1809 nextbb
= BLOCK_INFO (bb
)->next
;
1810 BLOCK_INFO (bb
)->next
= NULL
;
1812 /* Compute frequency of basic block. */
1815 #ifdef ENABLE_CHECKING
1816 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1817 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
1818 || (e
->flags
& EDGE_DFS_BACK
));
1821 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
1822 if (EDGE_INFO (e
)->back_edge
)
1824 sreal_add (&cyclic_probability
, &cyclic_probability
,
1825 &EDGE_INFO (e
)->back_edge_prob
);
1827 else if (!(e
->flags
& EDGE_DFS_BACK
))
1831 /* frequency += (e->probability
1832 * BLOCK_INFO (e->src)->frequency /
1833 REG_BR_PROB_BASE); */
1835 sreal_init (&tmp
, e
->probability
, 0);
1836 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
1837 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
1838 sreal_add (&frequency
, &frequency
, &tmp
);
1841 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
1843 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
1844 sizeof (frequency
));
1848 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
1850 memcpy (&cyclic_probability
, &real_almost_one
,
1851 sizeof (real_almost_one
));
1854 /* BLOCK_INFO (bb)->frequency = frequency
1855 / (1 - cyclic_probability) */
1857 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
1858 sreal_div (&BLOCK_INFO (bb
)->frequency
,
1859 &frequency
, &cyclic_probability
);
1863 bitmap_clear_bit (tovisit
, bb
->index
);
1865 e
= find_edge (bb
, head
);
1870 /* EDGE_INFO (e)->back_edge_prob
1871 = ((e->probability * BLOCK_INFO (bb)->frequency)
1872 / REG_BR_PROB_BASE); */
1874 sreal_init (&tmp
, e
->probability
, 0);
1875 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
1876 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
1877 &tmp
, &real_inv_br_prob_base
);
1880 /* Propagate to successor blocks. */
1881 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1882 if (!(e
->flags
& EDGE_DFS_BACK
)
1883 && BLOCK_INFO (e
->dest
)->npredecessors
)
1885 BLOCK_INFO (e
->dest
)->npredecessors
--;
1886 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
1891 BLOCK_INFO (last
)->next
= e
->dest
;
1899 /* Estimate probabilities of loopback edges in loops at same nest level. */
1902 estimate_loops_at_level (struct loop
*first_loop
)
1906 for (loop
= first_loop
; loop
; loop
= loop
->next
)
1911 bitmap tovisit
= BITMAP_ALLOC (NULL
);
1913 estimate_loops_at_level (loop
->inner
);
1915 /* Find current loop back edge and mark it. */
1916 e
= loop_latch_edge (loop
);
1917 EDGE_INFO (e
)->back_edge
= 1;
1919 bbs
= get_loop_body (loop
);
1920 for (i
= 0; i
< loop
->num_nodes
; i
++)
1921 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
1923 propagate_freq (loop
->header
, tovisit
);
1924 BITMAP_FREE (tovisit
);
1928 /* Propagates frequencies through structure of loops. */
1931 estimate_loops (void)
1933 bitmap tovisit
= BITMAP_ALLOC (NULL
);
1936 /* Start by estimating the frequencies in the loops. */
1937 if (number_of_loops () > 1)
1938 estimate_loops_at_level (current_loops
->tree_root
->inner
);
1940 /* Now propagate the frequencies through all the blocks. */
1943 bitmap_set_bit (tovisit
, bb
->index
);
1945 propagate_freq (ENTRY_BLOCK_PTR
, tovisit
);
1946 BITMAP_FREE (tovisit
);
1949 /* Convert counts measured by profile driven feedback to frequencies.
1950 Return nonzero iff there was any nonzero execution count. */
1953 counts_to_freqs (void)
1955 gcov_type count_max
, true_count_max
= 0;
1959 true_count_max
= MAX (bb
->count
, true_count_max
);
1961 count_max
= MAX (true_count_max
, 1);
1962 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
1963 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
1965 return true_count_max
;
1968 /* Return true if function is likely to be expensive, so there is no point to
1969 optimize performance of prologue, epilogue or do inlining at the expense
1970 of code size growth. THRESHOLD is the limit of number of instructions
1971 function can execute at average to be still considered not expensive. */
1974 expensive_function_p (int threshold
)
1976 unsigned int sum
= 0;
1980 /* We can not compute accurately for large thresholds due to scaled
1982 gcc_assert (threshold
<= BB_FREQ_MAX
);
1984 /* Frequencies are out of range. This either means that function contains
1985 internal loop executing more than BB_FREQ_MAX times or profile feedback
1986 is available and function has not been executed at all. */
1987 if (ENTRY_BLOCK_PTR
->frequency
== 0)
1990 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1991 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
1996 for (insn
= BB_HEAD (bb
); insn
!= NEXT_INSN (BB_END (bb
));
1997 insn
= NEXT_INSN (insn
))
1998 if (active_insn_p (insn
))
2000 sum
+= bb
->frequency
;
2009 /* Estimate basic blocks frequency by given branch probabilities. */
2012 estimate_bb_frequencies (void)
2017 if (cfun
->function_frequency
!= PROFILE_READ
|| !counts_to_freqs ())
2019 static int real_values_initialized
= 0;
2021 if (!real_values_initialized
)
2023 real_values_initialized
= 1;
2024 sreal_init (&real_zero
, 0, 0);
2025 sreal_init (&real_one
, 1, 0);
2026 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
2027 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
2028 sreal_init (&real_one_half
, 1, -1);
2029 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
2030 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
2033 mark_dfs_back_edges ();
2035 single_succ_edge (ENTRY_BLOCK_PTR
)->probability
= REG_BR_PROB_BASE
;
2037 /* Set up block info for each basic block. */
2038 alloc_aux_for_blocks (sizeof (struct block_info_def
));
2039 alloc_aux_for_edges (sizeof (struct edge_info_def
));
2040 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2045 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2047 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
2048 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2049 &EDGE_INFO (e
)->back_edge_prob
,
2050 &real_inv_br_prob_base
);
2054 /* First compute probabilities locally for each loop from innermost
2055 to outermost to examine probabilities for back edges. */
2058 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
2060 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
2061 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
2063 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
2064 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2068 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
2069 sreal_add (&tmp
, &tmp
, &real_one_half
);
2070 bb
->frequency
= sreal_to_int (&tmp
);
2073 free_aux_for_blocks ();
2074 free_aux_for_edges ();
2076 compute_function_frequency ();
2077 if (flag_reorder_functions
)
2078 choose_function_section ();
2081 /* Decide whether function is hot, cold or unlikely executed. */
2083 compute_function_frequency (void)
2087 if (!profile_info
|| !flag_branch_probabilities
)
2089 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
2091 cfun
->function_frequency
= FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
;
2092 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
2094 cfun
->function_frequency
= FUNCTION_FREQUENCY_HOT
;
2097 cfun
->function_frequency
= FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
;
2100 if (maybe_hot_bb_p (bb
))
2102 cfun
->function_frequency
= FUNCTION_FREQUENCY_HOT
;
2105 if (!probably_never_executed_bb_p (bb
))
2106 cfun
->function_frequency
= FUNCTION_FREQUENCY_NORMAL
;
2110 /* Choose appropriate section for the function. */
2112 choose_function_section (void)
2114 if (DECL_SECTION_NAME (current_function_decl
)
2115 || !targetm
.have_named_sections
2116 /* Theoretically we can split the gnu.linkonce text section too,
2117 but this requires more work as the frequency needs to match
2118 for all generated objects so we need to merge the frequency
2119 of all instances. For now just never set frequency for these. */
2120 || DECL_ONE_ONLY (current_function_decl
))
2123 /* If we are doing the partitioning optimization, let the optimization
2124 choose the correct section into which to put things. */
2126 if (flag_reorder_blocks_and_partition
)
2129 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_HOT
)
2130 DECL_SECTION_NAME (current_function_decl
) =
2131 build_string (strlen (HOT_TEXT_SECTION_NAME
), HOT_TEXT_SECTION_NAME
);
2132 if (cfun
->function_frequency
== FUNCTION_FREQUENCY_UNLIKELY_EXECUTED
)
2133 DECL_SECTION_NAME (current_function_decl
) =
2134 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME
),
2135 UNLIKELY_EXECUTED_TEXT_SECTION_NAME
);
2139 gate_estimate_probability (void)
2141 return flag_guess_branch_prob
;
2144 /* Build PREDICT_EXPR. */
2146 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
2148 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
2149 build_int_cst (NULL
, predictor
));
2150 PREDICT_EXPR_OUTCOME (t
) = taken
;
2155 predictor_name (enum br_predictor predictor
)
2157 return predictor_info
[predictor
].name
;
2160 struct gimple_opt_pass pass_profile
=
2164 "profile", /* name */
2165 gate_estimate_probability
, /* gate */
2166 tree_estimate_probability
, /* execute */
2169 0, /* static_pass_number */
2170 TV_BRANCH_PROB
, /* tv_id */
2171 PROP_cfg
, /* properties_required */
2172 0, /* properties_provided */
2173 0, /* properties_destroyed */
2174 0, /* todo_flags_start */
2175 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2179 struct gimple_opt_pass pass_strip_predict_hints
=
2185 strip_predict_hints
, /* execute */
2188 0, /* static_pass_number */
2189 TV_BRANCH_PROB
, /* tv_id */
2190 PROP_cfg
, /* properties_required */
2191 0, /* properties_provided */
2192 0, /* properties_destroyed */
2193 0, /* todo_flags_start */
2194 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */