1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000-2013 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
22 [1] "Branch Prediction for Free"
23 Ball and Larus; PLDI '93.
24 [2] "Static Branch Frequency and Program Profile Analysis"
25 Wu and Larus; MICRO-27.
26 [3] "Corpus-based Static Branch Prediction"
27 Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
32 #include "coretypes.h"
37 #include "hard-reg-set.h"
38 #include "basic-block.h"
39 #include "insn-config.h"
44 #include "diagnostic-core.h"
53 #include "tree-flow.h"
55 #include "tree-pass.h"
56 #include "tree-scalar-evolution.h"
58 #include "pointer-set.h"
60 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
61 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
62 static sreal real_zero
, real_one
, real_almost_one
, real_br_prob_base
,
63 real_inv_br_prob_base
, real_one_half
, real_bb_freq_max
;
65 /* Random guesstimation given names.
66 PROV_VERY_UNLIKELY should be small enough so basic block predicted
67 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
68 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
69 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
70 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
71 #define PROB_ALWAYS (REG_BR_PROB_BASE)
73 static void combine_predictions_for_insn (rtx
, basic_block
);
74 static void dump_prediction (FILE *, enum br_predictor
, int, basic_block
, int);
75 static void predict_paths_leading_to (basic_block
, enum br_predictor
, enum prediction
);
76 static void predict_paths_leading_to_edge (edge
, enum br_predictor
, enum prediction
);
77 static bool can_predict_insn_p (const_rtx
);
79 /* Information we hold about each branch predictor.
80 Filled using information from predict.def. */
84 const char *const name
; /* Name used in the debugging dumps. */
85 const int hitrate
; /* Expected hitrate used by
86 predict_insn_def call. */
90 /* Use given predictor without Dempster-Shaffer theory if it matches
91 using first_match heuristics. */
92 #define PRED_FLAG_FIRST_MATCH 1
94 /* Recompute hitrate in percent to our representation. */
96 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
98 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
99 static const struct predictor_info predictor_info
[]= {
100 #include "predict.def"
102 /* Upper bound on predictors. */
107 /* Return TRUE if frequency FREQ is considered to be hot. */
110 maybe_hot_frequency_p (struct function
*fun
, int freq
)
112 struct cgraph_node
*node
= cgraph_get_node (fun
->decl
);
113 if (!profile_info
|| !flag_branch_probabilities
)
115 if (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
)
117 if (node
->frequency
== NODE_FREQUENCY_HOT
)
120 if (profile_status_for_function (fun
) == PROFILE_ABSENT
)
122 if (node
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
123 && freq
< (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun
)->frequency
* 2 / 3))
125 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
) == 0)
127 if (freq
< (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun
)->frequency
128 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
133 static gcov_type min_count
= -1;
135 /* Determine the threshold for hot BB counts. */
138 get_hot_bb_threshold ()
140 gcov_working_set_t
*ws
;
143 ws
= find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE
));
145 min_count
= ws
->min_counter
;
150 /* Set the threshold for hot BB counts. */
153 set_hot_bb_threshold (gcov_type min
)
158 /* Return TRUE if frequency FREQ is considered to be hot. */
161 maybe_hot_count_p (struct function
*fun
, gcov_type count
)
163 if (fun
&& profile_status_for_function (fun
) != PROFILE_READ
)
165 /* Code executed at most once is not hot. */
166 if (profile_info
->runs
>= count
)
168 return (count
>= get_hot_bb_threshold ());
171 /* Return true in case BB can be CPU intensive and should be optimized
172 for maximal performance. */
175 maybe_hot_bb_p (struct function
*fun
, const_basic_block bb
)
177 gcc_checking_assert (fun
);
178 if (profile_status_for_function (fun
) == PROFILE_READ
)
179 return maybe_hot_count_p (fun
, bb
->count
);
180 return maybe_hot_frequency_p (fun
, bb
->frequency
);
183 /* Return true if the call can be hot. */
186 cgraph_maybe_hot_edge_p (struct cgraph_edge
*edge
)
188 if (profile_info
&& flag_branch_probabilities
189 && !maybe_hot_count_p (NULL
,
192 if (edge
->caller
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
194 && edge
->callee
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
196 if (edge
->caller
->frequency
> NODE_FREQUENCY_UNLIKELY_EXECUTED
198 && edge
->callee
->frequency
<= NODE_FREQUENCY_EXECUTED_ONCE
))
202 if (edge
->caller
->frequency
== NODE_FREQUENCY_HOT
)
204 if (edge
->caller
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
205 && edge
->frequency
< CGRAPH_FREQ_BASE
* 3 / 2)
207 if (flag_guess_branch_prob
)
209 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
) == 0
210 || edge
->frequency
<= (CGRAPH_FREQ_BASE
211 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
217 /* Return true in case BB can be CPU intensive and should be optimized
218 for maximal performance. */
221 maybe_hot_edge_p (edge e
)
223 if (profile_status
== PROFILE_READ
)
224 return maybe_hot_count_p (cfun
, e
->count
);
225 return maybe_hot_frequency_p (cfun
, EDGE_FREQUENCY (e
));
229 /* Return true in case BB is probably never executed. */
232 probably_never_executed_bb_p (struct function
*fun
, const_basic_block bb
)
234 gcc_checking_assert (fun
);
235 if (profile_info
&& flag_branch_probabilities
)
236 return ((bb
->count
+ profile_info
->runs
/ 2) / profile_info
->runs
) == 0;
237 if ((!profile_info
|| !flag_branch_probabilities
)
238 && (cgraph_get_node (fun
->decl
)->frequency
239 == NODE_FREQUENCY_UNLIKELY_EXECUTED
))
244 /* Return true if NODE should be optimized for size. */
247 cgraph_optimize_for_size_p (struct cgraph_node
*node
)
251 if (node
&& (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
257 /* Return true when current function should always be optimized for size. */
260 optimize_function_for_size_p (struct function
*fun
)
264 if (!fun
|| !fun
->decl
)
266 return cgraph_optimize_for_size_p (cgraph_get_node (fun
->decl
));
269 /* Return true when current function should always be optimized for speed. */
272 optimize_function_for_speed_p (struct function
*fun
)
274 return !optimize_function_for_size_p (fun
);
277 /* Return TRUE when BB should be optimized for size. */
280 optimize_bb_for_size_p (const_basic_block bb
)
282 return optimize_function_for_size_p (cfun
) || !maybe_hot_bb_p (cfun
, bb
);
285 /* Return TRUE when BB should be optimized for speed. */
288 optimize_bb_for_speed_p (const_basic_block bb
)
290 return !optimize_bb_for_size_p (bb
);
293 /* Return TRUE when BB should be optimized for size. */
296 optimize_edge_for_size_p (edge e
)
298 return optimize_function_for_size_p (cfun
) || !maybe_hot_edge_p (e
);
301 /* Return TRUE when BB should be optimized for speed. */
304 optimize_edge_for_speed_p (edge e
)
306 return !optimize_edge_for_size_p (e
);
309 /* Return TRUE when BB should be optimized for size. */
312 optimize_insn_for_size_p (void)
314 return optimize_function_for_size_p (cfun
) || !crtl
->maybe_hot_insn_p
;
317 /* Return TRUE when BB should be optimized for speed. */
320 optimize_insn_for_speed_p (void)
322 return !optimize_insn_for_size_p ();
325 /* Return TRUE when LOOP should be optimized for size. */
328 optimize_loop_for_size_p (struct loop
*loop
)
330 return optimize_bb_for_size_p (loop
->header
);
333 /* Return TRUE when LOOP should be optimized for speed. */
336 optimize_loop_for_speed_p (struct loop
*loop
)
338 return optimize_bb_for_speed_p (loop
->header
);
341 /* Return TRUE when LOOP nest should be optimized for speed. */
344 optimize_loop_nest_for_speed_p (struct loop
*loop
)
346 struct loop
*l
= loop
;
347 if (optimize_loop_for_speed_p (loop
))
350 while (l
&& l
!= loop
)
352 if (optimize_loop_for_speed_p (l
))
360 while (l
!= loop
&& !l
->next
)
369 /* Return TRUE when LOOP nest should be optimized for size. */
372 optimize_loop_nest_for_size_p (struct loop
*loop
)
374 return !optimize_loop_nest_for_speed_p (loop
);
377 /* Return true when edge E is likely to be well predictable by branch
381 predictable_edge_p (edge e
)
383 if (profile_status
== PROFILE_ABSENT
)
386 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100)
387 || (REG_BR_PROB_BASE
- e
->probability
388 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100))
394 /* Set RTL expansion for BB profile. */
397 rtl_profile_for_bb (basic_block bb
)
399 crtl
->maybe_hot_insn_p
= maybe_hot_bb_p (cfun
, bb
);
402 /* Set RTL expansion for edge profile. */
405 rtl_profile_for_edge (edge e
)
407 crtl
->maybe_hot_insn_p
= maybe_hot_edge_p (e
);
410 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
412 default_rtl_profile (void)
414 crtl
->maybe_hot_insn_p
= true;
417 /* Return true if the one of outgoing edges is already predicted by
421 rtl_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
424 if (!INSN_P (BB_END (bb
)))
426 for (note
= REG_NOTES (BB_END (bb
)); note
; note
= XEXP (note
, 1))
427 if (REG_NOTE_KIND (note
) == REG_BR_PRED
428 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
433 /* This map contains for a basic block the list of predictions for the
436 static struct pointer_map_t
*bb_predictions
;
438 /* Structure representing predictions in tree level. */
440 struct edge_prediction
{
441 struct edge_prediction
*ep_next
;
443 enum br_predictor ep_predictor
;
447 /* Return true if the one of outgoing edges is already predicted by
451 gimple_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
453 struct edge_prediction
*i
;
454 void **preds
= pointer_map_contains (bb_predictions
, bb
);
459 for (i
= (struct edge_prediction
*) *preds
; i
; i
= i
->ep_next
)
460 if (i
->ep_predictor
== predictor
)
465 /* Return true when the probability of edge is reliable.
467 The profile guessing code is good at predicting branch outcome (ie.
468 taken/not taken), that is predicted right slightly over 75% of time.
469 It is however notoriously poor on predicting the probability itself.
470 In general the profile appear a lot flatter (with probabilities closer
471 to 50%) than the reality so it is bad idea to use it to drive optimization
472 such as those disabling dynamic branch prediction for well predictable
475 There are two exceptions - edges leading to noreturn edges and edges
476 predicted by number of iterations heuristics are predicted well. This macro
477 should be able to distinguish those, but at the moment it simply check for
478 noreturn heuristic that is only one giving probability over 99% or bellow
479 1%. In future we might want to propagate reliability information across the
480 CFG if we find this information useful on multiple places. */
482 probability_reliable_p (int prob
)
484 return (profile_status
== PROFILE_READ
485 || (profile_status
== PROFILE_GUESSED
486 && (prob
<= HITRATE (1) || prob
>= HITRATE (99))));
489 /* Same predicate as above, working on edges. */
491 edge_probability_reliable_p (const_edge e
)
493 return probability_reliable_p (e
->probability
);
496 /* Same predicate as edge_probability_reliable_p, working on notes. */
498 br_prob_note_reliable_p (const_rtx note
)
500 gcc_assert (REG_NOTE_KIND (note
) == REG_BR_PROB
);
501 return probability_reliable_p (INTVAL (XEXP (note
, 0)));
505 predict_insn (rtx insn
, enum br_predictor predictor
, int probability
)
507 gcc_assert (any_condjump_p (insn
));
508 if (!flag_guess_branch_prob
)
511 add_reg_note (insn
, REG_BR_PRED
,
512 gen_rtx_CONCAT (VOIDmode
,
513 GEN_INT ((int) predictor
),
514 GEN_INT ((int) probability
)));
517 /* Predict insn by given predictor. */
520 predict_insn_def (rtx insn
, enum br_predictor predictor
,
521 enum prediction taken
)
523 int probability
= predictor_info
[(int) predictor
].hitrate
;
526 probability
= REG_BR_PROB_BASE
- probability
;
528 predict_insn (insn
, predictor
, probability
);
531 /* Predict edge E with given probability if possible. */
534 rtl_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
537 last_insn
= BB_END (e
->src
);
539 /* We can store the branch prediction information only about
540 conditional jumps. */
541 if (!any_condjump_p (last_insn
))
544 /* We always store probability of branching. */
545 if (e
->flags
& EDGE_FALLTHRU
)
546 probability
= REG_BR_PROB_BASE
- probability
;
548 predict_insn (last_insn
, predictor
, probability
);
551 /* Predict edge E with the given PROBABILITY. */
553 gimple_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
555 gcc_assert (profile_status
!= PROFILE_GUESSED
);
556 if ((e
->src
!= ENTRY_BLOCK_PTR
&& EDGE_COUNT (e
->src
->succs
) > 1)
557 && flag_guess_branch_prob
&& optimize
)
559 struct edge_prediction
*i
= XNEW (struct edge_prediction
);
560 void **preds
= pointer_map_insert (bb_predictions
, e
->src
);
562 i
->ep_next
= (struct edge_prediction
*) *preds
;
564 i
->ep_probability
= probability
;
565 i
->ep_predictor
= predictor
;
570 /* Remove all predictions on given basic block that are attached
573 remove_predictions_associated_with_edge (edge e
)
580 preds
= pointer_map_contains (bb_predictions
, e
->src
);
584 struct edge_prediction
**prediction
= (struct edge_prediction
**) preds
;
585 struct edge_prediction
*next
;
589 if ((*prediction
)->ep_edge
== e
)
591 next
= (*prediction
)->ep_next
;
596 prediction
= &((*prediction
)->ep_next
);
601 /* Clears the list of predictions stored for BB. */
604 clear_bb_predictions (basic_block bb
)
606 void **preds
= pointer_map_contains (bb_predictions
, bb
);
607 struct edge_prediction
*pred
, *next
;
612 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= next
)
614 next
= pred
->ep_next
;
620 /* Return true when we can store prediction on insn INSN.
621 At the moment we represent predictions only on conditional
622 jumps, not at computed jump or other complicated cases. */
624 can_predict_insn_p (const_rtx insn
)
626 return (JUMP_P (insn
)
627 && any_condjump_p (insn
)
628 && EDGE_COUNT (BLOCK_FOR_INSN (insn
)->succs
) >= 2);
631 /* Predict edge E by given predictor if possible. */
634 predict_edge_def (edge e
, enum br_predictor predictor
,
635 enum prediction taken
)
637 int probability
= predictor_info
[(int) predictor
].hitrate
;
640 probability
= REG_BR_PROB_BASE
- probability
;
642 predict_edge (e
, predictor
, probability
);
645 /* Invert all branch predictions or probability notes in the INSN. This needs
646 to be done each time we invert the condition used by the jump. */
649 invert_br_probabilities (rtx insn
)
653 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
654 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
655 XEXP (note
, 0) = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (note
, 0)));
656 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
657 XEXP (XEXP (note
, 0), 1)
658 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
661 /* Dump information about the branch prediction to the output file. */
664 dump_prediction (FILE *file
, enum br_predictor predictor
, int probability
,
665 basic_block bb
, int used
)
673 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
674 if (! (e
->flags
& EDGE_FALLTHRU
))
677 fprintf (file
, " %s heuristics%s: %.1f%%",
678 predictor_info
[predictor
].name
,
679 used
? "" : " (ignored)", probability
* 100.0 / REG_BR_PROB_BASE
);
683 fprintf (file
, " exec ");
684 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, bb
->count
);
687 fprintf (file
, " hit ");
688 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, e
->count
);
689 fprintf (file
, " (%.1f%%)", e
->count
* 100.0 / bb
->count
);
693 fprintf (file
, "\n");
696 /* We can not predict the probabilities of outgoing edges of bb. Set them
697 evenly and hope for the best. */
699 set_even_probabilities (basic_block bb
)
705 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
706 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
708 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
709 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
710 e
->probability
= (REG_BR_PROB_BASE
+ nedges
/ 2) / nedges
;
715 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
716 note if not already present. Remove now useless REG_BR_PRED notes. */
719 combine_predictions_for_insn (rtx insn
, basic_block bb
)
724 int best_probability
= PROB_EVEN
;
725 enum br_predictor best_predictor
= END_PREDICTORS
;
726 int combined_probability
= REG_BR_PROB_BASE
/ 2;
728 bool first_match
= false;
731 if (!can_predict_insn_p (insn
))
733 set_even_probabilities (bb
);
737 prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
738 pnote
= ®_NOTES (insn
);
740 fprintf (dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
743 /* We implement "first match" heuristics and use probability guessed
744 by predictor with smallest index. */
745 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
746 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
748 enum br_predictor predictor
= ((enum br_predictor
)
749 INTVAL (XEXP (XEXP (note
, 0), 0)));
750 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
753 if (best_predictor
> predictor
)
754 best_probability
= probability
, best_predictor
= predictor
;
756 d
= (combined_probability
* probability
757 + (REG_BR_PROB_BASE
- combined_probability
)
758 * (REG_BR_PROB_BASE
- probability
));
760 /* Use FP math to avoid overflows of 32bit integers. */
762 /* If one probability is 0% and one 100%, avoid division by zero. */
763 combined_probability
= REG_BR_PROB_BASE
/ 2;
765 combined_probability
= (((double) combined_probability
) * probability
766 * REG_BR_PROB_BASE
/ d
+ 0.5);
769 /* Decide which heuristic to use. In case we didn't match anything,
770 use no_prediction heuristic, in case we did match, use either
771 first match or Dempster-Shaffer theory depending on the flags. */
773 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
777 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
778 combined_probability
, bb
, true);
781 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
783 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
788 combined_probability
= best_probability
;
789 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
793 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
795 enum br_predictor predictor
= ((enum br_predictor
)
796 INTVAL (XEXP (XEXP (*pnote
, 0), 0)));
797 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
799 dump_prediction (dump_file
, predictor
, probability
, bb
,
800 !first_match
|| best_predictor
== predictor
);
801 *pnote
= XEXP (*pnote
, 1);
804 pnote
= &XEXP (*pnote
, 1);
809 add_reg_note (insn
, REG_BR_PROB
, GEN_INT (combined_probability
));
811 /* Save the prediction into CFG in case we are seeing non-degenerated
813 if (!single_succ_p (bb
))
815 BRANCH_EDGE (bb
)->probability
= combined_probability
;
816 FALLTHRU_EDGE (bb
)->probability
817 = REG_BR_PROB_BASE
- combined_probability
;
820 else if (!single_succ_p (bb
))
822 int prob
= INTVAL (XEXP (prob_note
, 0));
824 BRANCH_EDGE (bb
)->probability
= prob
;
825 FALLTHRU_EDGE (bb
)->probability
= REG_BR_PROB_BASE
- prob
;
828 single_succ_edge (bb
)->probability
= REG_BR_PROB_BASE
;
831 /* Combine predictions into single probability and store them into CFG.
832 Remove now useless prediction entries. */
835 combine_predictions_for_bb (basic_block bb
)
837 int best_probability
= PROB_EVEN
;
838 enum br_predictor best_predictor
= END_PREDICTORS
;
839 int combined_probability
= REG_BR_PROB_BASE
/ 2;
841 bool first_match
= false;
843 struct edge_prediction
*pred
;
845 edge e
, first
= NULL
, second
= NULL
;
849 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
850 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
853 if (first
&& !second
)
859 /* When there is no successor or only one choice, prediction is easy.
861 We are lazy for now and predict only basic blocks with two outgoing
862 edges. It is possible to predict generic case too, but we have to
863 ignore first match heuristics and do more involved combining. Implement
868 set_even_probabilities (bb
);
869 clear_bb_predictions (bb
);
871 fprintf (dump_file
, "%i edges in bb %i predicted to even probabilities\n",
877 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
879 preds
= pointer_map_contains (bb_predictions
, bb
);
882 /* We implement "first match" heuristics and use probability guessed
883 by predictor with smallest index. */
884 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
886 enum br_predictor predictor
= pred
->ep_predictor
;
887 int probability
= pred
->ep_probability
;
889 if (pred
->ep_edge
!= first
)
890 probability
= REG_BR_PROB_BASE
- probability
;
893 /* First match heuristics would be widly confused if we predicted
895 if (best_predictor
> predictor
)
897 struct edge_prediction
*pred2
;
898 int prob
= probability
;
900 for (pred2
= (struct edge_prediction
*) *preds
; pred2
; pred2
= pred2
->ep_next
)
901 if (pred2
!= pred
&& pred2
->ep_predictor
== pred
->ep_predictor
)
903 int probability2
= pred
->ep_probability
;
905 if (pred2
->ep_edge
!= first
)
906 probability2
= REG_BR_PROB_BASE
- probability2
;
908 if ((probability
< REG_BR_PROB_BASE
/ 2) !=
909 (probability2
< REG_BR_PROB_BASE
/ 2))
912 /* If the same predictor later gave better result, go for it! */
913 if ((probability
>= REG_BR_PROB_BASE
/ 2 && (probability2
> probability
))
914 || (probability
<= REG_BR_PROB_BASE
/ 2 && (probability2
< probability
)))
918 best_probability
= prob
, best_predictor
= predictor
;
921 d
= (combined_probability
* probability
922 + (REG_BR_PROB_BASE
- combined_probability
)
923 * (REG_BR_PROB_BASE
- probability
));
925 /* Use FP math to avoid overflows of 32bit integers. */
927 /* If one probability is 0% and one 100%, avoid division by zero. */
928 combined_probability
= REG_BR_PROB_BASE
/ 2;
930 combined_probability
= (((double) combined_probability
)
932 * REG_BR_PROB_BASE
/ d
+ 0.5);
936 /* Decide which heuristic to use. In case we didn't match anything,
937 use no_prediction heuristic, in case we did match, use either
938 first match or Dempster-Shaffer theory depending on the flags. */
940 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
944 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
, true);
947 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
949 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
954 combined_probability
= best_probability
;
955 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
959 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
961 enum br_predictor predictor
= pred
->ep_predictor
;
962 int probability
= pred
->ep_probability
;
964 if (pred
->ep_edge
!= EDGE_SUCC (bb
, 0))
965 probability
= REG_BR_PROB_BASE
- probability
;
966 dump_prediction (dump_file
, predictor
, probability
, bb
,
967 !first_match
|| best_predictor
== predictor
);
970 clear_bb_predictions (bb
);
974 first
->probability
= combined_probability
;
975 second
->probability
= REG_BR_PROB_BASE
- combined_probability
;
979 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
980 Return the SSA_NAME if the condition satisfies, NULL otherwise.
982 T1 and T2 should be one of the following cases:
983 1. T1 is SSA_NAME, T2 is NULL
984 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
985 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
988 strips_small_constant (tree t1
, tree t2
)
995 else if (TREE_CODE (t1
) == SSA_NAME
)
997 else if (host_integerp (t1
, 0))
998 value
= tree_low_cst (t1
, 0);
1004 else if (host_integerp (t2
, 0))
1005 value
= tree_low_cst (t2
, 0);
1006 else if (TREE_CODE (t2
) == SSA_NAME
)
1014 if (value
<= 4 && value
>= -4)
1020 /* Return the SSA_NAME in T or T's operands.
1021 Return NULL if SSA_NAME cannot be found. */
1024 get_base_value (tree t
)
1026 if (TREE_CODE (t
) == SSA_NAME
)
1029 if (!BINARY_CLASS_P (t
))
1032 switch (TREE_OPERAND_LENGTH (t
))
1035 return strips_small_constant (TREE_OPERAND (t
, 0), NULL
);
1037 return strips_small_constant (TREE_OPERAND (t
, 0),
1038 TREE_OPERAND (t
, 1));
1044 /* Check the compare STMT in LOOP. If it compares an induction
1045 variable to a loop invariant, return true, and save
1046 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1047 Otherwise return false and set LOOP_INVAIANT to NULL. */
1050 is_comparison_with_loop_invariant_p (gimple stmt
, struct loop
*loop
,
1051 tree
*loop_invariant
,
1052 enum tree_code
*compare_code
,
1056 tree op0
, op1
, bound
, base
;
1058 enum tree_code code
;
1061 code
= gimple_cond_code (stmt
);
1062 *loop_invariant
= NULL
;
1078 op0
= gimple_cond_lhs (stmt
);
1079 op1
= gimple_cond_rhs (stmt
);
1081 if ((TREE_CODE (op0
) != SSA_NAME
&& TREE_CODE (op0
) != INTEGER_CST
)
1082 || (TREE_CODE (op1
) != SSA_NAME
&& TREE_CODE (op1
) != INTEGER_CST
))
1084 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op0
, &iv0
, true))
1086 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op1
, &iv1
, true))
1088 if (TREE_CODE (iv0
.step
) != INTEGER_CST
1089 || TREE_CODE (iv1
.step
) != INTEGER_CST
)
1091 if ((integer_zerop (iv0
.step
) && integer_zerop (iv1
.step
))
1092 || (!integer_zerop (iv0
.step
) && !integer_zerop (iv1
.step
)))
1095 if (integer_zerop (iv0
.step
))
1097 if (code
!= NE_EXPR
&& code
!= EQ_EXPR
)
1098 code
= invert_tree_comparison (code
, false);
1101 if (host_integerp (iv1
.step
, 0))
1110 if (host_integerp (iv0
.step
, 0))
1116 if (TREE_CODE (bound
) != INTEGER_CST
)
1117 bound
= get_base_value (bound
);
1120 if (TREE_CODE (base
) != INTEGER_CST
)
1121 base
= get_base_value (base
);
1125 *loop_invariant
= bound
;
1126 *compare_code
= code
;
1128 *loop_iv_base
= base
;
1132 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1135 expr_coherent_p (tree t1
, tree t2
)
1138 tree ssa_name_1
= NULL
;
1139 tree ssa_name_2
= NULL
;
1141 gcc_assert (TREE_CODE (t1
) == SSA_NAME
|| TREE_CODE (t1
) == INTEGER_CST
);
1142 gcc_assert (TREE_CODE (t2
) == SSA_NAME
|| TREE_CODE (t2
) == INTEGER_CST
);
1147 if (TREE_CODE (t1
) == INTEGER_CST
&& TREE_CODE (t2
) == INTEGER_CST
)
1149 if (TREE_CODE (t1
) == INTEGER_CST
|| TREE_CODE (t2
) == INTEGER_CST
)
1152 /* Check to see if t1 is expressed/defined with t2. */
1153 stmt
= SSA_NAME_DEF_STMT (t1
);
1154 gcc_assert (stmt
!= NULL
);
1155 if (is_gimple_assign (stmt
))
1157 ssa_name_1
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1158 if (ssa_name_1
&& ssa_name_1
== t2
)
1162 /* Check to see if t2 is expressed/defined with t1. */
1163 stmt
= SSA_NAME_DEF_STMT (t2
);
1164 gcc_assert (stmt
!= NULL
);
1165 if (is_gimple_assign (stmt
))
1167 ssa_name_2
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1168 if (ssa_name_2
&& ssa_name_2
== t1
)
1172 /* Compare if t1 and t2's def_stmts are identical. */
1173 if (ssa_name_2
!= NULL
&& ssa_name_1
== ssa_name_2
)
1179 /* Predict branch probability of BB when BB contains a branch that compares
1180 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1181 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1184 for (int i = 0; i < bound; i++) {
1191 In this loop, we will predict the branch inside the loop to be taken. */
1194 predict_iv_comparison (struct loop
*loop
, basic_block bb
,
1195 tree loop_bound_var
,
1196 tree loop_iv_base_var
,
1197 enum tree_code loop_bound_code
,
1198 int loop_bound_step
)
1201 tree compare_var
, compare_base
;
1202 enum tree_code compare_code
;
1203 tree compare_step_var
;
1207 if (predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1208 || predicted_by_p (bb
, PRED_LOOP_ITERATIONS
)
1209 || predicted_by_p (bb
, PRED_LOOP_EXIT
))
1212 stmt
= last_stmt (bb
);
1213 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1215 if (!is_comparison_with_loop_invariant_p (stmt
, loop
, &compare_var
,
1221 /* Find the taken edge. */
1222 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1223 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1226 /* When comparing an IV to a loop invariant, NE is more likely to be
1227 taken while EQ is more likely to be not-taken. */
1228 if (compare_code
== NE_EXPR
)
1230 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1233 else if (compare_code
== EQ_EXPR
)
1235 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1239 if (!expr_coherent_p (loop_iv_base_var
, compare_base
))
1242 /* If loop bound, base and compare bound are all constants, we can
1243 calculate the probability directly. */
1244 if (host_integerp (loop_bound_var
, 0)
1245 && host_integerp (compare_var
, 0)
1246 && host_integerp (compare_base
, 0))
1249 bool of
, overflow
= false;
1250 double_int mod
, compare_count
, tem
, loop_count
;
1252 double_int loop_bound
= tree_to_double_int (loop_bound_var
);
1253 double_int compare_bound
= tree_to_double_int (compare_var
);
1254 double_int base
= tree_to_double_int (compare_base
);
1255 double_int compare_step
= tree_to_double_int (compare_step_var
);
1257 /* (loop_bound - base) / compare_step */
1258 tem
= loop_bound
.sub_with_overflow (base
, &of
);
1260 loop_count
= tem
.divmod_with_overflow (compare_step
,
1265 if ((!compare_step
.is_negative ())
1266 ^ (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1268 /* (loop_bound - compare_bound) / compare_step */
1269 tem
= loop_bound
.sub_with_overflow (compare_bound
, &of
);
1271 compare_count
= tem
.divmod_with_overflow (compare_step
,
1278 /* (compare_bound - base) / compare_step */
1279 tem
= compare_bound
.sub_with_overflow (base
, &of
);
1281 compare_count
= tem
.divmod_with_overflow (compare_step
,
1286 if (compare_code
== LE_EXPR
|| compare_code
== GE_EXPR
)
1288 if (loop_bound_code
== LE_EXPR
|| loop_bound_code
== GE_EXPR
)
1290 if (compare_count
.is_negative ())
1291 compare_count
= double_int_zero
;
1292 if (loop_count
.is_negative ())
1293 loop_count
= double_int_zero
;
1294 if (loop_count
.is_zero ())
1296 else if (compare_count
.scmp (loop_count
) == 1)
1297 probability
= REG_BR_PROB_BASE
;
1300 /* If loop_count is too big, such that REG_BR_PROB_BASE * loop_count
1301 could overflow, shift both loop_count and compare_count right
1302 a bit so that it doesn't overflow. Note both counts are known not
1303 to be negative at this point. */
1304 int clz_bits
= clz_hwi (loop_count
.high
);
1305 gcc_assert (REG_BR_PROB_BASE
< 32768);
1308 loop_count
.arshift (16 - clz_bits
, HOST_BITS_PER_DOUBLE_INT
);
1309 compare_count
.arshift (16 - clz_bits
, HOST_BITS_PER_DOUBLE_INT
);
1311 tem
= compare_count
.mul_with_sign (double_int::from_shwi
1312 (REG_BR_PROB_BASE
), true, &of
);
1314 tem
= tem
.divmod (loop_count
, true, TRUNC_DIV_EXPR
, &mod
);
1315 probability
= tem
.to_uhwi ();
1319 predict_edge (then_edge
, PRED_LOOP_IV_COMPARE
, probability
);
1324 if (expr_coherent_p (loop_bound_var
, compare_var
))
1326 if ((loop_bound_code
== LT_EXPR
|| loop_bound_code
== LE_EXPR
)
1327 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1328 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1329 else if ((loop_bound_code
== GT_EXPR
|| loop_bound_code
== GE_EXPR
)
1330 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1331 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1332 else if (loop_bound_code
== NE_EXPR
)
1334 /* If the loop backedge condition is "(i != bound)", we do
1335 the comparison based on the step of IV:
1336 * step < 0 : backedge condition is like (i > bound)
1337 * step > 0 : backedge condition is like (i < bound) */
1338 gcc_assert (loop_bound_step
!= 0);
1339 if (loop_bound_step
> 0
1340 && (compare_code
== LT_EXPR
1341 || compare_code
== LE_EXPR
))
1342 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1343 else if (loop_bound_step
< 0
1344 && (compare_code
== GT_EXPR
1345 || compare_code
== GE_EXPR
))
1346 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1348 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1351 /* The branch is predicted not-taken if loop_bound_code is
1352 opposite with compare_code. */
1353 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1355 else if (expr_coherent_p (loop_iv_base_var
, compare_var
))
1358 for (i = s; i < h; i++)
1360 The branch should be predicted taken. */
1361 if (loop_bound_step
> 0
1362 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1363 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1364 else if (loop_bound_step
< 0
1365 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1366 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1368 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1372 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1373 exits are resulted from short-circuit conditions that will generate an
1376 if (foo() || global > 10)
1379 This will be translated into:
1384 if foo() goto BB6 else goto BB5
1386 if global > 10 goto BB6 else goto BB7
1390 iftmp = (PHI 0(BB5), 1(BB6))
1391 if iftmp == 1 goto BB8 else goto BB3
1393 outside of the loop...
1395 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1396 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1397 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1398 exits to predict them using PRED_LOOP_EXIT. */
1401 predict_extra_loop_exits (edge exit_edge
)
1404 bool check_value_one
;
1406 tree cmp_rhs
, cmp_lhs
;
1407 gimple cmp_stmt
= last_stmt (exit_edge
->src
);
1409 if (!cmp_stmt
|| gimple_code (cmp_stmt
) != GIMPLE_COND
)
1411 cmp_rhs
= gimple_cond_rhs (cmp_stmt
);
1412 cmp_lhs
= gimple_cond_lhs (cmp_stmt
);
1413 if (!TREE_CONSTANT (cmp_rhs
)
1414 || !(integer_zerop (cmp_rhs
) || integer_onep (cmp_rhs
)))
1416 if (TREE_CODE (cmp_lhs
) != SSA_NAME
)
1419 /* If check_value_one is true, only the phi_args with value '1' will lead
1420 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1422 check_value_one
= (((integer_onep (cmp_rhs
))
1423 ^ (gimple_cond_code (cmp_stmt
) == EQ_EXPR
))
1424 ^ ((exit_edge
->flags
& EDGE_TRUE_VALUE
) != 0));
1426 phi_stmt
= SSA_NAME_DEF_STMT (cmp_lhs
);
1427 if (!phi_stmt
|| gimple_code (phi_stmt
) != GIMPLE_PHI
)
1430 for (i
= 0; i
< gimple_phi_num_args (phi_stmt
); i
++)
1434 tree val
= gimple_phi_arg_def (phi_stmt
, i
);
1435 edge e
= gimple_phi_arg_edge (phi_stmt
, i
);
1437 if (!TREE_CONSTANT (val
) || !(integer_zerop (val
) || integer_onep (val
)))
1439 if ((check_value_one
^ integer_onep (val
)) == 1)
1441 if (EDGE_COUNT (e
->src
->succs
) != 1)
1443 predict_paths_leading_to_edge (e
, PRED_LOOP_EXIT
, NOT_TAKEN
);
1447 FOR_EACH_EDGE (e1
, ei
, e
->src
->preds
)
1448 predict_paths_leading_to_edge (e1
, PRED_LOOP_EXIT
, NOT_TAKEN
);
1452 /* Predict edge probabilities by exploiting loop structure. */
1455 predict_loops (void)
1460 /* Try to predict out blocks in a loop that are not part of a
1462 FOR_EACH_LOOP (li
, loop
, 0)
1464 basic_block bb
, *bbs
;
1465 unsigned j
, n_exits
;
1467 struct tree_niter_desc niter_desc
;
1469 struct nb_iter_bound
*nb_iter
;
1470 enum tree_code loop_bound_code
= ERROR_MARK
;
1471 tree loop_bound_step
= NULL
;
1472 tree loop_bound_var
= NULL
;
1473 tree loop_iv_base
= NULL
;
1476 exits
= get_loop_exit_edges (loop
);
1477 n_exits
= exits
.length ();
1484 FOR_EACH_VEC_ELT (exits
, j
, ex
)
1487 HOST_WIDE_INT nitercst
;
1488 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
1490 enum br_predictor predictor
;
1492 predict_extra_loop_exits (ex
);
1494 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false, false))
1495 niter
= niter_desc
.niter
;
1496 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
1497 niter
= loop_niter_by_eval (loop
, ex
);
1499 if (TREE_CODE (niter
) == INTEGER_CST
)
1501 if (host_integerp (niter
, 1)
1503 && compare_tree_int (niter
, max
- 1) == -1)
1504 nitercst
= tree_low_cst (niter
, 1) + 1;
1507 predictor
= PRED_LOOP_ITERATIONS
;
1509 /* If we have just one exit and we can derive some information about
1510 the number of iterations of the loop from the statements inside
1511 the loop, use it to predict this exit. */
1512 else if (n_exits
== 1)
1514 nitercst
= estimated_stmt_executions_int (loop
);
1520 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
1525 /* If the prediction for number of iterations is zero, do not
1526 predict the exit edges. */
1530 probability
= ((REG_BR_PROB_BASE
+ nitercst
/ 2) / nitercst
);
1531 predict_edge (ex
, predictor
, probability
);
1535 /* Find information about loop bound variables. */
1536 for (nb_iter
= loop
->bounds
; nb_iter
;
1537 nb_iter
= nb_iter
->next
)
1539 && gimple_code (nb_iter
->stmt
) == GIMPLE_COND
)
1541 stmt
= nb_iter
->stmt
;
1544 if (!stmt
&& last_stmt (loop
->header
)
1545 && gimple_code (last_stmt (loop
->header
)) == GIMPLE_COND
)
1546 stmt
= last_stmt (loop
->header
);
1548 is_comparison_with_loop_invariant_p (stmt
, loop
,
1554 bbs
= get_loop_body (loop
);
1556 for (j
= 0; j
< loop
->num_nodes
; j
++)
1558 int header_found
= 0;
1564 /* Bypass loop heuristics on continue statement. These
1565 statements construct loops via "non-loop" constructs
1566 in the source language and are better to be handled
1568 if (predicted_by_p (bb
, PRED_CONTINUE
))
1571 /* Loop branch heuristics - predict an edge back to a
1572 loop's head as taken. */
1573 if (bb
== loop
->latch
)
1575 e
= find_edge (loop
->latch
, loop
->header
);
1579 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
1583 /* Loop exit heuristics - predict an edge exiting the loop if the
1584 conditional has no loop header successors as not taken. */
1586 /* If we already used more reliable loop exit predictors, do not
1587 bother with PRED_LOOP_EXIT. */
1588 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1589 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS
))
1591 /* For loop with many exits we don't want to predict all exits
1592 with the pretty large probability, because if all exits are
1593 considered in row, the loop would be predicted to iterate
1594 almost never. The code to divide probability by number of
1595 exits is very rough. It should compute the number of exits
1596 taken in each patch through function (not the overall number
1597 of exits that might be a lot higher for loops with wide switch
1598 statements in them) and compute n-th square root.
1600 We limit the minimal probability by 2% to avoid
1601 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1602 as this was causing regression in perl benchmark containing such
1605 int probability
= ((REG_BR_PROB_BASE
1606 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
1608 if (probability
< HITRATE (2))
1609 probability
= HITRATE (2);
1610 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1611 if (e
->dest
->index
< NUM_FIXED_BLOCKS
1612 || !flow_bb_inside_loop_p (loop
, e
->dest
))
1613 predict_edge (e
, PRED_LOOP_EXIT
, probability
);
1616 predict_iv_comparison (loop
, bb
, loop_bound_var
, loop_iv_base
,
1618 tree_low_cst (loop_bound_step
, 0));
1621 /* Free basic blocks from get_loop_body. */
1626 /* Attempt to predict probabilities of BB outgoing edges using local
1629 bb_estimate_probability_locally (basic_block bb
)
1631 rtx last_insn
= BB_END (bb
);
1634 if (! can_predict_insn_p (last_insn
))
1636 cond
= get_condition (last_insn
, NULL
, false, false);
1640 /* Try "pointer heuristic."
1641 A comparison ptr == 0 is predicted as false.
1642 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1643 if (COMPARISON_P (cond
)
1644 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
1645 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
1647 if (GET_CODE (cond
) == EQ
)
1648 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
1649 else if (GET_CODE (cond
) == NE
)
1650 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
1654 /* Try "opcode heuristic."
1655 EQ tests are usually false and NE tests are usually true. Also,
1656 most quantities are positive, so we can make the appropriate guesses
1657 about signed comparisons against zero. */
1658 switch (GET_CODE (cond
))
1661 /* Unconditional branch. */
1662 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
1663 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
1668 /* Floating point comparisons appears to behave in a very
1669 unpredictable way because of special role of = tests in
1671 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1673 /* Comparisons with 0 are often used for booleans and there is
1674 nothing useful to predict about them. */
1675 else if (XEXP (cond
, 1) == const0_rtx
1676 || XEXP (cond
, 0) == const0_rtx
)
1679 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
1684 /* Floating point comparisons appears to behave in a very
1685 unpredictable way because of special role of = tests in
1687 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1689 /* Comparisons with 0 are often used for booleans and there is
1690 nothing useful to predict about them. */
1691 else if (XEXP (cond
, 1) == const0_rtx
1692 || XEXP (cond
, 0) == const0_rtx
)
1695 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
1699 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
1703 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
1708 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1709 || XEXP (cond
, 1) == constm1_rtx
)
1710 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
1715 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1716 || XEXP (cond
, 1) == constm1_rtx
)
1717 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
1725 /* Set edge->probability for each successor edge of BB. */
1727 guess_outgoing_edge_probabilities (basic_block bb
)
1729 bb_estimate_probability_locally (bb
);
1730 combine_predictions_for_insn (BB_END (bb
), bb
);
1733 static tree
expr_expected_value (tree
, bitmap
);
1735 /* Helper function for expr_expected_value. */
1738 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
,
1739 tree op1
, bitmap visited
)
1743 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1745 if (TREE_CONSTANT (op0
))
1748 if (code
!= SSA_NAME
)
1751 def
= SSA_NAME_DEF_STMT (op0
);
1753 /* If we were already here, break the infinite cycle. */
1754 if (!bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
)))
1757 if (gimple_code (def
) == GIMPLE_PHI
)
1759 /* All the arguments of the PHI node must have the same constant
1761 int i
, n
= gimple_phi_num_args (def
);
1762 tree val
= NULL
, new_val
;
1764 for (i
= 0; i
< n
; i
++)
1766 tree arg
= PHI_ARG_DEF (def
, i
);
1768 /* If this PHI has itself as an argument, we cannot
1769 determine the string length of this argument. However,
1770 if we can find an expected constant value for the other
1771 PHI args then we can still be sure that this is
1772 likely a constant. So be optimistic and just
1773 continue with the next argument. */
1774 if (arg
== PHI_RESULT (def
))
1777 new_val
= expr_expected_value (arg
, visited
);
1782 else if (!operand_equal_p (val
, new_val
, false))
1787 if (is_gimple_assign (def
))
1789 if (gimple_assign_lhs (def
) != op0
)
1792 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
1793 gimple_assign_rhs1 (def
),
1794 gimple_assign_rhs_code (def
),
1795 gimple_assign_rhs2 (def
),
1799 if (is_gimple_call (def
))
1801 tree decl
= gimple_call_fndecl (def
);
1804 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
)
1805 switch (DECL_FUNCTION_CODE (decl
))
1807 case BUILT_IN_EXPECT
:
1810 if (gimple_call_num_args (def
) != 2)
1812 val
= gimple_call_arg (def
, 0);
1813 if (TREE_CONSTANT (val
))
1815 return gimple_call_arg (def
, 1);
1818 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
:
1819 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1
:
1820 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2
:
1821 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4
:
1822 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8
:
1823 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16
:
1824 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE
:
1825 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N
:
1826 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1
:
1827 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2
:
1828 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4
:
1829 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8
:
1830 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16
:
1831 /* Assume that any given atomic operation has low contention,
1832 and thus the compare-and-swap operation succeeds. */
1833 return boolean_true_node
;
1840 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
1843 op0
= expr_expected_value (op0
, visited
);
1846 op1
= expr_expected_value (op1
, visited
);
1849 res
= fold_build2 (code
, type
, op0
, op1
);
1850 if (TREE_CONSTANT (res
))
1854 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
1857 op0
= expr_expected_value (op0
, visited
);
1860 res
= fold_build1 (code
, type
, op0
);
1861 if (TREE_CONSTANT (res
))
1868 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1869 The function is used by builtin_expect branch predictor so the evidence
1870 must come from this construct and additional possible constant folding.
1872 We may want to implement more involved value guess (such as value range
1873 propagation based prediction), but such tricks shall go to new
1877 expr_expected_value (tree expr
, bitmap visited
)
1879 enum tree_code code
;
1882 if (TREE_CONSTANT (expr
))
1885 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1886 return expr_expected_value_1 (TREE_TYPE (expr
),
1887 op0
, code
, op1
, visited
);
1891 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1892 we no longer need. */
1894 strip_predict_hints (void)
1902 gimple_stmt_iterator bi
;
1903 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
);)
1905 gimple stmt
= gsi_stmt (bi
);
1907 if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1909 gsi_remove (&bi
, true);
1912 else if (gimple_code (stmt
) == GIMPLE_CALL
)
1914 tree fndecl
= gimple_call_fndecl (stmt
);
1917 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1918 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
1919 && gimple_call_num_args (stmt
) == 2)
1921 var
= gimple_call_lhs (stmt
);
1925 = gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
1926 gsi_replace (&bi
, ass_stmt
, true);
1930 gsi_remove (&bi
, true);
1941 /* Predict using opcode of the last statement in basic block. */
1943 tree_predict_by_opcode (basic_block bb
)
1945 gimple stmt
= last_stmt (bb
);
1954 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1956 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1957 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1959 op0
= gimple_cond_lhs (stmt
);
1960 op1
= gimple_cond_rhs (stmt
);
1961 cmp
= gimple_cond_code (stmt
);
1962 type
= TREE_TYPE (op0
);
1963 visited
= BITMAP_ALLOC (NULL
);
1964 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, visited
);
1965 BITMAP_FREE (visited
);
1968 if (integer_zerop (val
))
1969 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, NOT_TAKEN
);
1971 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, TAKEN
);
1974 /* Try "pointer heuristic."
1975 A comparison ptr == 0 is predicted as false.
1976 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1977 if (POINTER_TYPE_P (type
))
1980 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
1981 else if (cmp
== NE_EXPR
)
1982 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
1986 /* Try "opcode heuristic."
1987 EQ tests are usually false and NE tests are usually true. Also,
1988 most quantities are positive, so we can make the appropriate guesses
1989 about signed comparisons against zero. */
1994 /* Floating point comparisons appears to behave in a very
1995 unpredictable way because of special role of = tests in
1997 if (FLOAT_TYPE_P (type
))
1999 /* Comparisons with 0 are often used for booleans and there is
2000 nothing useful to predict about them. */
2001 else if (integer_zerop (op0
) || integer_zerop (op1
))
2004 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
2009 /* Floating point comparisons appears to behave in a very
2010 unpredictable way because of special role of = tests in
2012 if (FLOAT_TYPE_P (type
))
2014 /* Comparisons with 0 are often used for booleans and there is
2015 nothing useful to predict about them. */
2016 else if (integer_zerop (op0
)
2017 || integer_zerop (op1
))
2020 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
2024 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
2027 case UNORDERED_EXPR
:
2028 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
2033 if (integer_zerop (op1
)
2034 || integer_onep (op1
)
2035 || integer_all_onesp (op1
)
2038 || real_minus_onep (op1
))
2039 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
2044 if (integer_zerop (op1
)
2045 || integer_onep (op1
)
2046 || integer_all_onesp (op1
)
2049 || real_minus_onep (op1
))
2050 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
2058 /* Try to guess whether the value of return means error code. */
2060 static enum br_predictor
2061 return_prediction (tree val
, enum prediction
*prediction
)
2065 return PRED_NO_PREDICTION
;
2066 /* Different heuristics for pointers and scalars. */
2067 if (POINTER_TYPE_P (TREE_TYPE (val
)))
2069 /* NULL is usually not returned. */
2070 if (integer_zerop (val
))
2072 *prediction
= NOT_TAKEN
;
2073 return PRED_NULL_RETURN
;
2076 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
2078 /* Negative return values are often used to indicate
2080 if (TREE_CODE (val
) == INTEGER_CST
2081 && tree_int_cst_sgn (val
) < 0)
2083 *prediction
= NOT_TAKEN
;
2084 return PRED_NEGATIVE_RETURN
;
2086 /* Constant return values seems to be commonly taken.
2087 Zero/one often represent booleans so exclude them from the
2089 if (TREE_CONSTANT (val
)
2090 && (!integer_zerop (val
) && !integer_onep (val
)))
2092 *prediction
= TAKEN
;
2093 return PRED_CONST_RETURN
;
2096 return PRED_NO_PREDICTION
;
2099 /* Find the basic block with return expression and look up for possible
2100 return value trying to apply RETURN_PREDICTION heuristics. */
2102 apply_return_prediction (void)
2104 gimple return_stmt
= NULL
;
2108 int phi_num_args
, i
;
2109 enum br_predictor pred
;
2110 enum prediction direction
;
2113 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
2115 return_stmt
= last_stmt (e
->src
);
2117 && gimple_code (return_stmt
) == GIMPLE_RETURN
)
2122 return_val
= gimple_return_retval (return_stmt
);
2125 if (TREE_CODE (return_val
) != SSA_NAME
2126 || !SSA_NAME_DEF_STMT (return_val
)
2127 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
2129 phi
= SSA_NAME_DEF_STMT (return_val
);
2130 phi_num_args
= gimple_phi_num_args (phi
);
2131 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
2133 /* Avoid the degenerate case where all return values form the function
2134 belongs to same category (ie they are all positive constants)
2135 so we can hardly say something about them. */
2136 for (i
= 1; i
< phi_num_args
; i
++)
2137 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
2139 if (i
!= phi_num_args
)
2140 for (i
= 0; i
< phi_num_args
; i
++)
2142 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
2143 if (pred
!= PRED_NO_PREDICTION
)
2144 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi
, i
), pred
,
2149 /* Look for basic block that contains unlikely to happen events
2150 (such as noreturn calls) and mark all paths leading to execution
2151 of this basic blocks as unlikely. */
2154 tree_bb_level_predictions (void)
2157 bool has_return_edges
= false;
2161 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
2162 if (!(e
->flags
& (EDGE_ABNORMAL
| EDGE_FAKE
| EDGE_EH
)))
2164 has_return_edges
= true;
2168 apply_return_prediction ();
2172 gimple_stmt_iterator gsi
;
2174 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
2176 gimple stmt
= gsi_stmt (gsi
);
2179 if (is_gimple_call (stmt
))
2181 if ((gimple_call_flags (stmt
) & ECF_NORETURN
)
2182 && has_return_edges
)
2183 predict_paths_leading_to (bb
, PRED_NORETURN
,
2185 decl
= gimple_call_fndecl (stmt
);
2187 && lookup_attribute ("cold",
2188 DECL_ATTRIBUTES (decl
)))
2189 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
2192 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
2194 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
2195 gimple_predict_outcome (stmt
));
2196 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2197 hints to callers. */
2203 #ifdef ENABLE_CHECKING
2205 /* Callback for pointer_map_traverse, asserts that the pointer map is
2209 assert_is_empty (const void *key ATTRIBUTE_UNUSED
, void **value
,
2210 void *data ATTRIBUTE_UNUSED
)
2212 gcc_assert (!*value
);
2217 /* Predict branch probabilities and estimate profile for basic block BB. */
2220 tree_estimate_probability_bb (basic_block bb
)
2226 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2228 /* Predict edges to user labels with attributes. */
2229 if (e
->dest
!= EXIT_BLOCK_PTR
)
2231 gimple_stmt_iterator gi
;
2232 for (gi
= gsi_start_bb (e
->dest
); !gsi_end_p (gi
); gsi_next (&gi
))
2234 gimple stmt
= gsi_stmt (gi
);
2237 if (gimple_code (stmt
) != GIMPLE_LABEL
)
2239 decl
= gimple_label_label (stmt
);
2240 if (DECL_ARTIFICIAL (decl
))
2243 /* Finally, we have a user-defined label. */
2244 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl
)))
2245 predict_edge_def (e
, PRED_COLD_LABEL
, NOT_TAKEN
);
2246 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl
)))
2247 predict_edge_def (e
, PRED_HOT_LABEL
, TAKEN
);
2251 /* Predict early returns to be probable, as we've already taken
2252 care for error returns and other cases are often used for
2253 fast paths through function.
2255 Since we've already removed the return statements, we are
2256 looking for CFG like:
2266 if (e
->dest
!= bb
->next_bb
2267 && e
->dest
!= EXIT_BLOCK_PTR
2268 && single_succ_p (e
->dest
)
2269 && single_succ_edge (e
->dest
)->dest
== EXIT_BLOCK_PTR
2270 && (last
= last_stmt (e
->dest
)) != NULL
2271 && gimple_code (last
) == GIMPLE_RETURN
)
2276 if (single_succ_p (bb
))
2278 FOR_EACH_EDGE (e1
, ei1
, bb
->preds
)
2279 if (!predicted_by_p (e1
->src
, PRED_NULL_RETURN
)
2280 && !predicted_by_p (e1
->src
, PRED_CONST_RETURN
)
2281 && !predicted_by_p (e1
->src
, PRED_NEGATIVE_RETURN
))
2282 predict_edge_def (e1
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2285 if (!predicted_by_p (e
->src
, PRED_NULL_RETURN
)
2286 && !predicted_by_p (e
->src
, PRED_CONST_RETURN
)
2287 && !predicted_by_p (e
->src
, PRED_NEGATIVE_RETURN
))
2288 predict_edge_def (e
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2291 /* Look for block we are guarding (ie we dominate it,
2292 but it doesn't postdominate us). */
2293 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
2294 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
2295 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
2297 gimple_stmt_iterator bi
;
2299 /* The call heuristic claims that a guarded function call
2300 is improbable. This is because such calls are often used
2301 to signal exceptional situations such as printing error
2303 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
2306 gimple stmt
= gsi_stmt (bi
);
2307 if (is_gimple_call (stmt
)
2308 /* Constant and pure calls are hardly used to signalize
2309 something exceptional. */
2310 && gimple_has_side_effects (stmt
))
2312 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
2318 tree_predict_by_opcode (bb
);
2321 /* Predict branch probabilities and estimate profile of the tree CFG.
2322 This function can be called from the loop optimizers to recompute
2323 the profile information. */
2326 tree_estimate_probability (void)
2330 add_noreturn_fake_exit_edges ();
2331 connect_infinite_loops_to_exit ();
2332 /* We use loop_niter_by_eval, which requires that the loops have
2334 create_preheaders (CP_SIMPLE_PREHEADERS
);
2335 calculate_dominance_info (CDI_POST_DOMINATORS
);
2337 bb_predictions
= pointer_map_create ();
2338 tree_bb_level_predictions ();
2339 record_loop_exits ();
2341 if (number_of_loops () > 1)
2345 tree_estimate_probability_bb (bb
);
2348 combine_predictions_for_bb (bb
);
2350 #ifdef ENABLE_CHECKING
2351 pointer_map_traverse (bb_predictions
, assert_is_empty
, NULL
);
2353 pointer_map_destroy (bb_predictions
);
2354 bb_predictions
= NULL
;
2356 estimate_bb_frequencies ();
2357 free_dominance_info (CDI_POST_DOMINATORS
);
2358 remove_fake_exit_edges ();
2361 /* Predict branch probabilities and estimate profile of the tree CFG.
2362 This is the driver function for PASS_PROFILE. */
2365 tree_estimate_probability_driver (void)
2369 loop_optimizer_init (LOOPS_NORMAL
);
2370 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2371 flow_loops_dump (dump_file
, NULL
, 0);
2373 mark_irreducible_loops ();
2375 nb_loops
= number_of_loops ();
2379 tree_estimate_probability ();
2384 loop_optimizer_finalize ();
2385 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2386 gimple_dump_cfg (dump_file
, dump_flags
);
2387 if (profile_status
== PROFILE_ABSENT
)
2388 profile_status
= PROFILE_GUESSED
;
2392 /* Predict edges to successors of CUR whose sources are not postdominated by
2393 BB by PRED and recurse to all postdominators. */
2396 predict_paths_for_bb (basic_block cur
, basic_block bb
,
2397 enum br_predictor pred
,
2398 enum prediction taken
,
2405 /* We are looking for all edges forming edge cut induced by
2406 set of all blocks postdominated by BB. */
2407 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
2408 if (e
->src
->index
>= NUM_FIXED_BLOCKS
2409 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
2415 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2416 if (e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2418 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
2420 /* See if there is an edge from e->src that is not abnormal
2421 and does not lead to BB. */
2422 FOR_EACH_EDGE (e2
, ei2
, e
->src
->succs
)
2424 && !(e2
->flags
& (EDGE_EH
| EDGE_FAKE
))
2425 && !dominated_by_p (CDI_POST_DOMINATORS
, e2
->dest
, bb
))
2431 /* If there is non-abnormal path leaving e->src, predict edge
2432 using predictor. Otherwise we need to look for paths
2435 The second may lead to infinite loop in the case we are predicitng
2436 regions that are only reachable by abnormal edges. We simply
2437 prevent visiting given BB twice. */
2439 predict_edge_def (e
, pred
, taken
);
2440 else if (bitmap_set_bit (visited
, e
->src
->index
))
2441 predict_paths_for_bb (e
->src
, e
->src
, pred
, taken
, visited
);
2443 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
2445 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
2446 predict_paths_for_bb (son
, bb
, pred
, taken
, visited
);
2449 /* Sets branch probabilities according to PREDiction and
2453 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
2454 enum prediction taken
)
2456 bitmap visited
= BITMAP_ALLOC (NULL
);
2457 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2458 BITMAP_FREE (visited
);
2461 /* Like predict_paths_leading_to but take edge instead of basic block. */
2464 predict_paths_leading_to_edge (edge e
, enum br_predictor pred
,
2465 enum prediction taken
)
2467 bool has_nonloop_edge
= false;
2471 basic_block bb
= e
->src
;
2472 FOR_EACH_EDGE (e2
, ei
, bb
->succs
)
2473 if (e2
->dest
!= e
->src
&& e2
->dest
!= e
->dest
2474 && !(e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2475 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e2
->dest
))
2477 has_nonloop_edge
= true;
2480 if (!has_nonloop_edge
)
2482 bitmap visited
= BITMAP_ALLOC (NULL
);
2483 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2484 BITMAP_FREE (visited
);
2487 predict_edge_def (e
, pred
, taken
);
2490 /* This is used to carry information about basic blocks. It is
2491 attached to the AUX field of the standard CFG block. */
2493 typedef struct block_info_def
2495 /* Estimated frequency of execution of basic_block. */
2498 /* To keep queue of basic blocks to process. */
2501 /* Number of predecessors we need to visit first. */
2505 /* Similar information for edges. */
2506 typedef struct edge_info_def
2508 /* In case edge is a loopback edge, the probability edge will be reached
2509 in case header is. Estimated number of iterations of the loop can be
2510 then computed as 1 / (1 - back_edge_prob). */
2511 sreal back_edge_prob
;
2512 /* True if the edge is a loopback edge in the natural loop. */
2513 unsigned int back_edge
:1;
2516 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2517 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2519 /* Helper function for estimate_bb_frequencies.
2520 Propagate the frequencies in blocks marked in
2521 TOVISIT, starting in HEAD. */
2524 propagate_freq (basic_block head
, bitmap tovisit
)
2533 /* For each basic block we need to visit count number of his predecessors
2534 we need to visit first. */
2535 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
2540 bb
= BASIC_BLOCK (i
);
2542 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2544 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
2546 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
2548 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
2550 "Irreducible region hit, ignoring edge to %i->%i\n",
2551 e
->src
->index
, bb
->index
);
2553 BLOCK_INFO (bb
)->npredecessors
= count
;
2554 /* When function never returns, we will never process exit block. */
2555 if (!count
&& bb
== EXIT_BLOCK_PTR
)
2556 bb
->count
= bb
->frequency
= 0;
2559 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
2561 for (bb
= head
; bb
; bb
= nextbb
)
2564 sreal cyclic_probability
, frequency
;
2566 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
2567 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
2569 nextbb
= BLOCK_INFO (bb
)->next
;
2570 BLOCK_INFO (bb
)->next
= NULL
;
2572 /* Compute frequency of basic block. */
2575 #ifdef ENABLE_CHECKING
2576 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2577 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
2578 || (e
->flags
& EDGE_DFS_BACK
));
2581 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2582 if (EDGE_INFO (e
)->back_edge
)
2584 sreal_add (&cyclic_probability
, &cyclic_probability
,
2585 &EDGE_INFO (e
)->back_edge_prob
);
2587 else if (!(e
->flags
& EDGE_DFS_BACK
))
2591 /* frequency += (e->probability
2592 * BLOCK_INFO (e->src)->frequency /
2593 REG_BR_PROB_BASE); */
2595 sreal_init (&tmp
, e
->probability
, 0);
2596 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
2597 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
2598 sreal_add (&frequency
, &frequency
, &tmp
);
2601 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
2603 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
2604 sizeof (frequency
));
2608 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
2610 memcpy (&cyclic_probability
, &real_almost_one
,
2611 sizeof (real_almost_one
));
2614 /* BLOCK_INFO (bb)->frequency = frequency
2615 / (1 - cyclic_probability) */
2617 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
2618 sreal_div (&BLOCK_INFO (bb
)->frequency
,
2619 &frequency
, &cyclic_probability
);
2623 bitmap_clear_bit (tovisit
, bb
->index
);
2625 e
= find_edge (bb
, head
);
2630 /* EDGE_INFO (e)->back_edge_prob
2631 = ((e->probability * BLOCK_INFO (bb)->frequency)
2632 / REG_BR_PROB_BASE); */
2634 sreal_init (&tmp
, e
->probability
, 0);
2635 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
2636 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2637 &tmp
, &real_inv_br_prob_base
);
2640 /* Propagate to successor blocks. */
2641 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2642 if (!(e
->flags
& EDGE_DFS_BACK
)
2643 && BLOCK_INFO (e
->dest
)->npredecessors
)
2645 BLOCK_INFO (e
->dest
)->npredecessors
--;
2646 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
2651 BLOCK_INFO (last
)->next
= e
->dest
;
2659 /* Estimate probabilities of loopback edges in loops at same nest level. */
2662 estimate_loops_at_level (struct loop
*first_loop
)
2666 for (loop
= first_loop
; loop
; loop
= loop
->next
)
2671 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2673 estimate_loops_at_level (loop
->inner
);
2675 /* Find current loop back edge and mark it. */
2676 e
= loop_latch_edge (loop
);
2677 EDGE_INFO (e
)->back_edge
= 1;
2679 bbs
= get_loop_body (loop
);
2680 for (i
= 0; i
< loop
->num_nodes
; i
++)
2681 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
2683 propagate_freq (loop
->header
, tovisit
);
2684 BITMAP_FREE (tovisit
);
2688 /* Propagates frequencies through structure of loops. */
2691 estimate_loops (void)
2693 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2696 /* Start by estimating the frequencies in the loops. */
2697 if (number_of_loops () > 1)
2698 estimate_loops_at_level (current_loops
->tree_root
->inner
);
2700 /* Now propagate the frequencies through all the blocks. */
2703 bitmap_set_bit (tovisit
, bb
->index
);
2705 propagate_freq (ENTRY_BLOCK_PTR
, tovisit
);
2706 BITMAP_FREE (tovisit
);
2709 /* Convert counts measured by profile driven feedback to frequencies.
2710 Return nonzero iff there was any nonzero execution count. */
2713 counts_to_freqs (void)
2715 gcov_type count_max
, true_count_max
= 0;
2718 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2719 true_count_max
= MAX (bb
->count
, true_count_max
);
2721 count_max
= MAX (true_count_max
, 1);
2722 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2723 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
2725 return true_count_max
;
2728 /* Return true if function is likely to be expensive, so there is no point to
2729 optimize performance of prologue, epilogue or do inlining at the expense
2730 of code size growth. THRESHOLD is the limit of number of instructions
2731 function can execute at average to be still considered not expensive. */
2734 expensive_function_p (int threshold
)
2736 unsigned int sum
= 0;
2740 /* We can not compute accurately for large thresholds due to scaled
2742 gcc_assert (threshold
<= BB_FREQ_MAX
);
2744 /* Frequencies are out of range. This either means that function contains
2745 internal loop executing more than BB_FREQ_MAX times or profile feedback
2746 is available and function has not been executed at all. */
2747 if (ENTRY_BLOCK_PTR
->frequency
== 0)
2750 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2751 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
2756 FOR_BB_INSNS (bb
, insn
)
2757 if (active_insn_p (insn
))
2759 sum
+= bb
->frequency
;
2768 /* Estimate basic blocks frequency by given branch probabilities. */
2771 estimate_bb_frequencies (void)
2776 if (profile_status
!= PROFILE_READ
|| !counts_to_freqs ())
2778 static int real_values_initialized
= 0;
2780 if (!real_values_initialized
)
2782 real_values_initialized
= 1;
2783 sreal_init (&real_zero
, 0, 0);
2784 sreal_init (&real_one
, 1, 0);
2785 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
2786 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
2787 sreal_init (&real_one_half
, 1, -1);
2788 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
2789 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
2792 mark_dfs_back_edges ();
2794 single_succ_edge (ENTRY_BLOCK_PTR
)->probability
= REG_BR_PROB_BASE
;
2796 /* Set up block info for each basic block. */
2797 alloc_aux_for_blocks (sizeof (struct block_info_def
));
2798 alloc_aux_for_edges (sizeof (struct edge_info_def
));
2799 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2804 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2806 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
2807 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2808 &EDGE_INFO (e
)->back_edge_prob
,
2809 &real_inv_br_prob_base
);
2813 /* First compute probabilities locally for each loop from innermost
2814 to outermost to examine probabilities for back edges. */
2817 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
2819 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
2820 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
2822 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
2823 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2827 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
2828 sreal_add (&tmp
, &tmp
, &real_one_half
);
2829 bb
->frequency
= sreal_to_int (&tmp
);
2832 free_aux_for_blocks ();
2833 free_aux_for_edges ();
2835 compute_function_frequency ();
2838 /* Decide whether function is hot, cold or unlikely executed. */
2840 compute_function_frequency (void)
2843 struct cgraph_node
*node
= cgraph_get_node (current_function_decl
);
2844 if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2845 || MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2846 node
->only_called_at_startup
= true;
2847 if (DECL_STATIC_DESTRUCTOR (current_function_decl
))
2848 node
->only_called_at_exit
= true;
2850 if (!profile_info
|| !flag_branch_probabilities
)
2852 int flags
= flags_from_decl_or_type (current_function_decl
);
2853 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
2855 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2856 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
2858 node
->frequency
= NODE_FREQUENCY_HOT
;
2859 else if (flags
& ECF_NORETURN
)
2860 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2861 else if (MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2862 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2863 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2864 || DECL_STATIC_DESTRUCTOR (current_function_decl
))
2865 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2868 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2871 if (maybe_hot_bb_p (cfun
, bb
))
2873 node
->frequency
= NODE_FREQUENCY_HOT
;
2876 if (!probably_never_executed_bb_p (cfun
, bb
))
2877 node
->frequency
= NODE_FREQUENCY_NORMAL
;
2882 gate_estimate_probability (void)
2884 return flag_guess_branch_prob
;
2887 /* Build PREDICT_EXPR. */
2889 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
2891 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
2892 build_int_cst (integer_type_node
, predictor
));
2893 SET_PREDICT_EXPR_OUTCOME (t
, taken
);
2898 predictor_name (enum br_predictor predictor
)
2900 return predictor_info
[predictor
].name
;
2903 struct gimple_opt_pass pass_profile
=
2907 "profile_estimate", /* name */
2908 OPTGROUP_NONE
, /* optinfo_flags */
2909 gate_estimate_probability
, /* gate */
2910 tree_estimate_probability_driver
, /* execute */
2913 0, /* static_pass_number */
2914 TV_BRANCH_PROB
, /* tv_id */
2915 PROP_cfg
, /* properties_required */
2916 0, /* properties_provided */
2917 0, /* properties_destroyed */
2918 0, /* todo_flags_start */
2919 TODO_verify_ssa
/* todo_flags_finish */
2923 struct gimple_opt_pass pass_strip_predict_hints
=
2927 "*strip_predict_hints", /* name */
2928 OPTGROUP_NONE
, /* optinfo_flags */
2930 strip_predict_hints
, /* execute */
2933 0, /* static_pass_number */
2934 TV_BRANCH_PROB
, /* tv_id */
2935 PROP_cfg
, /* properties_required */
2936 0, /* properties_provided */
2937 0, /* properties_destroyed */
2938 0, /* todo_flags_start */
2939 TODO_verify_ssa
/* todo_flags_finish */
2943 /* Rebuild function frequencies. Passes are in general expected to
2944 maintain profile by hand, however in some cases this is not possible:
2945 for example when inlining several functions with loops freuqencies might run
2946 out of scale and thus needs to be recomputed. */
2949 rebuild_frequencies (void)
2951 timevar_push (TV_REBUILD_FREQUENCIES
);
2952 if (profile_status
== PROFILE_GUESSED
)
2954 loop_optimizer_init (0);
2955 add_noreturn_fake_exit_edges ();
2956 mark_irreducible_loops ();
2957 connect_infinite_loops_to_exit ();
2958 estimate_bb_frequencies ();
2959 remove_fake_exit_edges ();
2960 loop_optimizer_finalize ();
2962 else if (profile_status
== PROFILE_READ
)
2966 timevar_pop (TV_REBUILD_FREQUENCIES
);