1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
23 [1] "Branch Prediction for Free"
24 Ball and Larus; PLDI '93.
25 [2] "Static Branch Frequency and Program Profile Analysis"
26 Wu and Larus; MICRO-27.
27 [3] "Corpus-based Static Branch Prediction"
28 Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
33 #include "coretypes.h"
38 #include "hard-reg-set.h"
39 #include "basic-block.h"
40 #include "insn-config.h"
45 #include "diagnostic-core.h"
54 #include "tree-flow.h"
56 #include "tree-pass.h"
57 #include "tree-scalar-evolution.h"
59 #include "pointer-set.h"
61 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
62 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
63 static sreal real_zero
, real_one
, real_almost_one
, real_br_prob_base
,
64 real_inv_br_prob_base
, real_one_half
, real_bb_freq_max
;
66 /* Random guesstimation given names.
67 PROV_VERY_UNLIKELY should be small enough so basic block predicted
68 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
69 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
70 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
71 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
72 #define PROB_ALWAYS (REG_BR_PROB_BASE)
74 static void combine_predictions_for_insn (rtx
, basic_block
);
75 static void dump_prediction (FILE *, enum br_predictor
, int, basic_block
, int);
76 static void predict_paths_leading_to (basic_block
, enum br_predictor
, enum prediction
);
77 static void predict_paths_leading_to_edge (edge
, enum br_predictor
, enum prediction
);
78 static bool can_predict_insn_p (const_rtx
);
80 /* Information we hold about each branch predictor.
81 Filled using information from predict.def. */
85 const char *const name
; /* Name used in the debugging dumps. */
86 const int hitrate
; /* Expected hitrate used by
87 predict_insn_def call. */
91 /* Use given predictor without Dempster-Shaffer theory if it matches
92 using first_match heuristics. */
93 #define PRED_FLAG_FIRST_MATCH 1
95 /* Recompute hitrate in percent to our representation. */
97 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
99 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
100 static const struct predictor_info predictor_info
[]= {
101 #include "predict.def"
103 /* Upper bound on predictors. */
108 /* Return TRUE if frequency FREQ is considered to be hot. */
111 maybe_hot_frequency_p (int freq
)
113 struct cgraph_node
*node
= cgraph_get_node (current_function_decl
);
114 if (!profile_info
|| !flag_branch_probabilities
)
116 if (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
)
118 if (node
->frequency
== NODE_FREQUENCY_HOT
)
121 if (profile_status
== PROFILE_ABSENT
)
123 if (node
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
124 && freq
< (ENTRY_BLOCK_PTR
->frequency
* 2 / 3))
126 if (freq
< ENTRY_BLOCK_PTR
->frequency
/ PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
))
131 /* Return TRUE if frequency FREQ is considered to be hot. */
134 maybe_hot_count_p (gcov_type count
)
136 if (profile_status
!= PROFILE_READ
)
138 /* Code executed at most once is not hot. */
139 if (profile_info
->runs
>= count
)
142 > profile_info
->sum_max
/ PARAM_VALUE (HOT_BB_COUNT_FRACTION
));
145 /* Return true in case BB can be CPU intensive and should be optimized
146 for maximal performance. */
149 maybe_hot_bb_p (const_basic_block bb
)
151 /* Make sure CFUN exists, for dump_bb_info. */
153 if (profile_status
== PROFILE_READ
)
154 return maybe_hot_count_p (bb
->count
);
155 return maybe_hot_frequency_p (bb
->frequency
);
158 /* Return true if the call can be hot. */
161 cgraph_maybe_hot_edge_p (struct cgraph_edge
*edge
)
163 if (profile_info
&& flag_branch_probabilities
165 <= profile_info
->sum_max
/ PARAM_VALUE (HOT_BB_COUNT_FRACTION
)))
167 if (edge
->caller
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
169 && edge
->callee
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
171 if (edge
->caller
->frequency
> NODE_FREQUENCY_UNLIKELY_EXECUTED
173 && edge
->callee
->frequency
<= NODE_FREQUENCY_EXECUTED_ONCE
))
177 if (edge
->caller
->frequency
== NODE_FREQUENCY_HOT
)
179 if (edge
->caller
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
180 && edge
->frequency
< CGRAPH_FREQ_BASE
* 3 / 2)
182 if (flag_guess_branch_prob
183 && edge
->frequency
<= (CGRAPH_FREQ_BASE
184 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)))
189 /* Return true in case BB can be CPU intensive and should be optimized
190 for maximal performance. */
193 maybe_hot_edge_p (edge e
)
195 if (profile_status
== PROFILE_READ
)
196 return maybe_hot_count_p (e
->count
);
197 return maybe_hot_frequency_p (EDGE_FREQUENCY (e
));
201 /* Return true in case BB is probably never executed. */
204 probably_never_executed_bb_p (const_basic_block bb
)
206 /* Make sure CFUN exists, for dump_bb_info. */
208 if (profile_info
&& flag_branch_probabilities
)
209 return ((bb
->count
+ profile_info
->runs
/ 2) / profile_info
->runs
) == 0;
210 if ((!profile_info
|| !flag_branch_probabilities
)
211 && (cgraph_get_node (current_function_decl
)->frequency
212 == NODE_FREQUENCY_UNLIKELY_EXECUTED
))
217 /* Return true if NODE should be optimized for size. */
220 cgraph_optimize_for_size_p (struct cgraph_node
*node
)
224 if (node
&& (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
))
230 /* Return true when current function should always be optimized for size. */
233 optimize_function_for_size_p (struct function
*fun
)
237 if (!fun
|| !fun
->decl
)
239 return cgraph_optimize_for_size_p (cgraph_get_node (fun
->decl
));
242 /* Return true when current function should always be optimized for speed. */
245 optimize_function_for_speed_p (struct function
*fun
)
247 return !optimize_function_for_size_p (fun
);
250 /* Return TRUE when BB should be optimized for size. */
253 optimize_bb_for_size_p (const_basic_block bb
)
255 return optimize_function_for_size_p (cfun
) || !maybe_hot_bb_p (bb
);
258 /* Return TRUE when BB should be optimized for speed. */
261 optimize_bb_for_speed_p (const_basic_block bb
)
263 return !optimize_bb_for_size_p (bb
);
266 /* Return TRUE when BB should be optimized for size. */
269 optimize_edge_for_size_p (edge e
)
271 return optimize_function_for_size_p (cfun
) || !maybe_hot_edge_p (e
);
274 /* Return TRUE when BB should be optimized for speed. */
277 optimize_edge_for_speed_p (edge e
)
279 return !optimize_edge_for_size_p (e
);
282 /* Return TRUE when BB should be optimized for size. */
285 optimize_insn_for_size_p (void)
287 return optimize_function_for_size_p (cfun
) || !crtl
->maybe_hot_insn_p
;
290 /* Return TRUE when BB should be optimized for speed. */
293 optimize_insn_for_speed_p (void)
295 return !optimize_insn_for_size_p ();
298 /* Return TRUE when LOOP should be optimized for size. */
301 optimize_loop_for_size_p (struct loop
*loop
)
303 return optimize_bb_for_size_p (loop
->header
);
306 /* Return TRUE when LOOP should be optimized for speed. */
309 optimize_loop_for_speed_p (struct loop
*loop
)
311 return optimize_bb_for_speed_p (loop
->header
);
314 /* Return TRUE when LOOP nest should be optimized for speed. */
317 optimize_loop_nest_for_speed_p (struct loop
*loop
)
319 struct loop
*l
= loop
;
320 if (optimize_loop_for_speed_p (loop
))
323 while (l
&& l
!= loop
)
325 if (optimize_loop_for_speed_p (l
))
333 while (l
!= loop
&& !l
->next
)
342 /* Return TRUE when LOOP nest should be optimized for size. */
345 optimize_loop_nest_for_size_p (struct loop
*loop
)
347 return !optimize_loop_nest_for_speed_p (loop
);
350 /* Return true when edge E is likely to be well predictable by branch
354 predictable_edge_p (edge e
)
356 if (profile_status
== PROFILE_ABSENT
)
359 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100)
360 || (REG_BR_PROB_BASE
- e
->probability
361 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100))
367 /* Set RTL expansion for BB profile. */
370 rtl_profile_for_bb (basic_block bb
)
372 crtl
->maybe_hot_insn_p
= maybe_hot_bb_p (bb
);
375 /* Set RTL expansion for edge profile. */
378 rtl_profile_for_edge (edge e
)
380 crtl
->maybe_hot_insn_p
= maybe_hot_edge_p (e
);
383 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
385 default_rtl_profile (void)
387 crtl
->maybe_hot_insn_p
= true;
390 /* Return true if the one of outgoing edges is already predicted by
394 rtl_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
397 if (!INSN_P (BB_END (bb
)))
399 for (note
= REG_NOTES (BB_END (bb
)); note
; note
= XEXP (note
, 1))
400 if (REG_NOTE_KIND (note
) == REG_BR_PRED
401 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
406 /* This map contains for a basic block the list of predictions for the
409 static struct pointer_map_t
*bb_predictions
;
411 /* Structure representing predictions in tree level. */
413 struct edge_prediction
{
414 struct edge_prediction
*ep_next
;
416 enum br_predictor ep_predictor
;
420 /* Return true if the one of outgoing edges is already predicted by
424 gimple_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
426 struct edge_prediction
*i
;
427 void **preds
= pointer_map_contains (bb_predictions
, bb
);
432 for (i
= (struct edge_prediction
*) *preds
; i
; i
= i
->ep_next
)
433 if (i
->ep_predictor
== predictor
)
438 /* Return true when the probability of edge is reliable.
440 The profile guessing code is good at predicting branch outcome (ie.
441 taken/not taken), that is predicted right slightly over 75% of time.
442 It is however notoriously poor on predicting the probability itself.
443 In general the profile appear a lot flatter (with probabilities closer
444 to 50%) than the reality so it is bad idea to use it to drive optimization
445 such as those disabling dynamic branch prediction for well predictable
448 There are two exceptions - edges leading to noreturn edges and edges
449 predicted by number of iterations heuristics are predicted well. This macro
450 should be able to distinguish those, but at the moment it simply check for
451 noreturn heuristic that is only one giving probability over 99% or bellow
452 1%. In future we might want to propagate reliability information across the
453 CFG if we find this information useful on multiple places. */
455 probability_reliable_p (int prob
)
457 return (profile_status
== PROFILE_READ
458 || (profile_status
== PROFILE_GUESSED
459 && (prob
<= HITRATE (1) || prob
>= HITRATE (99))));
462 /* Same predicate as above, working on edges. */
464 edge_probability_reliable_p (const_edge e
)
466 return probability_reliable_p (e
->probability
);
469 /* Same predicate as edge_probability_reliable_p, working on notes. */
471 br_prob_note_reliable_p (const_rtx note
)
473 gcc_assert (REG_NOTE_KIND (note
) == REG_BR_PROB
);
474 return probability_reliable_p (INTVAL (XEXP (note
, 0)));
478 predict_insn (rtx insn
, enum br_predictor predictor
, int probability
)
480 gcc_assert (any_condjump_p (insn
));
481 if (!flag_guess_branch_prob
)
484 add_reg_note (insn
, REG_BR_PRED
,
485 gen_rtx_CONCAT (VOIDmode
,
486 GEN_INT ((int) predictor
),
487 GEN_INT ((int) probability
)));
490 /* Predict insn by given predictor. */
493 predict_insn_def (rtx insn
, enum br_predictor predictor
,
494 enum prediction taken
)
496 int probability
= predictor_info
[(int) predictor
].hitrate
;
499 probability
= REG_BR_PROB_BASE
- probability
;
501 predict_insn (insn
, predictor
, probability
);
504 /* Predict edge E with given probability if possible. */
507 rtl_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
510 last_insn
= BB_END (e
->src
);
512 /* We can store the branch prediction information only about
513 conditional jumps. */
514 if (!any_condjump_p (last_insn
))
517 /* We always store probability of branching. */
518 if (e
->flags
& EDGE_FALLTHRU
)
519 probability
= REG_BR_PROB_BASE
- probability
;
521 predict_insn (last_insn
, predictor
, probability
);
524 /* Predict edge E with the given PROBABILITY. */
526 gimple_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
528 gcc_assert (profile_status
!= PROFILE_GUESSED
);
529 if ((e
->src
!= ENTRY_BLOCK_PTR
&& EDGE_COUNT (e
->src
->succs
) > 1)
530 && flag_guess_branch_prob
&& optimize
)
532 struct edge_prediction
*i
= XNEW (struct edge_prediction
);
533 void **preds
= pointer_map_insert (bb_predictions
, e
->src
);
535 i
->ep_next
= (struct edge_prediction
*) *preds
;
537 i
->ep_probability
= probability
;
538 i
->ep_predictor
= predictor
;
543 /* Remove all predictions on given basic block that are attached
546 remove_predictions_associated_with_edge (edge e
)
553 preds
= pointer_map_contains (bb_predictions
, e
->src
);
557 struct edge_prediction
**prediction
= (struct edge_prediction
**) preds
;
558 struct edge_prediction
*next
;
562 if ((*prediction
)->ep_edge
== e
)
564 next
= (*prediction
)->ep_next
;
569 prediction
= &((*prediction
)->ep_next
);
574 /* Clears the list of predictions stored for BB. */
577 clear_bb_predictions (basic_block bb
)
579 void **preds
= pointer_map_contains (bb_predictions
, bb
);
580 struct edge_prediction
*pred
, *next
;
585 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= next
)
587 next
= pred
->ep_next
;
593 /* Return true when we can store prediction on insn INSN.
594 At the moment we represent predictions only on conditional
595 jumps, not at computed jump or other complicated cases. */
597 can_predict_insn_p (const_rtx insn
)
599 return (JUMP_P (insn
)
600 && any_condjump_p (insn
)
601 && EDGE_COUNT (BLOCK_FOR_INSN (insn
)->succs
) >= 2);
604 /* Predict edge E by given predictor if possible. */
607 predict_edge_def (edge e
, enum br_predictor predictor
,
608 enum prediction taken
)
610 int probability
= predictor_info
[(int) predictor
].hitrate
;
613 probability
= REG_BR_PROB_BASE
- probability
;
615 predict_edge (e
, predictor
, probability
);
618 /* Invert all branch predictions or probability notes in the INSN. This needs
619 to be done each time we invert the condition used by the jump. */
622 invert_br_probabilities (rtx insn
)
626 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
627 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
628 XEXP (note
, 0) = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (note
, 0)));
629 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
630 XEXP (XEXP (note
, 0), 1)
631 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
634 /* Dump information about the branch prediction to the output file. */
637 dump_prediction (FILE *file
, enum br_predictor predictor
, int probability
,
638 basic_block bb
, int used
)
646 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
647 if (! (e
->flags
& EDGE_FALLTHRU
))
650 fprintf (file
, " %s heuristics%s: %.1f%%",
651 predictor_info
[predictor
].name
,
652 used
? "" : " (ignored)", probability
* 100.0 / REG_BR_PROB_BASE
);
656 fprintf (file
, " exec ");
657 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, bb
->count
);
660 fprintf (file
, " hit ");
661 fprintf (file
, HOST_WIDEST_INT_PRINT_DEC
, e
->count
);
662 fprintf (file
, " (%.1f%%)", e
->count
* 100.0 / bb
->count
);
666 fprintf (file
, "\n");
669 /* We can not predict the probabilities of outgoing edges of bb. Set them
670 evenly and hope for the best. */
672 set_even_probabilities (basic_block bb
)
678 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
679 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
681 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
682 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
683 e
->probability
= (REG_BR_PROB_BASE
+ nedges
/ 2) / nedges
;
688 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
689 note if not already present. Remove now useless REG_BR_PRED notes. */
692 combine_predictions_for_insn (rtx insn
, basic_block bb
)
697 int best_probability
= PROB_EVEN
;
698 enum br_predictor best_predictor
= END_PREDICTORS
;
699 int combined_probability
= REG_BR_PROB_BASE
/ 2;
701 bool first_match
= false;
704 if (!can_predict_insn_p (insn
))
706 set_even_probabilities (bb
);
710 prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
711 pnote
= ®_NOTES (insn
);
713 fprintf (dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
716 /* We implement "first match" heuristics and use probability guessed
717 by predictor with smallest index. */
718 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
719 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
721 enum br_predictor predictor
= ((enum br_predictor
)
722 INTVAL (XEXP (XEXP (note
, 0), 0)));
723 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
726 if (best_predictor
> predictor
)
727 best_probability
= probability
, best_predictor
= predictor
;
729 d
= (combined_probability
* probability
730 + (REG_BR_PROB_BASE
- combined_probability
)
731 * (REG_BR_PROB_BASE
- probability
));
733 /* Use FP math to avoid overflows of 32bit integers. */
735 /* If one probability is 0% and one 100%, avoid division by zero. */
736 combined_probability
= REG_BR_PROB_BASE
/ 2;
738 combined_probability
= (((double) combined_probability
) * probability
739 * REG_BR_PROB_BASE
/ d
+ 0.5);
742 /* Decide which heuristic to use. In case we didn't match anything,
743 use no_prediction heuristic, in case we did match, use either
744 first match or Dempster-Shaffer theory depending on the flags. */
746 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
750 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
751 combined_probability
, bb
, true);
754 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
756 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
761 combined_probability
= best_probability
;
762 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
766 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
768 enum br_predictor predictor
= ((enum br_predictor
)
769 INTVAL (XEXP (XEXP (*pnote
, 0), 0)));
770 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
772 dump_prediction (dump_file
, predictor
, probability
, bb
,
773 !first_match
|| best_predictor
== predictor
);
774 *pnote
= XEXP (*pnote
, 1);
777 pnote
= &XEXP (*pnote
, 1);
782 add_reg_note (insn
, REG_BR_PROB
, GEN_INT (combined_probability
));
784 /* Save the prediction into CFG in case we are seeing non-degenerated
786 if (!single_succ_p (bb
))
788 BRANCH_EDGE (bb
)->probability
= combined_probability
;
789 FALLTHRU_EDGE (bb
)->probability
790 = REG_BR_PROB_BASE
- combined_probability
;
793 else if (!single_succ_p (bb
))
795 int prob
= INTVAL (XEXP (prob_note
, 0));
797 BRANCH_EDGE (bb
)->probability
= prob
;
798 FALLTHRU_EDGE (bb
)->probability
= REG_BR_PROB_BASE
- prob
;
801 single_succ_edge (bb
)->probability
= REG_BR_PROB_BASE
;
804 /* Combine predictions into single probability and store them into CFG.
805 Remove now useless prediction entries. */
808 combine_predictions_for_bb (basic_block bb
)
810 int best_probability
= PROB_EVEN
;
811 enum br_predictor best_predictor
= END_PREDICTORS
;
812 int combined_probability
= REG_BR_PROB_BASE
/ 2;
814 bool first_match
= false;
816 struct edge_prediction
*pred
;
818 edge e
, first
= NULL
, second
= NULL
;
822 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
823 if (!(e
->flags
& (EDGE_EH
| EDGE_FAKE
)))
826 if (first
&& !second
)
832 /* When there is no successor or only one choice, prediction is easy.
834 We are lazy for now and predict only basic blocks with two outgoing
835 edges. It is possible to predict generic case too, but we have to
836 ignore first match heuristics and do more involved combining. Implement
841 set_even_probabilities (bb
);
842 clear_bb_predictions (bb
);
844 fprintf (dump_file
, "%i edges in bb %i predicted to even probabilities\n",
850 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
852 preds
= pointer_map_contains (bb_predictions
, bb
);
855 /* We implement "first match" heuristics and use probability guessed
856 by predictor with smallest index. */
857 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
859 enum br_predictor predictor
= pred
->ep_predictor
;
860 int probability
= pred
->ep_probability
;
862 if (pred
->ep_edge
!= first
)
863 probability
= REG_BR_PROB_BASE
- probability
;
866 /* First match heuristics would be widly confused if we predicted
868 if (best_predictor
> predictor
)
870 struct edge_prediction
*pred2
;
871 int prob
= probability
;
873 for (pred2
= (struct edge_prediction
*) *preds
; pred2
; pred2
= pred2
->ep_next
)
874 if (pred2
!= pred
&& pred2
->ep_predictor
== pred
->ep_predictor
)
876 int probability2
= pred
->ep_probability
;
878 if (pred2
->ep_edge
!= first
)
879 probability2
= REG_BR_PROB_BASE
- probability2
;
881 if ((probability
< REG_BR_PROB_BASE
/ 2) !=
882 (probability2
< REG_BR_PROB_BASE
/ 2))
885 /* If the same predictor later gave better result, go for it! */
886 if ((probability
>= REG_BR_PROB_BASE
/ 2 && (probability2
> probability
))
887 || (probability
<= REG_BR_PROB_BASE
/ 2 && (probability2
< probability
)))
891 best_probability
= prob
, best_predictor
= predictor
;
894 d
= (combined_probability
* probability
895 + (REG_BR_PROB_BASE
- combined_probability
)
896 * (REG_BR_PROB_BASE
- probability
));
898 /* Use FP math to avoid overflows of 32bit integers. */
900 /* If one probability is 0% and one 100%, avoid division by zero. */
901 combined_probability
= REG_BR_PROB_BASE
/ 2;
903 combined_probability
= (((double) combined_probability
)
905 * REG_BR_PROB_BASE
/ d
+ 0.5);
909 /* Decide which heuristic to use. In case we didn't match anything,
910 use no_prediction heuristic, in case we did match, use either
911 first match or Dempster-Shaffer theory depending on the flags. */
913 if (predictor_info
[best_predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
917 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
, true);
920 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
922 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
927 combined_probability
= best_probability
;
928 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
, true);
932 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
934 enum br_predictor predictor
= pred
->ep_predictor
;
935 int probability
= pred
->ep_probability
;
937 if (pred
->ep_edge
!= EDGE_SUCC (bb
, 0))
938 probability
= REG_BR_PROB_BASE
- probability
;
939 dump_prediction (dump_file
, predictor
, probability
, bb
,
940 !first_match
|| best_predictor
== predictor
);
943 clear_bb_predictions (bb
);
947 first
->probability
= combined_probability
;
948 second
->probability
= REG_BR_PROB_BASE
- combined_probability
;
952 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
953 Return the SSA_NAME if the condition satisfies, NULL otherwise.
955 T1 and T2 should be one of the following cases:
956 1. T1 is SSA_NAME, T2 is NULL
957 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
958 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
961 strips_small_constant (tree t1
, tree t2
)
968 else if (TREE_CODE (t1
) == SSA_NAME
)
970 else if (host_integerp (t1
, 0))
971 value
= tree_low_cst (t1
, 0);
977 else if (host_integerp (t2
, 0))
978 value
= tree_low_cst (t2
, 0);
979 else if (TREE_CODE (t2
) == SSA_NAME
)
987 if (value
<= 4 && value
>= -4)
993 /* Return the SSA_NAME in T or T's operands.
994 Return NULL if SSA_NAME cannot be found. */
997 get_base_value (tree t
)
999 if (TREE_CODE (t
) == SSA_NAME
)
1002 if (!BINARY_CLASS_P (t
))
1005 switch (TREE_OPERAND_LENGTH (t
))
1008 return strips_small_constant (TREE_OPERAND (t
, 0), NULL
);
1010 return strips_small_constant (TREE_OPERAND (t
, 0),
1011 TREE_OPERAND (t
, 1));
1017 /* Check the compare STMT in LOOP. If it compares an induction
1018 variable to a loop invariant, return true, and save
1019 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1020 Otherwise return false and set LOOP_INVAIANT to NULL. */
1023 is_comparison_with_loop_invariant_p (gimple stmt
, struct loop
*loop
,
1024 tree
*loop_invariant
,
1025 enum tree_code
*compare_code
,
1029 tree op0
, op1
, bound
, base
;
1031 enum tree_code code
;
1034 code
= gimple_cond_code (stmt
);
1035 *loop_invariant
= NULL
;
1051 op0
= gimple_cond_lhs (stmt
);
1052 op1
= gimple_cond_rhs (stmt
);
1054 if ((TREE_CODE (op0
) != SSA_NAME
&& TREE_CODE (op0
) != INTEGER_CST
)
1055 || (TREE_CODE (op1
) != SSA_NAME
&& TREE_CODE (op1
) != INTEGER_CST
))
1057 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op0
, &iv0
, true))
1059 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op1
, &iv1
, true))
1061 if (TREE_CODE (iv0
.step
) != INTEGER_CST
1062 || TREE_CODE (iv1
.step
) != INTEGER_CST
)
1064 if ((integer_zerop (iv0
.step
) && integer_zerop (iv1
.step
))
1065 || (!integer_zerop (iv0
.step
) && !integer_zerop (iv1
.step
)))
1068 if (integer_zerop (iv0
.step
))
1070 if (code
!= NE_EXPR
&& code
!= EQ_EXPR
)
1071 code
= invert_tree_comparison (code
, false);
1074 if (host_integerp (iv1
.step
, 0))
1075 step
= tree_low_cst (iv1
.step
, 0);
1083 if (host_integerp (iv0
.step
, 0))
1084 step
= tree_low_cst (iv0
.step
, 0);
1089 if (TREE_CODE (bound
) != INTEGER_CST
)
1090 bound
= get_base_value (bound
);
1093 if (TREE_CODE (base
) != INTEGER_CST
)
1094 base
= get_base_value (base
);
1098 *loop_invariant
= bound
;
1099 *compare_code
= code
;
1101 *loop_iv_base
= base
;
1105 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1108 expr_coherent_p (tree t1
, tree t2
)
1111 tree ssa_name_1
= NULL
;
1112 tree ssa_name_2
= NULL
;
1114 gcc_assert (TREE_CODE (t1
) == SSA_NAME
|| TREE_CODE (t1
) == INTEGER_CST
);
1115 gcc_assert (TREE_CODE (t2
) == SSA_NAME
|| TREE_CODE (t2
) == INTEGER_CST
);
1120 if (TREE_CODE (t1
) == INTEGER_CST
&& TREE_CODE (t2
) == INTEGER_CST
)
1122 if (TREE_CODE (t1
) == INTEGER_CST
|| TREE_CODE (t2
) == INTEGER_CST
)
1125 /* Check to see if t1 is expressed/defined with t2. */
1126 stmt
= SSA_NAME_DEF_STMT (t1
);
1127 gcc_assert (stmt
!= NULL
);
1128 if (is_gimple_assign (stmt
))
1130 ssa_name_1
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1131 if (ssa_name_1
&& ssa_name_1
== t2
)
1135 /* Check to see if t2 is expressed/defined with t1. */
1136 stmt
= SSA_NAME_DEF_STMT (t2
);
1137 gcc_assert (stmt
!= NULL
);
1138 if (is_gimple_assign (stmt
))
1140 ssa_name_2
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1141 if (ssa_name_2
&& ssa_name_2
== t1
)
1145 /* Compare if t1 and t2's def_stmts are identical. */
1146 if (ssa_name_2
!= NULL
&& ssa_name_1
== ssa_name_2
)
1152 /* Predict branch probability of BB when BB contains a branch that compares
1153 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1154 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1157 for (int i = 0; i < bound; i++) {
1164 In this loop, we will predict the branch inside the loop to be taken. */
1167 predict_iv_comparison (struct loop
*loop
, basic_block bb
,
1168 tree loop_bound_var
,
1169 tree loop_iv_base_var
,
1170 enum tree_code loop_bound_code
,
1171 int loop_bound_step
)
1174 tree compare_var
, compare_base
;
1175 enum tree_code compare_code
;
1180 if (predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1181 || predicted_by_p (bb
, PRED_LOOP_ITERATIONS
)
1182 || predicted_by_p (bb
, PRED_LOOP_EXIT
))
1185 stmt
= last_stmt (bb
);
1186 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1188 if (!is_comparison_with_loop_invariant_p (stmt
, loop
, &compare_var
,
1194 /* Find the taken edge. */
1195 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1196 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1199 /* When comparing an IV to a loop invariant, NE is more likely to be
1200 taken while EQ is more likely to be not-taken. */
1201 if (compare_code
== NE_EXPR
)
1203 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1206 else if (compare_code
== EQ_EXPR
)
1208 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1212 if (!expr_coherent_p (loop_iv_base_var
, compare_base
))
1215 /* If loop bound, base and compare bound are all constants, we can
1216 calculate the probability directly. */
1217 if (host_integerp (loop_bound_var
, 0)
1218 && host_integerp (compare_var
, 0)
1219 && host_integerp (compare_base
, 0))
1222 HOST_WIDE_INT compare_count
;
1223 HOST_WIDE_INT loop_bound
= tree_low_cst (loop_bound_var
, 0);
1224 HOST_WIDE_INT compare_bound
= tree_low_cst (compare_var
, 0);
1225 HOST_WIDE_INT base
= tree_low_cst (compare_base
, 0);
1226 HOST_WIDE_INT loop_count
= (loop_bound
- base
) / compare_step
;
1228 if ((compare_step
> 0)
1229 ^ (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1230 compare_count
= (loop_bound
- compare_bound
) / compare_step
;
1232 compare_count
= (compare_bound
- base
) / compare_step
;
1234 if (compare_code
== LE_EXPR
|| compare_code
== GE_EXPR
)
1236 if (loop_bound_code
== LE_EXPR
|| loop_bound_code
== GE_EXPR
)
1238 if (compare_count
< 0)
1243 if (loop_count
== 0)
1245 else if (compare_count
> loop_count
)
1246 probability
= REG_BR_PROB_BASE
;
1248 probability
= (double) REG_BR_PROB_BASE
* compare_count
/ loop_count
;
1249 predict_edge (then_edge
, PRED_LOOP_IV_COMPARE
, probability
);
1253 if (expr_coherent_p (loop_bound_var
, compare_var
))
1255 if ((loop_bound_code
== LT_EXPR
|| loop_bound_code
== LE_EXPR
)
1256 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1257 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1258 else if ((loop_bound_code
== GT_EXPR
|| loop_bound_code
== GE_EXPR
)
1259 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1260 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1261 else if (loop_bound_code
== NE_EXPR
)
1263 /* If the loop backedge condition is "(i != bound)", we do
1264 the comparison based on the step of IV:
1265 * step < 0 : backedge condition is like (i > bound)
1266 * step > 0 : backedge condition is like (i < bound) */
1267 gcc_assert (loop_bound_step
!= 0);
1268 if (loop_bound_step
> 0
1269 && (compare_code
== LT_EXPR
1270 || compare_code
== LE_EXPR
))
1271 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1272 else if (loop_bound_step
< 0
1273 && (compare_code
== GT_EXPR
1274 || compare_code
== GE_EXPR
))
1275 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1277 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1280 /* The branch is predicted not-taken if loop_bound_code is
1281 opposite with compare_code. */
1282 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1284 else if (expr_coherent_p (loop_iv_base_var
, compare_var
))
1287 for (i = s; i < h; i++)
1289 The branch should be predicted taken. */
1290 if (loop_bound_step
> 0
1291 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1292 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1293 else if (loop_bound_step
< 0
1294 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1295 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1297 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1301 /* Predict edge probabilities by exploiting loop structure. */
1304 predict_loops (void)
1309 /* Try to predict out blocks in a loop that are not part of a
1311 FOR_EACH_LOOP (li
, loop
, 0)
1313 basic_block bb
, *bbs
;
1314 unsigned j
, n_exits
;
1315 VEC (edge
, heap
) *exits
;
1316 struct tree_niter_desc niter_desc
;
1318 struct nb_iter_bound
*nb_iter
;
1319 enum tree_code loop_bound_code
= ERROR_MARK
;
1320 int loop_bound_step
= 0;
1321 tree loop_bound_var
= NULL
;
1322 tree loop_iv_base
= NULL
;
1325 exits
= get_loop_exit_edges (loop
);
1326 n_exits
= VEC_length (edge
, exits
);
1328 FOR_EACH_VEC_ELT (edge
, exits
, j
, ex
)
1331 HOST_WIDE_INT nitercst
;
1332 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
1334 enum br_predictor predictor
;
1336 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false))
1337 niter
= niter_desc
.niter
;
1338 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
1339 niter
= loop_niter_by_eval (loop
, ex
);
1341 if (TREE_CODE (niter
) == INTEGER_CST
)
1343 if (host_integerp (niter
, 1)
1344 && compare_tree_int (niter
, max
-1) == -1)
1345 nitercst
= tree_low_cst (niter
, 1) + 1;
1348 predictor
= PRED_LOOP_ITERATIONS
;
1350 /* If we have just one exit and we can derive some information about
1351 the number of iterations of the loop from the statements inside
1352 the loop, use it to predict this exit. */
1353 else if (n_exits
== 1)
1355 nitercst
= estimated_stmt_executions_int (loop
);
1361 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
1366 probability
= ((REG_BR_PROB_BASE
+ nitercst
/ 2) / nitercst
);
1367 predict_edge (ex
, predictor
, probability
);
1369 VEC_free (edge
, heap
, exits
);
1371 /* Find information about loop bound variables. */
1372 for (nb_iter
= loop
->bounds
; nb_iter
;
1373 nb_iter
= nb_iter
->next
)
1375 && gimple_code (nb_iter
->stmt
) == GIMPLE_COND
)
1377 stmt
= nb_iter
->stmt
;
1380 if (!stmt
&& last_stmt (loop
->header
)
1381 && gimple_code (last_stmt (loop
->header
)) == GIMPLE_COND
)
1382 stmt
= last_stmt (loop
->header
);
1384 is_comparison_with_loop_invariant_p (stmt
, loop
,
1390 bbs
= get_loop_body (loop
);
1392 for (j
= 0; j
< loop
->num_nodes
; j
++)
1394 int header_found
= 0;
1400 /* Bypass loop heuristics on continue statement. These
1401 statements construct loops via "non-loop" constructs
1402 in the source language and are better to be handled
1404 if (predicted_by_p (bb
, PRED_CONTINUE
))
1407 /* Loop branch heuristics - predict an edge back to a
1408 loop's head as taken. */
1409 if (bb
== loop
->latch
)
1411 e
= find_edge (loop
->latch
, loop
->header
);
1415 predict_edge_def (e
, PRED_LOOP_BRANCH
, TAKEN
);
1419 /* Loop exit heuristics - predict an edge exiting the loop if the
1420 conditional has no loop header successors as not taken. */
1422 /* If we already used more reliable loop exit predictors, do not
1423 bother with PRED_LOOP_EXIT. */
1424 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS_GUESSED
)
1425 && !predicted_by_p (bb
, PRED_LOOP_ITERATIONS
))
1427 /* For loop with many exits we don't want to predict all exits
1428 with the pretty large probability, because if all exits are
1429 considered in row, the loop would be predicted to iterate
1430 almost never. The code to divide probability by number of
1431 exits is very rough. It should compute the number of exits
1432 taken in each patch through function (not the overall number
1433 of exits that might be a lot higher for loops with wide switch
1434 statements in them) and compute n-th square root.
1436 We limit the minimal probability by 2% to avoid
1437 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1438 as this was causing regression in perl benchmark containing such
1441 int probability
= ((REG_BR_PROB_BASE
1442 - predictor_info
[(int) PRED_LOOP_EXIT
].hitrate
)
1444 if (probability
< HITRATE (2))
1445 probability
= HITRATE (2);
1446 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1447 if (e
->dest
->index
< NUM_FIXED_BLOCKS
1448 || !flow_bb_inside_loop_p (loop
, e
->dest
))
1449 predict_edge (e
, PRED_LOOP_EXIT
, probability
);
1452 predict_iv_comparison (loop
, bb
, loop_bound_var
, loop_iv_base
,
1457 /* Free basic blocks from get_loop_body. */
1462 /* Attempt to predict probabilities of BB outgoing edges using local
1465 bb_estimate_probability_locally (basic_block bb
)
1467 rtx last_insn
= BB_END (bb
);
1470 if (! can_predict_insn_p (last_insn
))
1472 cond
= get_condition (last_insn
, NULL
, false, false);
1476 /* Try "pointer heuristic."
1477 A comparison ptr == 0 is predicted as false.
1478 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1479 if (COMPARISON_P (cond
)
1480 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
1481 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
1483 if (GET_CODE (cond
) == EQ
)
1484 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
1485 else if (GET_CODE (cond
) == NE
)
1486 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
1490 /* Try "opcode heuristic."
1491 EQ tests are usually false and NE tests are usually true. Also,
1492 most quantities are positive, so we can make the appropriate guesses
1493 about signed comparisons against zero. */
1494 switch (GET_CODE (cond
))
1497 /* Unconditional branch. */
1498 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
1499 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
1504 /* Floating point comparisons appears to behave in a very
1505 unpredictable way because of special role of = tests in
1507 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1509 /* Comparisons with 0 are often used for booleans and there is
1510 nothing useful to predict about them. */
1511 else if (XEXP (cond
, 1) == const0_rtx
1512 || XEXP (cond
, 0) == const0_rtx
)
1515 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
1520 /* Floating point comparisons appears to behave in a very
1521 unpredictable way because of special role of = tests in
1523 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
1525 /* Comparisons with 0 are often used for booleans and there is
1526 nothing useful to predict about them. */
1527 else if (XEXP (cond
, 1) == const0_rtx
1528 || XEXP (cond
, 0) == const0_rtx
)
1531 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
1535 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
1539 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
1544 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1545 || XEXP (cond
, 1) == constm1_rtx
)
1546 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
1551 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
1552 || XEXP (cond
, 1) == constm1_rtx
)
1553 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
1561 /* Set edge->probability for each successor edge of BB. */
1563 guess_outgoing_edge_probabilities (basic_block bb
)
1565 bb_estimate_probability_locally (bb
);
1566 combine_predictions_for_insn (BB_END (bb
), bb
);
1569 static tree
expr_expected_value (tree
, bitmap
);
1571 /* Helper function for expr_expected_value. */
1574 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
,
1575 tree op1
, bitmap visited
)
1579 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
1581 if (TREE_CONSTANT (op0
))
1584 if (code
!= SSA_NAME
)
1587 def
= SSA_NAME_DEF_STMT (op0
);
1589 /* If we were already here, break the infinite cycle. */
1590 if (!bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
)))
1593 if (gimple_code (def
) == GIMPLE_PHI
)
1595 /* All the arguments of the PHI node must have the same constant
1597 int i
, n
= gimple_phi_num_args (def
);
1598 tree val
= NULL
, new_val
;
1600 for (i
= 0; i
< n
; i
++)
1602 tree arg
= PHI_ARG_DEF (def
, i
);
1604 /* If this PHI has itself as an argument, we cannot
1605 determine the string length of this argument. However,
1606 if we can find an expected constant value for the other
1607 PHI args then we can still be sure that this is
1608 likely a constant. So be optimistic and just
1609 continue with the next argument. */
1610 if (arg
== PHI_RESULT (def
))
1613 new_val
= expr_expected_value (arg
, visited
);
1618 else if (!operand_equal_p (val
, new_val
, false))
1623 if (is_gimple_assign (def
))
1625 if (gimple_assign_lhs (def
) != op0
)
1628 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
1629 gimple_assign_rhs1 (def
),
1630 gimple_assign_rhs_code (def
),
1631 gimple_assign_rhs2 (def
),
1635 if (is_gimple_call (def
))
1637 tree decl
= gimple_call_fndecl (def
);
1640 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
)
1641 switch (DECL_FUNCTION_CODE (decl
))
1643 case BUILT_IN_EXPECT
:
1646 if (gimple_call_num_args (def
) != 2)
1648 val
= gimple_call_arg (def
, 0);
1649 if (TREE_CONSTANT (val
))
1651 return gimple_call_arg (def
, 1);
1654 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
:
1655 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1
:
1656 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2
:
1657 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4
:
1658 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8
:
1659 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16
:
1660 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE
:
1661 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N
:
1662 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1
:
1663 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2
:
1664 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4
:
1665 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8
:
1666 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16
:
1667 /* Assume that any given atomic operation has low contention,
1668 and thus the compare-and-swap operation succeeds. */
1669 return boolean_true_node
;
1676 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
1679 op0
= expr_expected_value (op0
, visited
);
1682 op1
= expr_expected_value (op1
, visited
);
1685 res
= fold_build2 (code
, type
, op0
, op1
);
1686 if (TREE_CONSTANT (res
))
1690 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
1693 op0
= expr_expected_value (op0
, visited
);
1696 res
= fold_build1 (code
, type
, op0
);
1697 if (TREE_CONSTANT (res
))
1704 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1705 The function is used by builtin_expect branch predictor so the evidence
1706 must come from this construct and additional possible constant folding.
1708 We may want to implement more involved value guess (such as value range
1709 propagation based prediction), but such tricks shall go to new
1713 expr_expected_value (tree expr
, bitmap visited
)
1715 enum tree_code code
;
1718 if (TREE_CONSTANT (expr
))
1721 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
1722 return expr_expected_value_1 (TREE_TYPE (expr
),
1723 op0
, code
, op1
, visited
);
1727 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1728 we no longer need. */
1730 strip_predict_hints (void)
1738 gimple_stmt_iterator bi
;
1739 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
);)
1741 gimple stmt
= gsi_stmt (bi
);
1743 if (gimple_code (stmt
) == GIMPLE_PREDICT
)
1745 gsi_remove (&bi
, true);
1748 else if (gimple_code (stmt
) == GIMPLE_CALL
)
1750 tree fndecl
= gimple_call_fndecl (stmt
);
1753 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
1754 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
1755 && gimple_call_num_args (stmt
) == 2)
1757 var
= gimple_call_lhs (stmt
);
1761 = gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
1762 gsi_replace (&bi
, ass_stmt
, true);
1766 gsi_remove (&bi
, true);
1777 /* Predict using opcode of the last statement in basic block. */
1779 tree_predict_by_opcode (basic_block bb
)
1781 gimple stmt
= last_stmt (bb
);
1790 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1792 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1793 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1795 op0
= gimple_cond_lhs (stmt
);
1796 op1
= gimple_cond_rhs (stmt
);
1797 cmp
= gimple_cond_code (stmt
);
1798 type
= TREE_TYPE (op0
);
1799 visited
= BITMAP_ALLOC (NULL
);
1800 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, visited
);
1801 BITMAP_FREE (visited
);
1804 if (integer_zerop (val
))
1805 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, NOT_TAKEN
);
1807 predict_edge_def (then_edge
, PRED_BUILTIN_EXPECT
, TAKEN
);
1810 /* Try "pointer heuristic."
1811 A comparison ptr == 0 is predicted as false.
1812 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1813 if (POINTER_TYPE_P (type
))
1816 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
1817 else if (cmp
== NE_EXPR
)
1818 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
1822 /* Try "opcode heuristic."
1823 EQ tests are usually false and NE tests are usually true. Also,
1824 most quantities are positive, so we can make the appropriate guesses
1825 about signed comparisons against zero. */
1830 /* Floating point comparisons appears to behave in a very
1831 unpredictable way because of special role of = tests in
1833 if (FLOAT_TYPE_P (type
))
1835 /* Comparisons with 0 are often used for booleans and there is
1836 nothing useful to predict about them. */
1837 else if (integer_zerop (op0
) || integer_zerop (op1
))
1840 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
1845 /* Floating point comparisons appears to behave in a very
1846 unpredictable way because of special role of = tests in
1848 if (FLOAT_TYPE_P (type
))
1850 /* Comparisons with 0 are often used for booleans and there is
1851 nothing useful to predict about them. */
1852 else if (integer_zerop (op0
)
1853 || integer_zerop (op1
))
1856 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
1860 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
1863 case UNORDERED_EXPR
:
1864 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
1869 if (integer_zerop (op1
)
1870 || integer_onep (op1
)
1871 || integer_all_onesp (op1
)
1874 || real_minus_onep (op1
))
1875 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
1880 if (integer_zerop (op1
)
1881 || integer_onep (op1
)
1882 || integer_all_onesp (op1
)
1885 || real_minus_onep (op1
))
1886 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
1894 /* Try to guess whether the value of return means error code. */
1896 static enum br_predictor
1897 return_prediction (tree val
, enum prediction
*prediction
)
1901 return PRED_NO_PREDICTION
;
1902 /* Different heuristics for pointers and scalars. */
1903 if (POINTER_TYPE_P (TREE_TYPE (val
)))
1905 /* NULL is usually not returned. */
1906 if (integer_zerop (val
))
1908 *prediction
= NOT_TAKEN
;
1909 return PRED_NULL_RETURN
;
1912 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
1914 /* Negative return values are often used to indicate
1916 if (TREE_CODE (val
) == INTEGER_CST
1917 && tree_int_cst_sgn (val
) < 0)
1919 *prediction
= NOT_TAKEN
;
1920 return PRED_NEGATIVE_RETURN
;
1922 /* Constant return values seems to be commonly taken.
1923 Zero/one often represent booleans so exclude them from the
1925 if (TREE_CONSTANT (val
)
1926 && (!integer_zerop (val
) && !integer_onep (val
)))
1928 *prediction
= TAKEN
;
1929 return PRED_CONST_RETURN
;
1932 return PRED_NO_PREDICTION
;
1935 /* Find the basic block with return expression and look up for possible
1936 return value trying to apply RETURN_PREDICTION heuristics. */
1938 apply_return_prediction (void)
1940 gimple return_stmt
= NULL
;
1944 int phi_num_args
, i
;
1945 enum br_predictor pred
;
1946 enum prediction direction
;
1949 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
1951 return_stmt
= last_stmt (e
->src
);
1953 && gimple_code (return_stmt
) == GIMPLE_RETURN
)
1958 return_val
= gimple_return_retval (return_stmt
);
1961 if (TREE_CODE (return_val
) != SSA_NAME
1962 || !SSA_NAME_DEF_STMT (return_val
)
1963 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
1965 phi
= SSA_NAME_DEF_STMT (return_val
);
1966 phi_num_args
= gimple_phi_num_args (phi
);
1967 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
1969 /* Avoid the degenerate case where all return values form the function
1970 belongs to same category (ie they are all positive constants)
1971 so we can hardly say something about them. */
1972 for (i
= 1; i
< phi_num_args
; i
++)
1973 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
1975 if (i
!= phi_num_args
)
1976 for (i
= 0; i
< phi_num_args
; i
++)
1978 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
1979 if (pred
!= PRED_NO_PREDICTION
)
1980 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi
, i
), pred
,
1985 /* Look for basic block that contains unlikely to happen events
1986 (such as noreturn calls) and mark all paths leading to execution
1987 of this basic blocks as unlikely. */
1990 tree_bb_level_predictions (void)
1993 bool has_return_edges
= false;
1997 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR
->preds
)
1998 if (!(e
->flags
& (EDGE_ABNORMAL
| EDGE_FAKE
| EDGE_EH
)))
2000 has_return_edges
= true;
2004 apply_return_prediction ();
2008 gimple_stmt_iterator gsi
;
2010 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
2012 gimple stmt
= gsi_stmt (gsi
);
2015 if (is_gimple_call (stmt
))
2017 if ((gimple_call_flags (stmt
) & ECF_NORETURN
)
2018 && has_return_edges
)
2019 predict_paths_leading_to (bb
, PRED_NORETURN
,
2021 decl
= gimple_call_fndecl (stmt
);
2023 && lookup_attribute ("cold",
2024 DECL_ATTRIBUTES (decl
)))
2025 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
2028 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
2030 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
2031 gimple_predict_outcome (stmt
));
2032 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2033 hints to callers. */
2039 #ifdef ENABLE_CHECKING
2041 /* Callback for pointer_map_traverse, asserts that the pointer map is
2045 assert_is_empty (const void *key ATTRIBUTE_UNUSED
, void **value
,
2046 void *data ATTRIBUTE_UNUSED
)
2048 gcc_assert (!*value
);
2053 /* Predict branch probabilities and estimate profile for basic block BB. */
2056 tree_estimate_probability_bb (basic_block bb
)
2062 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2064 /* Predict edges to user labels with attributes. */
2065 if (e
->dest
!= EXIT_BLOCK_PTR
)
2067 gimple_stmt_iterator gi
;
2068 for (gi
= gsi_start_bb (e
->dest
); !gsi_end_p (gi
); gsi_next (&gi
))
2070 gimple stmt
= gsi_stmt (gi
);
2073 if (gimple_code (stmt
) != GIMPLE_LABEL
)
2075 decl
= gimple_label_label (stmt
);
2076 if (DECL_ARTIFICIAL (decl
))
2079 /* Finally, we have a user-defined label. */
2080 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl
)))
2081 predict_edge_def (e
, PRED_COLD_LABEL
, NOT_TAKEN
);
2082 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl
)))
2083 predict_edge_def (e
, PRED_HOT_LABEL
, TAKEN
);
2087 /* Predict early returns to be probable, as we've already taken
2088 care for error returns and other cases are often used for
2089 fast paths through function.
2091 Since we've already removed the return statements, we are
2092 looking for CFG like:
2102 if (e
->dest
!= bb
->next_bb
2103 && e
->dest
!= EXIT_BLOCK_PTR
2104 && single_succ_p (e
->dest
)
2105 && single_succ_edge (e
->dest
)->dest
== EXIT_BLOCK_PTR
2106 && (last
= last_stmt (e
->dest
)) != NULL
2107 && gimple_code (last
) == GIMPLE_RETURN
)
2112 if (single_succ_p (bb
))
2114 FOR_EACH_EDGE (e1
, ei1
, bb
->preds
)
2115 if (!predicted_by_p (e1
->src
, PRED_NULL_RETURN
)
2116 && !predicted_by_p (e1
->src
, PRED_CONST_RETURN
)
2117 && !predicted_by_p (e1
->src
, PRED_NEGATIVE_RETURN
))
2118 predict_edge_def (e1
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2121 if (!predicted_by_p (e
->src
, PRED_NULL_RETURN
)
2122 && !predicted_by_p (e
->src
, PRED_CONST_RETURN
)
2123 && !predicted_by_p (e
->src
, PRED_NEGATIVE_RETURN
))
2124 predict_edge_def (e
, PRED_TREE_EARLY_RETURN
, NOT_TAKEN
);
2127 /* Look for block we are guarding (ie we dominate it,
2128 but it doesn't postdominate us). */
2129 if (e
->dest
!= EXIT_BLOCK_PTR
&& e
->dest
!= bb
2130 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
2131 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
2133 gimple_stmt_iterator bi
;
2135 /* The call heuristic claims that a guarded function call
2136 is improbable. This is because such calls are often used
2137 to signal exceptional situations such as printing error
2139 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
2142 gimple stmt
= gsi_stmt (bi
);
2143 if (is_gimple_call (stmt
)
2144 /* Constant and pure calls are hardly used to signalize
2145 something exceptional. */
2146 && gimple_has_side_effects (stmt
))
2148 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
2154 tree_predict_by_opcode (bb
);
2157 /* Predict branch probabilities and estimate profile of the tree CFG.
2158 This function can be called from the loop optimizers to recompute
2159 the profile information. */
2162 tree_estimate_probability (void)
2166 add_noreturn_fake_exit_edges ();
2167 connect_infinite_loops_to_exit ();
2168 /* We use loop_niter_by_eval, which requires that the loops have
2170 create_preheaders (CP_SIMPLE_PREHEADERS
);
2171 calculate_dominance_info (CDI_POST_DOMINATORS
);
2173 bb_predictions
= pointer_map_create ();
2174 tree_bb_level_predictions ();
2175 record_loop_exits ();
2177 if (number_of_loops () > 1)
2181 tree_estimate_probability_bb (bb
);
2184 combine_predictions_for_bb (bb
);
2186 #ifdef ENABLE_CHECKING
2187 pointer_map_traverse (bb_predictions
, assert_is_empty
, NULL
);
2189 pointer_map_destroy (bb_predictions
);
2190 bb_predictions
= NULL
;
2192 estimate_bb_frequencies ();
2193 free_dominance_info (CDI_POST_DOMINATORS
);
2194 remove_fake_exit_edges ();
2197 /* Predict branch probabilities and estimate profile of the tree CFG.
2198 This is the driver function for PASS_PROFILE. */
2201 tree_estimate_probability_driver (void)
2205 loop_optimizer_init (LOOPS_NORMAL
);
2206 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2207 flow_loops_dump (dump_file
, NULL
, 0);
2209 mark_irreducible_loops ();
2211 nb_loops
= number_of_loops ();
2215 tree_estimate_probability ();
2220 loop_optimizer_finalize ();
2221 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2222 gimple_dump_cfg (dump_file
, dump_flags
);
2223 if (profile_status
== PROFILE_ABSENT
)
2224 profile_status
= PROFILE_GUESSED
;
2228 /* Predict edges to successors of CUR whose sources are not postdominated by
2229 BB by PRED and recurse to all postdominators. */
2232 predict_paths_for_bb (basic_block cur
, basic_block bb
,
2233 enum br_predictor pred
,
2234 enum prediction taken
,
2241 /* We are looking for all edges forming edge cut induced by
2242 set of all blocks postdominated by BB. */
2243 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
2244 if (e
->src
->index
>= NUM_FIXED_BLOCKS
2245 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
2251 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2252 if (e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2254 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
2256 /* See if there is an edge from e->src that is not abnormal
2257 and does not lead to BB. */
2258 FOR_EACH_EDGE (e2
, ei2
, e
->src
->succs
)
2260 && !(e2
->flags
& (EDGE_EH
| EDGE_FAKE
))
2261 && !dominated_by_p (CDI_POST_DOMINATORS
, e2
->dest
, bb
))
2267 /* If there is non-abnormal path leaving e->src, predict edge
2268 using predictor. Otherwise we need to look for paths
2271 The second may lead to infinite loop in the case we are predicitng
2272 regions that are only reachable by abnormal edges. We simply
2273 prevent visiting given BB twice. */
2275 predict_edge_def (e
, pred
, taken
);
2276 else if (bitmap_set_bit (visited
, e
->src
->index
))
2277 predict_paths_for_bb (e
->src
, e
->src
, pred
, taken
, visited
);
2279 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
2281 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
2282 predict_paths_for_bb (son
, bb
, pred
, taken
, visited
);
2285 /* Sets branch probabilities according to PREDiction and
2289 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
2290 enum prediction taken
)
2292 bitmap visited
= BITMAP_ALLOC (NULL
);
2293 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2294 BITMAP_FREE (visited
);
2297 /* Like predict_paths_leading_to but take edge instead of basic block. */
2300 predict_paths_leading_to_edge (edge e
, enum br_predictor pred
,
2301 enum prediction taken
)
2303 bool has_nonloop_edge
= false;
2307 basic_block bb
= e
->src
;
2308 FOR_EACH_EDGE (e2
, ei
, bb
->succs
)
2309 if (e2
->dest
!= e
->src
&& e2
->dest
!= e
->dest
2310 && !(e
->flags
& (EDGE_EH
| EDGE_FAKE
))
2311 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e2
->dest
))
2313 has_nonloop_edge
= true;
2316 if (!has_nonloop_edge
)
2318 bitmap visited
= BITMAP_ALLOC (NULL
);
2319 predict_paths_for_bb (bb
, bb
, pred
, taken
, visited
);
2320 BITMAP_FREE (visited
);
2323 predict_edge_def (e
, pred
, taken
);
2326 /* This is used to carry information about basic blocks. It is
2327 attached to the AUX field of the standard CFG block. */
2329 typedef struct block_info_def
2331 /* Estimated frequency of execution of basic_block. */
2334 /* To keep queue of basic blocks to process. */
2337 /* Number of predecessors we need to visit first. */
2341 /* Similar information for edges. */
2342 typedef struct edge_info_def
2344 /* In case edge is a loopback edge, the probability edge will be reached
2345 in case header is. Estimated number of iterations of the loop can be
2346 then computed as 1 / (1 - back_edge_prob). */
2347 sreal back_edge_prob
;
2348 /* True if the edge is a loopback edge in the natural loop. */
2349 unsigned int back_edge
:1;
2352 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2353 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2355 /* Helper function for estimate_bb_frequencies.
2356 Propagate the frequencies in blocks marked in
2357 TOVISIT, starting in HEAD. */
2360 propagate_freq (basic_block head
, bitmap tovisit
)
2369 /* For each basic block we need to visit count number of his predecessors
2370 we need to visit first. */
2371 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
2376 bb
= BASIC_BLOCK (i
);
2378 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2380 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
2382 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
2384 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
2386 "Irreducible region hit, ignoring edge to %i->%i\n",
2387 e
->src
->index
, bb
->index
);
2389 BLOCK_INFO (bb
)->npredecessors
= count
;
2390 /* When function never returns, we will never process exit block. */
2391 if (!count
&& bb
== EXIT_BLOCK_PTR
)
2392 bb
->count
= bb
->frequency
= 0;
2395 memcpy (&BLOCK_INFO (head
)->frequency
, &real_one
, sizeof (real_one
));
2397 for (bb
= head
; bb
; bb
= nextbb
)
2400 sreal cyclic_probability
, frequency
;
2402 memcpy (&cyclic_probability
, &real_zero
, sizeof (real_zero
));
2403 memcpy (&frequency
, &real_zero
, sizeof (real_zero
));
2405 nextbb
= BLOCK_INFO (bb
)->next
;
2406 BLOCK_INFO (bb
)->next
= NULL
;
2408 /* Compute frequency of basic block. */
2411 #ifdef ENABLE_CHECKING
2412 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2413 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
2414 || (e
->flags
& EDGE_DFS_BACK
));
2417 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
2418 if (EDGE_INFO (e
)->back_edge
)
2420 sreal_add (&cyclic_probability
, &cyclic_probability
,
2421 &EDGE_INFO (e
)->back_edge_prob
);
2423 else if (!(e
->flags
& EDGE_DFS_BACK
))
2427 /* frequency += (e->probability
2428 * BLOCK_INFO (e->src)->frequency /
2429 REG_BR_PROB_BASE); */
2431 sreal_init (&tmp
, e
->probability
, 0);
2432 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (e
->src
)->frequency
);
2433 sreal_mul (&tmp
, &tmp
, &real_inv_br_prob_base
);
2434 sreal_add (&frequency
, &frequency
, &tmp
);
2437 if (sreal_compare (&cyclic_probability
, &real_zero
) == 0)
2439 memcpy (&BLOCK_INFO (bb
)->frequency
, &frequency
,
2440 sizeof (frequency
));
2444 if (sreal_compare (&cyclic_probability
, &real_almost_one
) > 0)
2446 memcpy (&cyclic_probability
, &real_almost_one
,
2447 sizeof (real_almost_one
));
2450 /* BLOCK_INFO (bb)->frequency = frequency
2451 / (1 - cyclic_probability) */
2453 sreal_sub (&cyclic_probability
, &real_one
, &cyclic_probability
);
2454 sreal_div (&BLOCK_INFO (bb
)->frequency
,
2455 &frequency
, &cyclic_probability
);
2459 bitmap_clear_bit (tovisit
, bb
->index
);
2461 e
= find_edge (bb
, head
);
2466 /* EDGE_INFO (e)->back_edge_prob
2467 = ((e->probability * BLOCK_INFO (bb)->frequency)
2468 / REG_BR_PROB_BASE); */
2470 sreal_init (&tmp
, e
->probability
, 0);
2471 sreal_mul (&tmp
, &tmp
, &BLOCK_INFO (bb
)->frequency
);
2472 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2473 &tmp
, &real_inv_br_prob_base
);
2476 /* Propagate to successor blocks. */
2477 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2478 if (!(e
->flags
& EDGE_DFS_BACK
)
2479 && BLOCK_INFO (e
->dest
)->npredecessors
)
2481 BLOCK_INFO (e
->dest
)->npredecessors
--;
2482 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
2487 BLOCK_INFO (last
)->next
= e
->dest
;
2495 /* Estimate probabilities of loopback edges in loops at same nest level. */
2498 estimate_loops_at_level (struct loop
*first_loop
)
2502 for (loop
= first_loop
; loop
; loop
= loop
->next
)
2507 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2509 estimate_loops_at_level (loop
->inner
);
2511 /* Find current loop back edge and mark it. */
2512 e
= loop_latch_edge (loop
);
2513 EDGE_INFO (e
)->back_edge
= 1;
2515 bbs
= get_loop_body (loop
);
2516 for (i
= 0; i
< loop
->num_nodes
; i
++)
2517 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
2519 propagate_freq (loop
->header
, tovisit
);
2520 BITMAP_FREE (tovisit
);
2524 /* Propagates frequencies through structure of loops. */
2527 estimate_loops (void)
2529 bitmap tovisit
= BITMAP_ALLOC (NULL
);
2532 /* Start by estimating the frequencies in the loops. */
2533 if (number_of_loops () > 1)
2534 estimate_loops_at_level (current_loops
->tree_root
->inner
);
2536 /* Now propagate the frequencies through all the blocks. */
2539 bitmap_set_bit (tovisit
, bb
->index
);
2541 propagate_freq (ENTRY_BLOCK_PTR
, tovisit
);
2542 BITMAP_FREE (tovisit
);
2545 /* Convert counts measured by profile driven feedback to frequencies.
2546 Return nonzero iff there was any nonzero execution count. */
2549 counts_to_freqs (void)
2551 gcov_type count_max
, true_count_max
= 0;
2554 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2555 true_count_max
= MAX (bb
->count
, true_count_max
);
2557 count_max
= MAX (true_count_max
, 1);
2558 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2559 bb
->frequency
= (bb
->count
* BB_FREQ_MAX
+ count_max
/ 2) / count_max
;
2561 return true_count_max
;
2564 /* Return true if function is likely to be expensive, so there is no point to
2565 optimize performance of prologue, epilogue or do inlining at the expense
2566 of code size growth. THRESHOLD is the limit of number of instructions
2567 function can execute at average to be still considered not expensive. */
2570 expensive_function_p (int threshold
)
2572 unsigned int sum
= 0;
2576 /* We can not compute accurately for large thresholds due to scaled
2578 gcc_assert (threshold
<= BB_FREQ_MAX
);
2580 /* Frequencies are out of range. This either means that function contains
2581 internal loop executing more than BB_FREQ_MAX times or profile feedback
2582 is available and function has not been executed at all. */
2583 if (ENTRY_BLOCK_PTR
->frequency
== 0)
2586 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2587 limit
= ENTRY_BLOCK_PTR
->frequency
* threshold
;
2592 for (insn
= BB_HEAD (bb
); insn
!= NEXT_INSN (BB_END (bb
));
2593 insn
= NEXT_INSN (insn
))
2594 if (active_insn_p (insn
))
2596 sum
+= bb
->frequency
;
2605 /* Estimate basic blocks frequency by given branch probabilities. */
2608 estimate_bb_frequencies (void)
2613 if (profile_status
!= PROFILE_READ
|| !counts_to_freqs ())
2615 static int real_values_initialized
= 0;
2617 if (!real_values_initialized
)
2619 real_values_initialized
= 1;
2620 sreal_init (&real_zero
, 0, 0);
2621 sreal_init (&real_one
, 1, 0);
2622 sreal_init (&real_br_prob_base
, REG_BR_PROB_BASE
, 0);
2623 sreal_init (&real_bb_freq_max
, BB_FREQ_MAX
, 0);
2624 sreal_init (&real_one_half
, 1, -1);
2625 sreal_div (&real_inv_br_prob_base
, &real_one
, &real_br_prob_base
);
2626 sreal_sub (&real_almost_one
, &real_one
, &real_inv_br_prob_base
);
2629 mark_dfs_back_edges ();
2631 single_succ_edge (ENTRY_BLOCK_PTR
)->probability
= REG_BR_PROB_BASE
;
2633 /* Set up block info for each basic block. */
2634 alloc_aux_for_blocks (sizeof (struct block_info_def
));
2635 alloc_aux_for_edges (sizeof (struct edge_info_def
));
2636 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2641 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2643 sreal_init (&EDGE_INFO (e
)->back_edge_prob
, e
->probability
, 0);
2644 sreal_mul (&EDGE_INFO (e
)->back_edge_prob
,
2645 &EDGE_INFO (e
)->back_edge_prob
,
2646 &real_inv_br_prob_base
);
2650 /* First compute probabilities locally for each loop from innermost
2651 to outermost to examine probabilities for back edges. */
2654 memcpy (&freq_max
, &real_zero
, sizeof (real_zero
));
2656 if (sreal_compare (&freq_max
, &BLOCK_INFO (bb
)->frequency
) < 0)
2657 memcpy (&freq_max
, &BLOCK_INFO (bb
)->frequency
, sizeof (freq_max
));
2659 sreal_div (&freq_max
, &real_bb_freq_max
, &freq_max
);
2660 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR
, NULL
, next_bb
)
2664 sreal_mul (&tmp
, &BLOCK_INFO (bb
)->frequency
, &freq_max
);
2665 sreal_add (&tmp
, &tmp
, &real_one_half
);
2666 bb
->frequency
= sreal_to_int (&tmp
);
2669 free_aux_for_blocks ();
2670 free_aux_for_edges ();
2672 compute_function_frequency ();
2675 /* Decide whether function is hot, cold or unlikely executed. */
2677 compute_function_frequency (void)
2680 struct cgraph_node
*node
= cgraph_get_node (current_function_decl
);
2681 if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2682 || MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2683 node
->only_called_at_startup
= true;
2684 if (DECL_STATIC_DESTRUCTOR (current_function_decl
))
2685 node
->only_called_at_exit
= true;
2687 if (!profile_info
|| !flag_branch_probabilities
)
2689 int flags
= flags_from_decl_or_type (current_function_decl
);
2690 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
2692 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2693 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
2695 node
->frequency
= NODE_FREQUENCY_HOT
;
2696 else if (flags
& ECF_NORETURN
)
2697 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2698 else if (MAIN_NAME_P (DECL_NAME (current_function_decl
)))
2699 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2700 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
2701 || DECL_STATIC_DESTRUCTOR (current_function_decl
))
2702 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
2705 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
2708 if (maybe_hot_bb_p (bb
))
2710 node
->frequency
= NODE_FREQUENCY_HOT
;
2713 if (!probably_never_executed_bb_p (bb
))
2714 node
->frequency
= NODE_FREQUENCY_NORMAL
;
2719 gate_estimate_probability (void)
2721 return flag_guess_branch_prob
;
2724 /* Build PREDICT_EXPR. */
2726 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
2728 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
2729 build_int_cst (integer_type_node
, predictor
));
2730 SET_PREDICT_EXPR_OUTCOME (t
, taken
);
2735 predictor_name (enum br_predictor predictor
)
2737 return predictor_info
[predictor
].name
;
2740 struct gimple_opt_pass pass_profile
=
2744 "profile_estimate", /* name */
2745 gate_estimate_probability
, /* gate */
2746 tree_estimate_probability_driver
, /* execute */
2749 0, /* static_pass_number */
2750 TV_BRANCH_PROB
, /* tv_id */
2751 PROP_cfg
, /* properties_required */
2752 0, /* properties_provided */
2753 0, /* properties_destroyed */
2754 0, /* todo_flags_start */
2755 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2759 struct gimple_opt_pass pass_strip_predict_hints
=
2763 "*strip_predict_hints", /* name */
2765 strip_predict_hints
, /* execute */
2768 0, /* static_pass_number */
2769 TV_BRANCH_PROB
, /* tv_id */
2770 PROP_cfg
, /* properties_required */
2771 0, /* properties_provided */
2772 0, /* properties_destroyed */
2773 0, /* todo_flags_start */
2774 TODO_ggc_collect
| TODO_verify_ssa
/* todo_flags_finish */
2778 /* Rebuild function frequencies. Passes are in general expected to
2779 maintain profile by hand, however in some cases this is not possible:
2780 for example when inlining several functions with loops freuqencies might run
2781 out of scale and thus needs to be recomputed. */
2784 rebuild_frequencies (void)
2786 timevar_push (TV_REBUILD_FREQUENCIES
);
2787 if (profile_status
== PROFILE_GUESSED
)
2789 loop_optimizer_init (0);
2790 add_noreturn_fake_exit_edges ();
2791 mark_irreducible_loops ();
2792 connect_infinite_loops_to_exit ();
2793 estimate_bb_frequencies ();
2794 remove_fake_exit_edges ();
2795 loop_optimizer_finalize ();
2797 else if (profile_status
== PROFILE_READ
)
2801 timevar_pop (TV_REBUILD_FREQUENCIES
);