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 (freq
< (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun
)->frequency
126 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
131 /* Return TRUE if frequency FREQ is considered to be hot. */
134 maybe_hot_count_p (struct function
*fun
, gcov_type count
)
136 gcov_working_set_t
*ws
;
137 static gcov_type min_count
= -1;
138 if (fun
&& profile_status_for_function (fun
) != PROFILE_READ
)
140 /* Code executed at most once is not hot. */
141 if (profile_info
->runs
>= count
)
145 ws
= find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE
));
147 min_count
= ws
->min_counter
;
149 return (count
>= min_count
);
152 /* Return true in case BB can be CPU intensive and should be optimized
153 for maximal performance. */
156 maybe_hot_bb_p (struct function
*fun
, const_basic_block bb
)
158 gcc_checking_assert (fun
);
159 if (profile_status_for_function (fun
) == PROFILE_READ
)
160 return maybe_hot_count_p (fun
, bb
->count
);
161 return maybe_hot_frequency_p (fun
, bb
->frequency
);
164 /* Return true if the call can be hot. */
167 cgraph_maybe_hot_edge_p (struct cgraph_edge
*edge
)
169 if (profile_info
&& flag_branch_probabilities
170 && !maybe_hot_count_p (NULL
,
173 if (edge
->caller
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
175 && edge
->callee
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
177 if (edge
->caller
->frequency
> NODE_FREQUENCY_UNLIKELY_EXECUTED
179 && edge
->callee
->frequency
<= NODE_FREQUENCY_EXECUTED_ONCE
))
183 if (edge
->caller
->frequency
== NODE_FREQUENCY_HOT
)
185 if (edge
->caller
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
186 && edge
->frequency
< CGRAPH_FREQ_BASE
* 3 / 2)
188 if (flag_guess_branch_prob
189 && edge
->frequency
<= (CGRAPH_FREQ_BASE
190 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
195 /* Return true in case BB can be CPU intensive and should be optimized
196 for maximal performance. */
199 maybe_hot_edge_p (edge e
)
201 if (profile_status
== PROFILE_READ
)
202 return maybe_hot_count_p (cfun
, e
->count
);
203 return maybe_hot_frequency_p (cfun
, EDGE_FREQUENCY (e
));
207 /* Return true in case BB is probably never executed. */
210 probably_never_executed_bb_p (struct function
*fun
, const_basic_block bb
)
212 gcc_checking_assert (fun
);
213 if (profile_info
&& flag_branch_probabilities
)
214 return ((bb
->count
+ profile_info
->runs
/ 2) / profile_info
->runs
) == 0;
215 if ((!profile_info
|| !flag_branch_probabilities
)
216 && (cgraph_get_node (fun
->decl
)->frequency
217 == NODE_FREQUENCY_UNLIKELY_EXECUTED
))
222 /* Return true if NODE should be optimized for size. */
225 cgraph_optimize_for_size_p (struct cgraph_node
*node
)
229 if (node
&& (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
235 /* Return true when current function should always be optimized for size. */
238 optimize_function_for_size_p (struct function
*fun
)
242 if (!fun
|| !fun
->decl
)
244 return cgraph_optimize_for_size_p (cgraph_get_node (fun
->decl
));
247 /* Return true when current function should always be optimized for speed. */
250 optimize_function_for_speed_p (struct function
*fun
)
252 return !optimize_function_for_size_p (fun
);
255 /* Return TRUE when BB should be optimized for size. */
258 optimize_bb_for_size_p (const_basic_block bb
)
260 return optimize_function_for_size_p (cfun
) || !maybe_hot_bb_p (cfun
, bb
);
263 /* Return TRUE when BB should be optimized for speed. */
266 optimize_bb_for_speed_p (const_basic_block bb
)
268 return !optimize_bb_for_size_p (bb
);
271 /* Return TRUE when BB should be optimized for size. */
274 optimize_edge_for_size_p (edge e
)
276 return optimize_function_for_size_p (cfun
) || !maybe_hot_edge_p (e
);
279 /* Return TRUE when BB should be optimized for speed. */
282 optimize_edge_for_speed_p (edge e
)
284 return !optimize_edge_for_size_p (e
);
287 /* Return TRUE when BB should be optimized for size. */
290 optimize_insn_for_size_p (void)
292 return optimize_function_for_size_p (cfun
) || !crtl
->maybe_hot_insn_p
;
295 /* Return TRUE when BB should be optimized for speed. */
298 optimize_insn_for_speed_p (void)
300 return !optimize_insn_for_size_p ();
303 /* Return TRUE when LOOP should be optimized for size. */
306 optimize_loop_for_size_p (struct loop
*loop
)
308 return optimize_bb_for_size_p (loop
->header
);
311 /* Return TRUE when LOOP should be optimized for speed. */
314 optimize_loop_for_speed_p (struct loop
*loop
)
316 return optimize_bb_for_speed_p (loop
->header
);
319 /* Return TRUE when LOOP nest should be optimized for speed. */
322 optimize_loop_nest_for_speed_p (struct loop
*loop
)
324 struct loop
*l
= loop
;
325 if (optimize_loop_for_speed_p (loop
))
328 while (l
&& l
!= loop
)
330 if (optimize_loop_for_speed_p (l
))
338 while (l
!= loop
&& !l
->next
)
347 /* Return TRUE when LOOP nest should be optimized for size. */
350 optimize_loop_nest_for_size_p (struct loop
*loop
)
352 return !optimize_loop_nest_for_speed_p (loop
);
355 /* Return true when edge E is likely to be well predictable by branch
359 predictable_edge_p (edge e
)
361 if (profile_status
== PROFILE_ABSENT
)
364 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100)
365 || (REG_BR_PROB_BASE
- e
->probability
366 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100))
372 /* Set RTL expansion for BB profile. */
375 rtl_profile_for_bb (basic_block bb
)
377 crtl
->maybe_hot_insn_p
= maybe_hot_bb_p (cfun
, bb
);
380 /* Set RTL expansion for edge profile. */
383 rtl_profile_for_edge (edge e
)
385 crtl
->maybe_hot_insn_p
= maybe_hot_edge_p (e
);
388 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
390 default_rtl_profile (void)
392 crtl
->maybe_hot_insn_p
= true;
395 /* Return true if the one of outgoing edges is already predicted by
399 rtl_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
402 if (!INSN_P (BB_END (bb
)))
404 for (note
= REG_NOTES (BB_END (bb
)); note
; note
= XEXP (note
, 1))
405 if (REG_NOTE_KIND (note
) == REG_BR_PRED
406 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
411 /* This map contains for a basic block the list of predictions for the
414 static struct pointer_map_t
*bb_predictions
;
416 /* Structure representing predictions in tree level. */
418 struct edge_prediction
{
419 struct edge_prediction
*ep_next
;
421 enum br_predictor ep_predictor
;
425 /* Return true if the one of outgoing edges is already predicted by
429 gimple_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
431 struct edge_prediction
*i
;
432 void **preds
= pointer_map_contains (bb_predictions
, bb
);
437 for (i
= (struct edge_prediction
*) *preds
; i
; i
= i
->ep_next
)
438 if (i
->ep_predictor
== predictor
)
443 /* Return true when the probability of edge is reliable.
445 The profile guessing code is good at predicting branch outcome (ie.
446 taken/not taken), that is predicted right slightly over 75% of time.
447 It is however notoriously poor on predicting the probability itself.
448 In general the profile appear a lot flatter (with probabilities closer
449 to 50%) than the reality so it is bad idea to use it to drive optimization
450 such as those disabling dynamic branch prediction for well predictable
453 There are two exceptions - edges leading to noreturn edges and edges
454 predicted by number of iterations heuristics are predicted well. This macro
455 should be able to distinguish those, but at the moment it simply check for
456 noreturn heuristic that is only one giving probability over 99% or bellow
457 1%. In future we might want to propagate reliability information across the
458 CFG if we find this information useful on multiple places. */
460 probability_reliable_p (int prob
)
462 return (profile_status
== PROFILE_READ
463 || (profile_status
== PROFILE_GUESSED
464 && (prob
<= HITRATE (1) || prob
>= HITRATE (99))));
467 /* Same predicate as above, working on edges. */
469 edge_probability_reliable_p (const_edge e
)
471 return probability_reliable_p (e
->probability
);
474 /* Same predicate as edge_probability_reliable_p, working on notes. */
476 br_prob_note_reliable_p (const_rtx note
)
478 gcc_assert (REG_NOTE_KIND (note
) == REG_BR_PROB
);
479 return probability_reliable_p (INTVAL (XEXP (note
, 0)));
483 predict_insn (rtx insn
, enum br_predictor predictor
, int probability
)
485 gcc_assert (any_condjump_p (insn
));
486 if (!flag_guess_branch_prob
)
489 add_reg_note (insn
, REG_BR_PRED
,
490 gen_rtx_CONCAT (VOIDmode
,
491 GEN_INT ((int) predictor
),
492 GEN_INT ((int) probability
)));
495 /* Predict insn by given predictor. */
498 predict_insn_def (rtx insn
, enum br_predictor predictor
,
499 enum prediction taken
)
501 int probability
= predictor_info
[(int) predictor
].hitrate
;
504 probability
= REG_BR_PROB_BASE
- probability
;
506 predict_insn (insn
, predictor
, probability
);
509 /* Predict edge E with given probability if possible. */
512 rtl_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
515 last_insn
= BB_END (e
->src
);
517 /* We can store the branch prediction information only about
518 conditional jumps. */
519 if (!any_condjump_p (last_insn
))
522 /* We always store probability of branching. */
523 if (e
->flags
& EDGE_FALLTHRU
)
524 probability
= REG_BR_PROB_BASE
- probability
;
526 predict_insn (last_insn
, predictor
, probability
);
529 /* Predict edge E with the given PROBABILITY. */
531 gimple_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
533 gcc_assert (profile_status
!= PROFILE_GUESSED
);
534 if ((e
->src
!= ENTRY_BLOCK_PTR
&& EDGE_COUNT (e
->src
->succs
) > 1)
535 && flag_guess_branch_prob
&& optimize
)
537 struct edge_prediction
*i
= XNEW (struct edge_prediction
);
538 void **preds
= pointer_map_insert (bb_predictions
, e
->src
);
540 i
->ep_next
= (struct edge_prediction
*) *preds
;
542 i
->ep_probability
= probability
;
543 i
->ep_predictor
= predictor
;
548 /* Remove all predictions on given basic block that are attached
551 remove_predictions_associated_with_edge (edge e
)
558 preds
= pointer_map_contains (bb_predictions
, e
->src
);
562 struct edge_prediction
**prediction
= (struct edge_prediction
**) preds
;
563 struct edge_prediction
*next
;
567 if ((*prediction
)->ep_edge
== e
)
569 next
= (*prediction
)->ep_next
;
574 prediction
= &((*prediction
)->ep_next
);
579 /* Clears the list of predictions stored for BB. */
582 clear_bb_predictions (basic_block bb
)
584 void **preds
= pointer_map_contains (bb_predictions
, bb
);
585 struct edge_prediction
*pred
, *next
;
590 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= next
)
592 next
= pred
->ep_next
;
598 /* Return true when we can store prediction on insn INSN.
599 At the moment we represent predictions only on conditional
600 jumps, not at computed jump or other complicated cases. */
602 can_predict_insn_p (const_rtx insn
)
604 return (JUMP_P (insn
)
605 && any_condjump_p (insn
)
606 && EDGE_COUNT (BLOCK_FOR_INSN (insn
)->succs
) >= 2);
609 /* Predict edge E by given predictor if possible. */
612 predict_edge_def (edge e
, enum br_predictor predictor
,
613 enum prediction taken
)
615 int probability
= predictor_info
[(int) predictor
].hitrate
;
618 probability
= REG_BR_PROB_BASE
- probability
;
620 predict_edge (e
, predictor
, probability
);
623 /* Invert all branch predictions or probability notes in the INSN. This needs
624 to be done each time we invert the condition used by the jump. */
627 invert_br_probabilities (rtx insn
)
631 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
632 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
633 XEXP (note
, 0) = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (note
, 0)));
634 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
635 XEXP (XEXP (note
, 0), 1)
636 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
639 /* Dump information about the branch prediction to the output file. */
642 dump_prediction (FILE *file
, enum br_predictor predictor
, int probability
,
643 basic_block bb
, int used
)
651 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
652 if (! (e
->flags
& EDGE_FALLTHRU
))
655 fprintf (file
, " %s heuristics%s: %.1f%%",
656 predictor_info
[predictor
].name
,
657 used
? "" : " (ignored)", probability
* 100.0 / REG_BR_PROB_BASE
);
661 fprintf (file
, " exec ");
662 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, bb
->count
);
665 fprintf (file
, " hit ");
666 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, e
->count
);
667 fprintf (file
, " (%.1f%%)", e
->count
* 100.0 / bb
->count
);
671 fprintf (file
, "\n");
674 /* We can not predict the probabilities of outgoing edges of bb. Set them
675 evenly and hope for the best. */
677 set_even_probabilities (basic_block bb
)
683 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
684 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
686 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
687 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
688 e
->probability
= (REG_BR_PROB_BASE
+ nedges
/ 2) / nedges
;
693 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
694 note if not already present. Remove now useless REG_BR_PRED notes. */
697 combine_predictions_for_insn (rtx insn
, basic_block bb
)
702 int best_probability
= PROB_EVEN
;
703 enum br_predictor best_predictor
= END_PREDICTORS
;
704 int combined_probability
= REG_BR_PROB_BASE
/ 2;
706 bool first_match
= false;
709 if (!can_predict_insn_p (insn
))
711 set_even_probabilities (bb
);
715 prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
716 pnote
= ®_NOTES (insn
);
718 fprintf (dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
721 /* We implement "first match" heuristics and use probability guessed
722 by predictor with smallest index. */
723 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
724 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
726 enum br_predictor predictor
= ((enum br_predictor
)
727 INTVAL (XEXP (XEXP (note
, 0), 0)));
728 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
731 if (best_predictor
> predictor
)
732 best_probability
= probability
, best_predictor
= predictor
;
734 d
= (combined_probability
* probability
735 + (REG_BR_PROB_BASE
- combined_probability
)
736 * (REG_BR_PROB_BASE
- probability
));
738 /* Use FP math to avoid overflows of 32bit integers. */
740 /* If one probability is 0% and one 100%, avoid division by zero. */
741 combined_probability
= REG_BR_PROB_BASE
/ 2;
743 combined_probability
= (((double) combined_probability
) * probability
744 * REG_BR_PROB_BASE
/ d
+ 0.5);
747 /* Decide which heuristic to use. In case we didn't match anything,
748 use no_prediction heuristic, in case we did match, use either
749 first match or Dempster-Shaffer theory depending on the flags. */
751 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
755 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
756 combined_probability
, bb
, true);
759 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
761 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
766 combined_probability
= best_probability
;
767 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
771 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
773 enum br_predictor predictor
= ((enum br_predictor
)
774 INTVAL (XEXP (XEXP (*pnote
, 0), 0)));
775 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
777 dump_prediction (dump_file
, predictor
, probability
, bb
,
778 !first_match
|| best_predictor
== predictor
);
779 *pnote
= XEXP (*pnote
, 1);
782 pnote
= &XEXP (*pnote
, 1);
787 add_reg_note (insn
, REG_BR_PROB
, GEN_INT (combined_probability
));
789 /* Save the prediction into CFG in case we are seeing non-degenerated
791 if (!single_succ_p (bb
))
793 BRANCH_EDGE (bb
)->probability
= combined_probability
;
794 FALLTHRU_EDGE (bb
)->probability
795 = REG_BR_PROB_BASE
- combined_probability
;
798 else if (!single_succ_p (bb
))
800 int prob
= INTVAL (XEXP (prob_note
, 0));
802 BRANCH_EDGE (bb
)->probability
= prob
;
803 FALLTHRU_EDGE (bb
)->probability
= REG_BR_PROB_BASE
- prob
;
806 single_succ_edge (bb
)->probability
= REG_BR_PROB_BASE
;
809 /* Combine predictions into single probability and store them into CFG.
810 Remove now useless prediction entries. */
813 combine_predictions_for_bb (basic_block bb
)
815 int best_probability
= PROB_EVEN
;
816 enum br_predictor best_predictor
= END_PREDICTORS
;
817 int combined_probability
= REG_BR_PROB_BASE
/ 2;
819 bool first_match
= false;
821 struct edge_prediction
*pred
;
823 edge e
, first
= NULL
, second
= NULL
;
827 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
828 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
831 if (first
&& !second
)
837 /* When there is no successor or only one choice, prediction is easy.
839 We are lazy for now and predict only basic blocks with two outgoing
840 edges. It is possible to predict generic case too, but we have to
841 ignore first match heuristics and do more involved combining. Implement
846 set_even_probabilities (bb
);
847 clear_bb_predictions (bb
);
849 fprintf (dump_file
, "%i edges in bb %i predicted to even probabilities\n",
855 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
857 preds
= pointer_map_contains (bb_predictions
, bb
);
860 /* We implement "first match" heuristics and use probability guessed
861 by predictor with smallest index. */
862 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
864 enum br_predictor predictor
= pred
->ep_predictor
;
865 int probability
= pred
->ep_probability
;
867 if (pred
->ep_edge
!= first
)
868 probability
= REG_BR_PROB_BASE
- probability
;
871 /* First match heuristics would be widly confused if we predicted
873 if (best_predictor
> predictor
)
875 struct edge_prediction
*pred2
;
876 int prob
= probability
;
878 for (pred2
= (struct edge_prediction
*) *preds
; pred2
; pred2
= pred2
->ep_next
)
879 if (pred2
!= pred
&& pred2
->ep_predictor
== pred
->ep_predictor
)
881 int probability2
= pred
->ep_probability
;
883 if (pred2
->ep_edge
!= first
)
884 probability2
= REG_BR_PROB_BASE
- probability2
;
886 if ((probability
< REG_BR_PROB_BASE
/ 2) !=
887 (probability2
< REG_BR_PROB_BASE
/ 2))
890 /* If the same predictor later gave better result, go for it! */
891 if ((probability
>= REG_BR_PROB_BASE
/ 2 && (probability2
> probability
))
892 || (probability
<= REG_BR_PROB_BASE
/ 2 && (probability2
< probability
)))
896 best_probability
= prob
, best_predictor
= predictor
;
899 d
= (combined_probability
* probability
900 + (REG_BR_PROB_BASE
- combined_probability
)
901 * (REG_BR_PROB_BASE
- probability
));
903 /* Use FP math to avoid overflows of 32bit integers. */
905 /* If one probability is 0% and one 100%, avoid division by zero. */
906 combined_probability
= REG_BR_PROB_BASE
/ 2;
908 combined_probability
= (((double) combined_probability
)
910 * REG_BR_PROB_BASE
/ d
+ 0.5);
914 /* Decide which heuristic to use. In case we didn't match anything,
915 use no_prediction heuristic, in case we did match, use either
916 first match or Dempster-Shaffer theory depending on the flags. */
918 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
922 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
, true);
925 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
927 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
932 combined_probability
= best_probability
;
933 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
937 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
939 enum br_predictor predictor
= pred
->ep_predictor
;
940 int probability
= pred
->ep_probability
;
942 if (pred
->ep_edge
!= EDGE_SUCC (bb
, 0))
943 probability
= REG_BR_PROB_BASE
- probability
;
944 dump_prediction (dump_file
, predictor
, probability
, bb
,
945 !first_match
|| best_predictor
== predictor
);
948 clear_bb_predictions (bb
);
952 first
->probability
= combined_probability
;
953 second
->probability
= REG_BR_PROB_BASE
- combined_probability
;
957 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
958 Return the SSA_NAME if the condition satisfies, NULL otherwise.
960 T1 and T2 should be one of the following cases:
961 1. T1 is SSA_NAME, T2 is NULL
962 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
963 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
966 strips_small_constant (tree t1
, tree t2
)
973 else if (TREE_CODE (t1
) == SSA_NAME
)
975 else if (host_integerp (t1
, 0))
976 value
= tree_low_cst (t1
, 0);
982 else if (host_integerp (t2
, 0))
983 value
= tree_low_cst (t2
, 0);
984 else if (TREE_CODE (t2
) == SSA_NAME
)
992 if (value
<= 4 && value
>= -4)
998 /* Return the SSA_NAME in T or T's operands.
999 Return NULL if SSA_NAME cannot be found. */
1002 get_base_value (tree t
)
1004 if (TREE_CODE (t
) == SSA_NAME
)
1007 if (!BINARY_CLASS_P (t
))
1010 switch (TREE_OPERAND_LENGTH (t
))
1013 return strips_small_constant (TREE_OPERAND (t
, 0), NULL
);
1015 return strips_small_constant (TREE_OPERAND (t
, 0),
1016 TREE_OPERAND (t
, 1));
1022 /* Check the compare STMT in LOOP. If it compares an induction
1023 variable to a loop invariant, return true, and save
1024 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1025 Otherwise return false and set LOOP_INVAIANT to NULL. */
1028 is_comparison_with_loop_invariant_p (gimple stmt
, struct loop
*loop
,
1029 tree
*loop_invariant
,
1030 enum tree_code
*compare_code
,
1034 tree op0
, op1
, bound
, base
;
1036 enum tree_code code
;
1039 code
= gimple_cond_code (stmt
);
1040 *loop_invariant
= NULL
;
1056 op0
= gimple_cond_lhs (stmt
);
1057 op1
= gimple_cond_rhs (stmt
);
1059 if ((TREE_CODE (op0
) != SSA_NAME
&& TREE_CODE (op0
) != INTEGER_CST
)
1060 || (TREE_CODE (op1
) != SSA_NAME
&& TREE_CODE (op1
) != INTEGER_CST
))
1062 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op0
, &iv0
, true))
1064 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op1
, &iv1
, true))
1066 if (TREE_CODE (iv0
.step
) != INTEGER_CST
1067 || TREE_CODE (iv1
.step
) != INTEGER_CST
)
1069 if ((integer_zerop (iv0
.step
) && integer_zerop (iv1
.step
))
1070 || (!integer_zerop (iv0
.step
) && !integer_zerop (iv1
.step
)))
1073 if (integer_zerop (iv0
.step
))
1075 if (code
!= NE_EXPR
&& code
!= EQ_EXPR
)
1076 code
= invert_tree_comparison (code
, false);
1079 if (host_integerp (iv1
.step
, 0))
1080 step
= tree_low_cst (iv1
.step
, 0);
1088 if (host_integerp (iv0
.step
, 0))
1089 step
= tree_low_cst (iv0
.step
, 0);
1094 if (TREE_CODE (bound
) != INTEGER_CST
)
1095 bound
= get_base_value (bound
);
1098 if (TREE_CODE (base
) != INTEGER_CST
)
1099 base
= get_base_value (base
);
1103 *loop_invariant
= bound
;
1104 *compare_code
= code
;
1106 *loop_iv_base
= base
;
1110 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1113 expr_coherent_p (tree t1
, tree t2
)
1116 tree ssa_name_1
= NULL
;
1117 tree ssa_name_2
= NULL
;
1119 gcc_assert (TREE_CODE (t1
) == SSA_NAME
|| TREE_CODE (t1
) == INTEGER_CST
);
1120 gcc_assert (TREE_CODE (t2
) == SSA_NAME
|| TREE_CODE (t2
) == INTEGER_CST
);
1125 if (TREE_CODE (t1
) == INTEGER_CST
&& TREE_CODE (t2
) == INTEGER_CST
)
1127 if (TREE_CODE (t1
) == INTEGER_CST
|| TREE_CODE (t2
) == INTEGER_CST
)
1130 /* Check to see if t1 is expressed/defined with t2. */
1131 stmt
= SSA_NAME_DEF_STMT (t1
);
1132 gcc_assert (stmt
!= NULL
);
1133 if (is_gimple_assign (stmt
))
1135 ssa_name_1
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1136 if (ssa_name_1
&& ssa_name_1
== t2
)
1140 /* Check to see if t2 is expressed/defined with t1. */
1141 stmt
= SSA_NAME_DEF_STMT (t2
);
1142 gcc_assert (stmt
!= NULL
);
1143 if (is_gimple_assign (stmt
))
1145 ssa_name_2
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1146 if (ssa_name_2
&& ssa_name_2
== t1
)
1150 /* Compare if t1 and t2's def_stmts are identical. */
1151 if (ssa_name_2
!= NULL
&& ssa_name_1
== ssa_name_2
)
1157 /* Predict branch probability of BB when BB contains a branch that compares
1158 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1159 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1162 for (int i = 0; i < bound; i++) {
1169 In this loop, we will predict the branch inside the loop to be taken. */
1172 predict_iv_comparison (struct loop
*loop
, basic_block bb
,
1173 tree loop_bound_var
,
1174 tree loop_iv_base_var
,
1175 enum tree_code loop_bound_code
,
1176 int loop_bound_step
)
1179 tree compare_var
, compare_base
;
1180 enum tree_code compare_code
;
1185 if (predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1186 || predicted_by_p (bb
, PRED_LOOP_ITERATIONS
)
1187 || predicted_by_p (bb
, PRED_LOOP_EXIT
))
1190 stmt
= last_stmt (bb
);
1191 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1193 if (!is_comparison_with_loop_invariant_p (stmt
, loop
, &compare_var
,
1199 /* Find the taken edge. */
1200 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1201 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1204 /* When comparing an IV to a loop invariant, NE is more likely to be
1205 taken while EQ is more likely to be not-taken. */
1206 if (compare_code
== NE_EXPR
)
1208 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1211 else if (compare_code
== EQ_EXPR
)
1213 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1217 if (!expr_coherent_p (loop_iv_base_var
, compare_base
))
1220 /* If loop bound, base and compare bound are all constants, we can
1221 calculate the probability directly. */
1222 if (host_integerp (loop_bound_var
, 0)
1223 && host_integerp (compare_var
, 0)
1224 && host_integerp (compare_base
, 0))
1227 HOST_WIDE_INT compare_count
;
1228 HOST_WIDE_INT loop_bound
= tree_low_cst (loop_bound_var
, 0);
1229 HOST_WIDE_INT compare_bound
= tree_low_cst (compare_var
, 0);
1230 HOST_WIDE_INT base
= tree_low_cst (compare_base
, 0);
1231 HOST_WIDE_INT loop_count
= (loop_bound
- base
) / compare_step
;
1233 if ((compare_step
> 0)
1234 ^ (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1235 compare_count
= (loop_bound
- compare_bound
) / compare_step
;
1237 compare_count
= (compare_bound
- base
) / compare_step
;
1239 if (compare_code
== LE_EXPR
|| compare_code
== GE_EXPR
)
1241 if (loop_bound_code
== LE_EXPR
|| loop_bound_code
== GE_EXPR
)
1243 if (compare_count
< 0)
1248 if (loop_count
== 0)
1250 else if (compare_count
> loop_count
)
1251 probability
= REG_BR_PROB_BASE
;
1253 probability
= (double) REG_BR_PROB_BASE
* compare_count
/ loop_count
;
1254 predict_edge (then_edge
, PRED_LOOP_IV_COMPARE
, probability
);
1258 if (expr_coherent_p (loop_bound_var
, compare_var
))
1260 if ((loop_bound_code
== LT_EXPR
|| loop_bound_code
== LE_EXPR
)
1261 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1262 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1263 else if ((loop_bound_code
== GT_EXPR
|| loop_bound_code
== GE_EXPR
)
1264 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1265 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1266 else if (loop_bound_code
== NE_EXPR
)
1268 /* If the loop backedge condition is "(i != bound)", we do
1269 the comparison based on the step of IV:
1270 * step < 0 : backedge condition is like (i > bound)
1271 * step > 0 : backedge condition is like (i < bound) */
1272 gcc_assert (loop_bound_step
!= 0);
1273 if (loop_bound_step
> 0
1274 && (compare_code
== LT_EXPR
1275 || compare_code
== LE_EXPR
))
1276 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1277 else if (loop_bound_step
< 0
1278 && (compare_code
== GT_EXPR
1279 || compare_code
== GE_EXPR
))
1280 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1282 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1285 /* The branch is predicted not-taken if loop_bound_code is
1286 opposite with compare_code. */
1287 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1289 else if (expr_coherent_p (loop_iv_base_var
, compare_var
))
1292 for (i = s; i < h; i++)
1294 The branch should be predicted taken. */
1295 if (loop_bound_step
> 0
1296 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1297 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1298 else if (loop_bound_step
< 0
1299 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1300 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1302 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1306 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1307 exits are resulted from short-circuit conditions that will generate an
1310 if (foo() || global > 10)
1313 This will be translated into:
1318 if foo() goto BB6 else goto BB5
1320 if global > 10 goto BB6 else goto BB7
1324 iftmp = (PHI 0(BB5), 1(BB6))
1325 if iftmp == 1 goto BB8 else goto BB3
1327 outside of the loop...
1329 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1330 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1331 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1332 exits to predict them using PRED_LOOP_EXIT. */
1335 predict_extra_loop_exits (edge exit_edge
)
1338 bool check_value_one
;
1340 tree cmp_rhs
, cmp_lhs
;
1341 gimple cmp_stmt
= last_stmt (exit_edge
->src
);
1343 if (!cmp_stmt
|| gimple_code (cmp_stmt
) != GIMPLE_COND
)
1345 cmp_rhs
= gimple_cond_rhs (cmp_stmt
);
1346 cmp_lhs
= gimple_cond_lhs (cmp_stmt
);
1347 if (!TREE_CONSTANT (cmp_rhs
)
1348 || !(integer_zerop (cmp_rhs
) || integer_onep (cmp_rhs
)))
1350 if (TREE_CODE (cmp_lhs
) != SSA_NAME
)
1353 /* If check_value_one is true, only the phi_args with value '1' will lead
1354 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1356 check_value_one
= (((integer_onep (cmp_rhs
))
1357 ^ (gimple_cond_code (cmp_stmt
) == EQ_EXPR
))
1358 ^ ((exit_edge
->flags
& EDGE_TRUE_VALUE
) != 0));
1360 phi_stmt
= SSA_NAME_DEF_STMT (cmp_lhs
);
1361 if (!phi_stmt
|| gimple_code (phi_stmt
) != GIMPLE_PHI
)
1364 for (i
= 0; i
< gimple_phi_num_args (phi_stmt
); i
++)
1368 tree val
= gimple_phi_arg_def (phi_stmt
, i
);
1369 edge e
= gimple_phi_arg_edge (phi_stmt
, i
);
1371 if (!TREE_CONSTANT (val
) || !(integer_zerop (val
) || integer_onep (val
)))
1373 if ((check_value_one
^ integer_onep (val
)) == 1)
1375 if (EDGE_COUNT (e
->src
->succs
) != 1)
1377 predict_paths_leading_to_edge (e
, PRED_LOOP_EXIT
, NOT_TAKEN
);
1381 FOR_EACH_EDGE (e1
, ei
, e
->src
->preds
)
1382 predict_paths_leading_to_edge (e1
, PRED_LOOP_EXIT
, NOT_TAKEN
);
1386 /* Predict edge probabilities by exploiting loop structure. */
1389 predict_loops (void)
1394 /* Try to predict out blocks in a loop that are not part of a
1396 FOR_EACH_LOOP (li
, loop
, 0)
1398 basic_block bb
, *bbs
;
1399 unsigned j
, n_exits
;
1401 struct tree_niter_desc niter_desc
;
1403 struct nb_iter_bound
*nb_iter
;
1404 enum tree_code loop_bound_code
= ERROR_MARK
;
1405 int loop_bound_step
= 0;
1406 tree loop_bound_var
= NULL
;
1407 tree loop_iv_base
= NULL
;
1410 exits
= get_loop_exit_edges (loop
);
1411 n_exits
= exits
.length ();
1418 FOR_EACH_VEC_ELT (exits
, j
, ex
)
1421 HOST_WIDE_INT nitercst
;
1422 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
1424 enum br_predictor predictor
;
1426 predict_extra_loop_exits (ex
);
1428 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false, false))
1429 niter
= niter_desc
.niter
;
1430 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
1431 niter
= loop_niter_by_eval (loop
, ex
);
1433 if (TREE_CODE (niter
) == INTEGER_CST
)
1435 if (host_integerp (niter
, 1)
1437 && compare_tree_int (niter
, max
- 1) == -1)
1438 nitercst
= tree_low_cst (niter
, 1) + 1;
1441 predictor
= PRED_LOOP_ITERATIONS
;
1443 /* If we have just one exit and we can derive some information about
1444 the number of iterations of the loop from the statements inside
1445 the loop, use it to predict this exit. */
1446 else if (n_exits
== 1)
1448 nitercst
= estimated_stmt_executions_int (loop
);
1454 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
1459 /* If the prediction for number of iterations is zero, do not
1460 predict the exit edges. */
1464 probability
= ((REG_BR_PROB_BASE
+ nitercst
/ 2) / nitercst
);
1465 predict_edge (ex
, predictor
, probability
);
1469 /* Find information about loop bound variables. */
1470 for (nb_iter
= loop
->bounds
; nb_iter
;
1471 nb_iter
= nb_iter
->next
)
1473 && gimple_code (nb_iter
->stmt
) == GIMPLE_COND
)
1475 stmt
= nb_iter
->stmt
;
1478 if (!stmt
&& last_stmt (loop
->header
)
1479 && gimple_code (last_stmt (loop
->header
)) == GIMPLE_COND
)
1480 stmt
= last_stmt (loop
->header
);
1482 is_comparison_with_loop_invariant_p (stmt
, loop
,
1488 bbs
= get_loop_body (loop
);
1490 for (j
= 0; j
< loop
->num_nodes
; j
++)
1492 int header_found
= 0;
1498 /* Bypass loop heuristics on continue statement. These
1499 statements construct loops via "non-loop" constructs
1500 in the source language and are better to be handled
1502 if (predicted_by_p (bb
, PRED_CONTINUE
))
1505 /* Loop branch heuristics - predict an edge back to a
1506 loop's head as taken. */
1507 if (bb
== loop
->latch
)
1509 e
= find_edge (loop
->latch
, loop
->header
);
1513 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
1517 /* Loop exit heuristics - predict an edge exiting the loop if the
1518 conditional has no loop header successors as not taken. */
1520 /* If we already used more reliable loop exit predictors, do not
1521 bother with PRED_LOOP_EXIT. */
1522 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1523 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS
))
1525 /* For loop with many exits we don't want to predict all exits
1526 with the pretty large probability, because if all exits are
1527 considered in row, the loop would be predicted to iterate
1528 almost never. The code to divide probability by number of
1529 exits is very rough. It should compute the number of exits
1530 taken in each patch through function (not the overall number
1531 of exits that might be a lot higher for loops with wide switch
1532 statements in them) and compute n-th square root.
1534 We limit the minimal probability by 2% to avoid
1535 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1536 as this was causing regression in perl benchmark containing such
1539 int probability
= ((REG_BR_PROB_BASE
1540 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
1542 if (probability
< HITRATE (2))
1543 probability
= HITRATE (2);
1544 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1545 if (e
->dest
->index
< NUM_FIXED_BLOCKS
1546 || !flow_bb_inside_loop_p (loop
, e
->dest
))
1547 predict_edge (e
, PRED_LOOP_EXIT
, probability
);
1550 predict_iv_comparison (loop
, bb
, loop_bound_var
, loop_iv_base
,
1555 /* Free basic blocks from get_loop_body. */
1560 /* Attempt to predict probabilities of BB outgoing edges using local
1563 bb_estimate_probability_locally (basic_block bb
)
1565 rtx last_insn
= BB_END (bb
);
1568 if (! can_predict_insn_p (last_insn
))
1570 cond
= get_condition (last_insn
, NULL
, false, false);
1574 /* Try "pointer heuristic."
1575 A comparison ptr == 0 is predicted as false.
1576 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1577 if (COMPARISON_P (cond
)
1578 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
1579 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
1581 if (GET_CODE (cond
) == EQ
)
1582 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
1583 else if (GET_CODE (cond
) == NE
)
1584 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
1588 /* Try "opcode heuristic."
1589 EQ tests are usually false and NE tests are usually true. Also,
1590 most quantities are positive, so we can make the appropriate guesses
1591 about signed comparisons against zero. */
1592 switch (GET_CODE (cond
))
1595 /* Unconditional branch. */
1596 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
1597 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
1602 /* Floating point comparisons appears to behave in a very
1603 unpredictable way because of special role of = tests in
1605 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1607 /* Comparisons with 0 are often used for booleans and there is
1608 nothing useful to predict about them. */
1609 else if (XEXP (cond
, 1) == const0_rtx
1610 || XEXP (cond
, 0) == const0_rtx
)
1613 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
1618 /* Floating point comparisons appears to behave in a very
1619 unpredictable way because of special role of = tests in
1621 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1623 /* Comparisons with 0 are often used for booleans and there is
1624 nothing useful to predict about them. */
1625 else if (XEXP (cond
, 1) == const0_rtx
1626 || XEXP (cond
, 0) == const0_rtx
)
1629 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
1633 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
1637 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
1642 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1643 || XEXP (cond
, 1) == constm1_rtx
)
1644 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
1649 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1650 || XEXP (cond
, 1) == constm1_rtx
)
1651 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
1659 /* Set edge->probability for each successor edge of BB. */
1661 guess_outgoing_edge_probabilities (basic_block bb
)
1663 bb_estimate_probability_locally (bb
);
1664 combine_predictions_for_insn (BB_END (bb
), bb
);
1667 static tree
expr_expected_value (tree
, bitmap
);
1669 /* Helper function for expr_expected_value. */
1672 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
,
1673 tree op1
, bitmap visited
)
1677 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1679 if (TREE_CONSTANT (op0
))
1682 if (code
!= SSA_NAME
)
1685 def
= SSA_NAME_DEF_STMT (op0
);
1687 /* If we were already here, break the infinite cycle. */
1688 if (!bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
)))
1691 if (gimple_code (def
) == GIMPLE_PHI
)
1693 /* All the arguments of the PHI node must have the same constant
1695 int i
, n
= gimple_phi_num_args (def
);
1696 tree val
= NULL
, new_val
;
1698 for (i
= 0; i
< n
; i
++)
1700 tree arg
= PHI_ARG_DEF (def
, i
);
1702 /* If this PHI has itself as an argument, we cannot
1703 determine the string length of this argument. However,
1704 if we can find an expected constant value for the other
1705 PHI args then we can still be sure that this is
1706 likely a constant. So be optimistic and just
1707 continue with the next argument. */
1708 if (arg
== PHI_RESULT (def
))
1711 new_val
= expr_expected_value (arg
, visited
);
1716 else if (!operand_equal_p (val
, new_val
, false))
1721 if (is_gimple_assign (def
))
1723 if (gimple_assign_lhs (def
) != op0
)
1726 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
1727 gimple_assign_rhs1 (def
),
1728 gimple_assign_rhs_code (def
),
1729 gimple_assign_rhs2 (def
),
1733 if (is_gimple_call (def
))
1735 tree decl
= gimple_call_fndecl (def
);
1738 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
)
1739 switch (DECL_FUNCTION_CODE (decl
))
1741 case BUILT_IN_EXPECT
:
1744 if (gimple_call_num_args (def
) != 2)
1746 val
= gimple_call_arg (def
, 0);
1747 if (TREE_CONSTANT (val
))
1749 return gimple_call_arg (def
, 1);
1752 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
:
1753 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1
:
1754 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2
:
1755 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4
:
1756 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8
:
1757 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16
:
1758 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE
:
1759 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N
:
1760 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1
:
1761 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2
:
1762 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4
:
1763 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8
:
1764 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16
:
1765 /* Assume that any given atomic operation has low contention,
1766 and thus the compare-and-swap operation succeeds. */
1767 return boolean_true_node
;
1774 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
1777 op0
= expr_expected_value (op0
, visited
);
1780 op1
= expr_expected_value (op1
, visited
);
1783 res
= fold_build2 (code
, type
, op0
, op1
);
1784 if (TREE_CONSTANT (res
))
1788 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
1791 op0
= expr_expected_value (op0
, visited
);
1794 res
= fold_build1 (code
, type
, op0
);
1795 if (TREE_CONSTANT (res
))
1802 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1803 The function is used by builtin_expect branch predictor so the evidence
1804 must come from this construct and additional possible constant folding.
1806 We may want to implement more involved value guess (such as value range
1807 propagation based prediction), but such tricks shall go to new
1811 expr_expected_value (tree expr
, bitmap visited
)
1813 enum tree_code code
;
1816 if (TREE_CONSTANT (expr
))
1819 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1820 return expr_expected_value_1 (TREE_TYPE (expr
),
1821 op0
, code
, op1
, visited
);
1825 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1826 we no longer need. */
1828 strip_predict_hints (void)
1836 gimple_stmt_iterator bi
;
1837 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
);)
1839 gimple stmt
= gsi_stmt (bi
);
1841 if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1843 gsi_remove (&bi
, true);
1846 else if (gimple_code (stmt
) == GIMPLE_CALL
)
1848 tree fndecl
= gimple_call_fndecl (stmt
);
1851 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1852 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
1853 && gimple_call_num_args (stmt
) == 2)
1855 var
= gimple_call_lhs (stmt
);
1859 = gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
1860 gsi_replace (&bi
, ass_stmt
, true);
1864 gsi_remove (&bi
, true);
1875 /* Predict using opcode of the last statement in basic block. */
1877 tree_predict_by_opcode (basic_block bb
)
1879 gimple stmt
= last_stmt (bb
);
1888 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1890 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1891 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1893 op0
= gimple_cond_lhs (stmt
);
1894 op1
= gimple_cond_rhs (stmt
);
1895 cmp
= gimple_cond_code (stmt
);
1896 type
= TREE_TYPE (op0
);
1897 visited
= BITMAP_ALLOC (NULL
);
1898 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, visited
);
1899 BITMAP_FREE (visited
);
1902 if (integer_zerop (val
))
1903 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, NOT_TAKEN
);
1905 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, TAKEN
);
1908 /* Try "pointer heuristic."
1909 A comparison ptr == 0 is predicted as false.
1910 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1911 if (POINTER_TYPE_P (type
))
1914 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
1915 else if (cmp
== NE_EXPR
)
1916 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
1920 /* Try "opcode heuristic."
1921 EQ tests are usually false and NE tests are usually true. Also,
1922 most quantities are positive, so we can make the appropriate guesses
1923 about signed comparisons against zero. */
1928 /* Floating point comparisons appears to behave in a very
1929 unpredictable way because of special role of = tests in
1931 if (FLOAT_TYPE_P (type
))
1933 /* Comparisons with 0 are often used for booleans and there is
1934 nothing useful to predict about them. */
1935 else if (integer_zerop (op0
) || integer_zerop (op1
))
1938 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
1943 /* Floating point comparisons appears to behave in a very
1944 unpredictable way because of special role of = tests in
1946 if (FLOAT_TYPE_P (type
))
1948 /* Comparisons with 0 are often used for booleans and there is
1949 nothing useful to predict about them. */
1950 else if (integer_zerop (op0
)
1951 || integer_zerop (op1
))
1954 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
1958 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
1961 case UNORDERED_EXPR
:
1962 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
1967 if (integer_zerop (op1
)
1968 || integer_onep (op1
)
1969 || integer_all_onesp (op1
)
1972 || real_minus_onep (op1
))
1973 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
1978 if (integer_zerop (op1
)
1979 || integer_onep (op1
)
1980 || integer_all_onesp (op1
)
1983 || real_minus_onep (op1
))
1984 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
1992 /* Try to guess whether the value of return means error code. */
1994 static enum br_predictor
1995 return_prediction (tree val
, enum prediction
*prediction
)
1999 return PRED_NO_PREDICTION
;
2000 /* Different heuristics for pointers and scalars. */
2001 if (POINTER_TYPE_P (TREE_TYPE (val
)))
2003 /* NULL is usually not returned. */
2004 if (integer_zerop (val
))
2006 *prediction
= NOT_TAKEN
;
2007 return PRED_NULL_RETURN
;
2010 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
2012 /* Negative return values are often used to indicate
2014 if (TREE_CODE (val
) == INTEGER_CST
2015 && tree_int_cst_sgn (val
) < 0)
2017 *prediction
= NOT_TAKEN
;
2018 return PRED_NEGATIVE_RETURN
;
2020 /* Constant return values seems to be commonly taken.
2021 Zero/one often represent booleans so exclude them from the
2023 if (TREE_CONSTANT (val
)
2024 && (!integer_zerop (val
) && !integer_onep (val
)))
2026 *prediction
= TAKEN
;
2027 return PRED_CONST_RETURN
;
2030 return PRED_NO_PREDICTION
;
2033 /* Find the basic block with return expression and look up for possible
2034 return value trying to apply RETURN_PREDICTION heuristics. */
2036 apply_return_prediction (void)
2038 gimple return_stmt
= NULL
;
2042 int phi_num_args
, i
;
2043 enum br_predictor pred
;
2044 enum prediction direction
;
2047 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
2049 return_stmt
= last_stmt (e
->src
);
2051 && gimple_code (return_stmt
) == GIMPLE_RETURN
)
2056 return_val
= gimple_return_retval (return_stmt
);
2059 if (TREE_CODE (return_val
) != SSA_NAME
2060 || !SSA_NAME_DEF_STMT (return_val
)
2061 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
2063 phi
= SSA_NAME_DEF_STMT (return_val
);
2064 phi_num_args
= gimple_phi_num_args (phi
);
2065 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
2067 /* Avoid the degenerate case where all return values form the function
2068 belongs to same category (ie they are all positive constants)
2069 so we can hardly say something about them. */
2070 for (i
= 1; i
< phi_num_args
; i
++)
2071 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
2073 if (i
!= phi_num_args
)
2074 for (i
= 0; i
< phi_num_args
; i
++)
2076 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
2077 if (pred
!= PRED_NO_PREDICTION
)
2078 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi
, i
), pred
,
2083 /* Look for basic block that contains unlikely to happen events
2084 (such as noreturn calls) and mark all paths leading to execution
2085 of this basic blocks as unlikely. */
2088 tree_bb_level_predictions (void)
2091 bool has_return_edges
= false;
2095 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
2096 if (!(e
->flags
& (EDGE_ABNORMAL
| EDGE_FAKE
| EDGE_EH
)))
2098 has_return_edges
= true;
2102 apply_return_prediction ();
2106 gimple_stmt_iterator gsi
;
2108 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
2110 gimple stmt
= gsi_stmt (gsi
);
2113 if (is_gimple_call (stmt
))
2115 if ((gimple_call_flags (stmt
) & ECF_NORETURN
)
2116 && has_return_edges
)
2117 predict_paths_leading_to (bb
, PRED_NORETURN
,
2119 decl
= gimple_call_fndecl (stmt
);
2121 && lookup_attribute ("cold",
2122 DECL_ATTRIBUTES (decl
)))
2123 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
2126 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
2128 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
2129 gimple_predict_outcome (stmt
));
2130 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2131 hints to callers. */
2137 #ifdef ENABLE_CHECKING
2139 /* Callback for pointer_map_traverse, asserts that the pointer map is
2143 assert_is_empty (const void *key ATTRIBUTE_UNUSED
, void **value
,
2144 void *data ATTRIBUTE_UNUSED
)
2146 gcc_assert (!*value
);
2151 /* Predict branch probabilities and estimate profile for basic block BB. */
2154 tree_estimate_probability_bb (basic_block bb
)
2160 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2162 /* Predict edges to user labels with attributes. */
2163 if (e
->dest
!= EXIT_BLOCK_PTR
)
2165 gimple_stmt_iterator gi
;
2166 for (gi
= gsi_start_bb (e
->dest
); !gsi_end_p (gi
); gsi_next (&gi
))
2168 gimple stmt
= gsi_stmt (gi
);
2171 if (gimple_code (stmt
) != GIMPLE_LABEL
)
2173 decl
= gimple_label_label (stmt
);
2174 if (DECL_ARTIFICIAL (decl
))
2177 /* Finally, we have a user-defined label. */
2178 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl
)))
2179 predict_edge_def (e
, PRED_COLD_LABEL
, NOT_TAKEN
);
2180 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl
)))
2181 predict_edge_def (e
, PRED_HOT_LABEL
, TAKEN
);
2185 /* Predict early returns to be probable, as we've already taken
2186 care for error returns and other cases are often used for
2187 fast paths through function.
2189 Since we've already removed the return statements, we are
2190 looking for CFG like:
2200 if (e
->dest
!= bb
->next_bb
2201 && e
->dest
!= EXIT_BLOCK_PTR
2202 && single_succ_p (e
->dest
)
2203 && single_succ_edge (e
->dest
)->dest
== EXIT_BLOCK_PTR
2204 && (last
= last_stmt (e
->dest
)) != NULL
2205 && gimple_code (last
) == GIMPLE_RETURN
)
2210 if (single_succ_p (bb
))
2212 FOR_EACH_EDGE (e1
, ei1
, bb
->preds
)
2213 if (!predicted_by_p (e1
->src
, PRED_NULL_RETURN
)
2214 && !predicted_by_p (e1
->src
, PRED_CONST_RETURN
)
2215 && !predicted_by_p (e1
->src
, PRED_NEGATIVE_RETURN
))
2216 predict_edge_def (e1
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2219 if (!predicted_by_p (e
->src
, PRED_NULL_RETURN
)
2220 && !predicted_by_p (e
->src
, PRED_CONST_RETURN
)
2221 && !predicted_by_p (e
->src
, PRED_NEGATIVE_RETURN
))
2222 predict_edge_def (e
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2225 /* Look for block we are guarding (ie we dominate it,
2226 but it doesn't postdominate us). */
2227 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
2228 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
2229 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
2231 gimple_stmt_iterator bi
;
2233 /* The call heuristic claims that a guarded function call
2234 is improbable. This is because such calls are often used
2235 to signal exceptional situations such as printing error
2237 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
2240 gimple stmt
= gsi_stmt (bi
);
2241 if (is_gimple_call (stmt
)
2242 /* Constant and pure calls are hardly used to signalize
2243 something exceptional. */
2244 && gimple_has_side_effects (stmt
))
2246 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
2252 tree_predict_by_opcode (bb
);
2255 /* Predict branch probabilities and estimate profile of the tree CFG.
2256 This function can be called from the loop optimizers to recompute
2257 the profile information. */
2260 tree_estimate_probability (void)
2264 add_noreturn_fake_exit_edges ();
2265 connect_infinite_loops_to_exit ();
2266 /* We use loop_niter_by_eval, which requires that the loops have
2268 create_preheaders (CP_SIMPLE_PREHEADERS
);
2269 calculate_dominance_info (CDI_POST_DOMINATORS
);
2271 bb_predictions
= pointer_map_create ();
2272 tree_bb_level_predictions ();
2273 record_loop_exits ();
2275 if (number_of_loops () > 1)
2279 tree_estimate_probability_bb (bb
);
2282 combine_predictions_for_bb (bb
);
2284 #ifdef ENABLE_CHECKING
2285 pointer_map_traverse (bb_predictions
, assert_is_empty
, NULL
);
2287 pointer_map_destroy (bb_predictions
);
2288 bb_predictions
= NULL
;
2290 estimate_bb_frequencies ();
2291 free_dominance_info (CDI_POST_DOMINATORS
);
2292 remove_fake_exit_edges ();
2295 /* Predict branch probabilities and estimate profile of the tree CFG.
2296 This is the driver function for PASS_PROFILE. */
2299 tree_estimate_probability_driver (void)
2303 loop_optimizer_init (LOOPS_NORMAL
);
2304 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2305 flow_loops_dump (dump_file
, NULL
, 0);
2307 mark_irreducible_loops ();
2309 nb_loops
= number_of_loops ();
2313 tree_estimate_probability ();
2318 loop_optimizer_finalize ();
2319 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2320 gimple_dump_cfg (dump_file
, dump_flags
);
2321 if (profile_status
== PROFILE_ABSENT
)
2322 profile_status
= PROFILE_GUESSED
;
2326 /* Predict edges to successors of CUR whose sources are not postdominated by
2327 BB by PRED and recurse to all postdominators. */
2330 predict_paths_for_bb (basic_block cur
, basic_block bb
,
2331 enum br_predictor pred
,
2332 enum prediction taken
,
2339 /* We are looking for all edges forming edge cut induced by
2340 set of all blocks postdominated by BB. */
2341 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
2342 if (e
->src
->index
>= NUM_FIXED_BLOCKS
2343 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
2349 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2350 if (e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2352 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
2354 /* See if there is an edge from e->src that is not abnormal
2355 and does not lead to BB. */
2356 FOR_EACH_EDGE (e2
, ei2
, e
->src
->succs
)
2358 && !(e2
->flags
& (EDGE_EH
| EDGE_FAKE
))
2359 && !dominated_by_p (CDI_POST_DOMINATORS
, e2
->dest
, bb
))
2365 /* If there is non-abnormal path leaving e->src, predict edge
2366 using predictor. Otherwise we need to look for paths
2369 The second may lead to infinite loop in the case we are predicitng
2370 regions that are only reachable by abnormal edges. We simply
2371 prevent visiting given BB twice. */
2373 predict_edge_def (e
, pred
, taken
);
2374 else if (bitmap_set_bit (visited
, e
->src
->index
))
2375 predict_paths_for_bb (e
->src
, e
->src
, pred
, taken
, visited
);
2377 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
2379 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
2380 predict_paths_for_bb (son
, bb
, pred
, taken
, visited
);
2383 /* Sets branch probabilities according to PREDiction and
2387 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
2388 enum prediction taken
)
2390 bitmap visited
= BITMAP_ALLOC (NULL
);
2391 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2392 BITMAP_FREE (visited
);
2395 /* Like predict_paths_leading_to but take edge instead of basic block. */
2398 predict_paths_leading_to_edge (edge e
, enum br_predictor pred
,
2399 enum prediction taken
)
2401 bool has_nonloop_edge
= false;
2405 basic_block bb
= e
->src
;
2406 FOR_EACH_EDGE (e2
, ei
, bb
->succs
)
2407 if (e2
->dest
!= e
->src
&& e2
->dest
!= e
->dest
2408 && !(e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2409 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e2
->dest
))
2411 has_nonloop_edge
= true;
2414 if (!has_nonloop_edge
)
2416 bitmap visited
= BITMAP_ALLOC (NULL
);
2417 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2418 BITMAP_FREE (visited
);
2421 predict_edge_def (e
, pred
, taken
);
2424 /* This is used to carry information about basic blocks. It is
2425 attached to the AUX field of the standard CFG block. */
2427 typedef struct block_info_def
2429 /* Estimated frequency of execution of basic_block. */
2432 /* To keep queue of basic blocks to process. */
2435 /* Number of predecessors we need to visit first. */
2439 /* Similar information for edges. */
2440 typedef struct edge_info_def
2442 /* In case edge is a loopback edge, the probability edge will be reached
2443 in case header is. Estimated number of iterations of the loop can be
2444 then computed as 1 / (1 - back_edge_prob). */
2445 sreal back_edge_prob
;
2446 /* True if the edge is a loopback edge in the natural loop. */
2447 unsigned int back_edge
:1;
2450 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2451 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2453 /* Helper function for estimate_bb_frequencies.
2454 Propagate the frequencies in blocks marked in
2455 TOVISIT, starting in HEAD. */
2458 propagate_freq (basic_block head
, bitmap tovisit
)
2467 /* For each basic block we need to visit count number of his predecessors
2468 we need to visit first. */
2469 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
2474 bb
= BASIC_BLOCK (i
);
2476 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2478 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
2480 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
2482 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
2484 "Irreducible region hit, ignoring edge to %i->%i\n",
2485 e
->src
->index
, bb
->index
);
2487 BLOCK_INFO (bb
)->npredecessors
= count
;
2488 /* When function never returns, we will never process exit block. */
2489 if (!count
&& bb
== EXIT_BLOCK_PTR
)
2490 bb
->count
= bb
->frequency
= 0;
2493 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
2495 for (bb
= head
; bb
; bb
= nextbb
)
2498 sreal cyclic_probability
, frequency
;
2500 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
2501 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
2503 nextbb
= BLOCK_INFO (bb
)->next
;
2504 BLOCK_INFO (bb
)->next
= NULL
;
2506 /* Compute frequency of basic block. */
2509 #ifdef ENABLE_CHECKING
2510 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2511 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
2512 || (e
->flags
& EDGE_DFS_BACK
));
2515 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2516 if (EDGE_INFO (e
)->back_edge
)
2518 sreal_add (&cyclic_probability
, &cyclic_probability
,
2519 &EDGE_INFO (e
)->back_edge_prob
);
2521 else if (!(e
->flags
& EDGE_DFS_BACK
))
2525 /* frequency += (e->probability
2526 * BLOCK_INFO (e->src)->frequency /
2527 REG_BR_PROB_BASE); */
2529 sreal_init (&tmp
, e
->probability
, 0);
2530 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
2531 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
2532 sreal_add (&frequency
, &frequency
, &tmp
);
2535 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
2537 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
2538 sizeof (frequency
));
2542 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
2544 memcpy (&cyclic_probability
, &real_almost_one
,
2545 sizeof (real_almost_one
));
2548 /* BLOCK_INFO (bb)->frequency = frequency
2549 / (1 - cyclic_probability) */
2551 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
2552 sreal_div (&BLOCK_INFO (bb
)->frequency
,
2553 &frequency
, &cyclic_probability
);
2557 bitmap_clear_bit (tovisit
, bb
->index
);
2559 e
= find_edge (bb
, head
);
2564 /* EDGE_INFO (e)->back_edge_prob
2565 = ((e->probability * BLOCK_INFO (bb)->frequency)
2566 / REG_BR_PROB_BASE); */
2568 sreal_init (&tmp
, e
->probability
, 0);
2569 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
2570 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2571 &tmp
, &real_inv_br_prob_base
);
2574 /* Propagate to successor blocks. */
2575 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2576 if (!(e
->flags
& EDGE_DFS_BACK
)
2577 && BLOCK_INFO (e
->dest
)->npredecessors
)
2579 BLOCK_INFO (e
->dest
)->npredecessors
--;
2580 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
2585 BLOCK_INFO (last
)->next
= e
->dest
;
2593 /* Estimate probabilities of loopback edges in loops at same nest level. */
2596 estimate_loops_at_level (struct loop
*first_loop
)
2600 for (loop
= first_loop
; loop
; loop
= loop
->next
)
2605 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2607 estimate_loops_at_level (loop
->inner
);
2609 /* Find current loop back edge and mark it. */
2610 e
= loop_latch_edge (loop
);
2611 EDGE_INFO (e
)->back_edge
= 1;
2613 bbs
= get_loop_body (loop
);
2614 for (i
= 0; i
< loop
->num_nodes
; i
++)
2615 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
2617 propagate_freq (loop
->header
, tovisit
);
2618 BITMAP_FREE (tovisit
);
2622 /* Propagates frequencies through structure of loops. */
2625 estimate_loops (void)
2627 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2630 /* Start by estimating the frequencies in the loops. */
2631 if (number_of_loops () > 1)
2632 estimate_loops_at_level (current_loops
->tree_root
->inner
);
2634 /* Now propagate the frequencies through all the blocks. */
2637 bitmap_set_bit (tovisit
, bb
->index
);
2639 propagate_freq (ENTRY_BLOCK_PTR
, tovisit
);
2640 BITMAP_FREE (tovisit
);
2643 /* Convert counts measured by profile driven feedback to frequencies.
2644 Return nonzero iff there was any nonzero execution count. */
2647 counts_to_freqs (void)
2649 gcov_type count_max
, true_count_max
= 0;
2652 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2653 true_count_max
= MAX (bb
->count
, true_count_max
);
2655 count_max
= MAX (true_count_max
, 1);
2656 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2657 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
2659 return true_count_max
;
2662 /* Return true if function is likely to be expensive, so there is no point to
2663 optimize performance of prologue, epilogue or do inlining at the expense
2664 of code size growth. THRESHOLD is the limit of number of instructions
2665 function can execute at average to be still considered not expensive. */
2668 expensive_function_p (int threshold
)
2670 unsigned int sum
= 0;
2674 /* We can not compute accurately for large thresholds due to scaled
2676 gcc_assert (threshold
<= BB_FREQ_MAX
);
2678 /* Frequencies are out of range. This either means that function contains
2679 internal loop executing more than BB_FREQ_MAX times or profile feedback
2680 is available and function has not been executed at all. */
2681 if (ENTRY_BLOCK_PTR
->frequency
== 0)
2684 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2685 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
2690 for (insn
= BB_HEAD (bb
); insn
!= NEXT_INSN (BB_END (bb
));
2691 insn
= NEXT_INSN (insn
))
2692 if (active_insn_p (insn
))
2694 sum
+= bb
->frequency
;
2703 /* Estimate basic blocks frequency by given branch probabilities. */
2706 estimate_bb_frequencies (void)
2711 if (profile_status
!= PROFILE_READ
|| !counts_to_freqs ())
2713 static int real_values_initialized
= 0;
2715 if (!real_values_initialized
)
2717 real_values_initialized
= 1;
2718 sreal_init (&real_zero
, 0, 0);
2719 sreal_init (&real_one
, 1, 0);
2720 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
2721 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
2722 sreal_init (&real_one_half
, 1, -1);
2723 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
2724 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
2727 mark_dfs_back_edges ();
2729 single_succ_edge (ENTRY_BLOCK_PTR
)->probability
= REG_BR_PROB_BASE
;
2731 /* Set up block info for each basic block. */
2732 alloc_aux_for_blocks (sizeof (struct block_info_def
));
2733 alloc_aux_for_edges (sizeof (struct edge_info_def
));
2734 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2739 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2741 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
2742 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2743 &EDGE_INFO (e
)->back_edge_prob
,
2744 &real_inv_br_prob_base
);
2748 /* First compute probabilities locally for each loop from innermost
2749 to outermost to examine probabilities for back edges. */
2752 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
2754 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
2755 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
2757 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
2758 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2762 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
2763 sreal_add (&tmp
, &tmp
, &real_one_half
);
2764 bb
->frequency
= sreal_to_int (&tmp
);
2767 free_aux_for_blocks ();
2768 free_aux_for_edges ();
2770 compute_function_frequency ();
2773 /* Decide whether function is hot, cold or unlikely executed. */
2775 compute_function_frequency (void)
2778 struct cgraph_node
*node
= cgraph_get_node (current_function_decl
);
2779 if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2780 || MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2781 node
->only_called_at_startup
= true;
2782 if (DECL_STATIC_DESTRUCTOR (current_function_decl
))
2783 node
->only_called_at_exit
= true;
2785 if (!profile_info
|| !flag_branch_probabilities
)
2787 int flags
= flags_from_decl_or_type (current_function_decl
);
2788 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
2790 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2791 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
2793 node
->frequency
= NODE_FREQUENCY_HOT
;
2794 else if (flags
& ECF_NORETURN
)
2795 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2796 else if (MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2797 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2798 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2799 || DECL_STATIC_DESTRUCTOR (current_function_decl
))
2800 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2803 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2806 if (maybe_hot_bb_p (cfun
, bb
))
2808 node
->frequency
= NODE_FREQUENCY_HOT
;
2811 if (!probably_never_executed_bb_p (cfun
, bb
))
2812 node
->frequency
= NODE_FREQUENCY_NORMAL
;
2817 gate_estimate_probability (void)
2819 return flag_guess_branch_prob
;
2822 /* Build PREDICT_EXPR. */
2824 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
2826 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
2827 build_int_cst (integer_type_node
, predictor
));
2828 SET_PREDICT_EXPR_OUTCOME (t
, taken
);
2833 predictor_name (enum br_predictor predictor
)
2835 return predictor_info
[predictor
].name
;
2838 struct gimple_opt_pass pass_profile
=
2842 "profile_estimate", /* name */
2843 OPTGROUP_NONE
, /* optinfo_flags */
2844 gate_estimate_probability
, /* gate */
2845 tree_estimate_probability_driver
, /* execute */
2848 0, /* static_pass_number */
2849 TV_BRANCH_PROB
, /* tv_id */
2850 PROP_cfg
, /* properties_required */
2851 0, /* properties_provided */
2852 0, /* properties_destroyed */
2853 0, /* todo_flags_start */
2854 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2858 struct gimple_opt_pass pass_strip_predict_hints
=
2862 "*strip_predict_hints", /* name */
2863 OPTGROUP_NONE
, /* optinfo_flags */
2865 strip_predict_hints
, /* execute */
2868 0, /* static_pass_number */
2869 TV_BRANCH_PROB
, /* tv_id */
2870 PROP_cfg
, /* properties_required */
2871 0, /* properties_provided */
2872 0, /* properties_destroyed */
2873 0, /* todo_flags_start */
2874 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2878 /* Rebuild function frequencies. Passes are in general expected to
2879 maintain profile by hand, however in some cases this is not possible:
2880 for example when inlining several functions with loops freuqencies might run
2881 out of scale and thus needs to be recomputed. */
2884 rebuild_frequencies (void)
2886 timevar_push (TV_REBUILD_FREQUENCIES
);
2887 if (profile_status
== PROFILE_GUESSED
)
2889 loop_optimizer_init (0);
2890 add_noreturn_fake_exit_edges ();
2891 mark_irreducible_loops ();
2892 connect_infinite_loops_to_exit ();
2893 estimate_bb_frequencies ();
2894 remove_fake_exit_edges ();
2895 loop_optimizer_finalize ();
2897 else if (profile_status
== PROFILE_READ
)
2901 timevar_pop (TV_REBUILD_FREQUENCIES
);