1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000-2017 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"
38 #include "tree-pass.h"
44 #include "diagnostic-core.h"
45 #include "gimple-predict.h"
46 #include "fold-const.h"
53 #include "gimple-iterator.h"
55 #include "tree-ssa-loop-niter.h"
56 #include "tree-ssa-loop.h"
57 #include "tree-scalar-evolution.h"
58 #include "ipa-utils.h"
59 #include "gimple-pretty-print.h"
63 /* Enum with reasons why a predictor is ignored. */
69 REASON_SINGLE_EDGE_DUPLICATE
,
70 REASON_EDGE_PAIR_DUPLICATE
73 /* String messages for the aforementioned enum. */
75 static const char *reason_messages
[] = {"", " (ignored)",
76 " (single edge duplicate)", " (edge pair duplicate)"};
78 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
79 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
80 static sreal real_almost_one
, real_br_prob_base
,
81 real_inv_br_prob_base
, real_one_half
, real_bb_freq_max
;
83 static void combine_predictions_for_insn (rtx_insn
*, basic_block
);
84 static void dump_prediction (FILE *, enum br_predictor
, int, basic_block
,
85 enum predictor_reason
, edge
);
86 static void predict_paths_leading_to (basic_block
, enum br_predictor
,
88 struct loop
*in_loop
= NULL
);
89 static void predict_paths_leading_to_edge (edge
, enum br_predictor
,
91 struct loop
*in_loop
= NULL
);
92 static bool can_predict_insn_p (const rtx_insn
*);
94 /* Information we hold about each branch predictor.
95 Filled using information from predict.def. */
99 const char *const name
; /* Name used in the debugging dumps. */
100 const int hitrate
; /* Expected hitrate used by
101 predict_insn_def call. */
105 /* Use given predictor without Dempster-Shaffer theory if it matches
106 using first_match heuristics. */
107 #define PRED_FLAG_FIRST_MATCH 1
109 /* Recompute hitrate in percent to our representation. */
111 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
113 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
114 static const struct predictor_info predictor_info
[]= {
115 #include "predict.def"
117 /* Upper bound on predictors. */
122 /* Return TRUE if frequency FREQ is considered to be hot. */
125 maybe_hot_frequency_p (struct function
*fun
, int freq
)
127 struct cgraph_node
*node
= cgraph_node::get (fun
->decl
);
128 if (!profile_info
|| profile_status_for_fn (fun
) != PROFILE_READ
)
130 if (node
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
)
132 if (node
->frequency
== NODE_FREQUENCY_HOT
)
135 if (profile_status_for_fn (fun
) == PROFILE_ABSENT
)
137 if (node
->frequency
== NODE_FREQUENCY_EXECUTED_ONCE
138 && freq
< (ENTRY_BLOCK_PTR_FOR_FN (fun
)->frequency
* 2 / 3))
140 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
) == 0)
142 if (freq
* PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION
)
143 < ENTRY_BLOCK_PTR_FOR_FN (fun
)->frequency
)
148 static gcov_type min_count
= -1;
150 /* Determine the threshold for hot BB counts. */
153 get_hot_bb_threshold ()
155 gcov_working_set_t
*ws
;
158 ws
= find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE
));
160 min_count
= ws
->min_counter
;
165 /* Set the threshold for hot BB counts. */
168 set_hot_bb_threshold (gcov_type min
)
173 /* Return TRUE if frequency FREQ is considered to be hot. */
176 maybe_hot_count_p (struct function
*, profile_count count
)
178 if (!count
.initialized_p ())
180 /* Code executed at most once is not hot. */
181 if (count
<= MAX (profile_info
? profile_info
->runs
: 1, 1))
183 return (count
.to_gcov_type () >= get_hot_bb_threshold ());
186 /* Return true in case BB can be CPU intensive and should be optimized
187 for maximal performance. */
190 maybe_hot_bb_p (struct function
*fun
, const_basic_block bb
)
192 gcc_checking_assert (fun
);
193 if (!maybe_hot_count_p (fun
, bb
->count
))
195 return maybe_hot_frequency_p (fun
, bb
->frequency
);
198 /* Return true in case BB can be CPU intensive and should be optimized
199 for maximal performance. */
202 maybe_hot_edge_p (edge e
)
204 if (!maybe_hot_count_p (cfun
, e
->count
))
206 return maybe_hot_frequency_p (cfun
, EDGE_FREQUENCY (e
));
209 /* Return true if profile COUNT and FREQUENCY, or function FUN static
210 node frequency reflects never being executed. */
213 probably_never_executed (struct function
*fun
,
214 profile_count count
, int)
216 gcc_checking_assert (fun
);
217 if (count
== profile_count::zero ())
219 if (count
.initialized_p () && profile_status_for_fn (fun
) == PROFILE_READ
)
221 int unlikely_count_fraction
= PARAM_VALUE (UNLIKELY_BB_COUNT_FRACTION
);
222 if (count
.apply_scale (unlikely_count_fraction
, 1) >= profile_info
->runs
)
226 if ((!profile_info
|| profile_status_for_fn (fun
) != PROFILE_READ
)
227 && (cgraph_node::get (fun
->decl
)->frequency
228 == NODE_FREQUENCY_UNLIKELY_EXECUTED
))
234 /* Return true in case BB is probably never executed. */
237 probably_never_executed_bb_p (struct function
*fun
, const_basic_block bb
)
239 return probably_never_executed (fun
, bb
->count
, bb
->frequency
);
243 /* Return true if E is unlikely executed for obvious reasons. */
246 unlikely_executed_edge_p (edge e
)
248 return (e
->count
== profile_count::zero ()
249 || e
->probability
== profile_probability::never ())
250 || (e
->flags
& (EDGE_EH
| EDGE_FAKE
));
253 /* Return true in case edge E is probably never executed. */
256 probably_never_executed_edge_p (struct function
*fun
, edge e
)
258 if (unlikely_executed_edge_p (e
))
260 return probably_never_executed (fun
, e
->count
, EDGE_FREQUENCY (e
));
263 /* Return true when current function should always be optimized for size. */
266 optimize_function_for_size_p (struct function
*fun
)
268 if (!fun
|| !fun
->decl
)
269 return optimize_size
;
270 cgraph_node
*n
= cgraph_node::get (fun
->decl
);
271 return n
&& n
->optimize_for_size_p ();
274 /* Return true when current function should always be optimized for speed. */
277 optimize_function_for_speed_p (struct function
*fun
)
279 return !optimize_function_for_size_p (fun
);
282 /* Return the optimization type that should be used for the function FUN. */
285 function_optimization_type (struct function
*fun
)
287 return (optimize_function_for_speed_p (fun
)
289 : OPTIMIZE_FOR_SIZE
);
292 /* Return TRUE when BB should be optimized for size. */
295 optimize_bb_for_size_p (const_basic_block bb
)
297 return (optimize_function_for_size_p (cfun
)
298 || (bb
&& !maybe_hot_bb_p (cfun
, bb
)));
301 /* Return TRUE when BB should be optimized for speed. */
304 optimize_bb_for_speed_p (const_basic_block bb
)
306 return !optimize_bb_for_size_p (bb
);
309 /* Return the optimization type that should be used for block BB. */
312 bb_optimization_type (const_basic_block bb
)
314 return (optimize_bb_for_speed_p (bb
)
316 : OPTIMIZE_FOR_SIZE
);
319 /* Return TRUE when BB should be optimized for size. */
322 optimize_edge_for_size_p (edge e
)
324 return optimize_function_for_size_p (cfun
) || !maybe_hot_edge_p (e
);
327 /* Return TRUE when BB should be optimized for speed. */
330 optimize_edge_for_speed_p (edge e
)
332 return !optimize_edge_for_size_p (e
);
335 /* Return TRUE when BB should be optimized for size. */
338 optimize_insn_for_size_p (void)
340 return optimize_function_for_size_p (cfun
) || !crtl
->maybe_hot_insn_p
;
343 /* Return TRUE when BB should be optimized for speed. */
346 optimize_insn_for_speed_p (void)
348 return !optimize_insn_for_size_p ();
351 /* Return TRUE when LOOP should be optimized for size. */
354 optimize_loop_for_size_p (struct loop
*loop
)
356 return optimize_bb_for_size_p (loop
->header
);
359 /* Return TRUE when LOOP should be optimized for speed. */
362 optimize_loop_for_speed_p (struct loop
*loop
)
364 return optimize_bb_for_speed_p (loop
->header
);
367 /* Return TRUE when LOOP nest should be optimized for speed. */
370 optimize_loop_nest_for_speed_p (struct loop
*loop
)
372 struct loop
*l
= loop
;
373 if (optimize_loop_for_speed_p (loop
))
376 while (l
&& l
!= loop
)
378 if (optimize_loop_for_speed_p (l
))
386 while (l
!= loop
&& !l
->next
)
395 /* Return TRUE when LOOP nest should be optimized for size. */
398 optimize_loop_nest_for_size_p (struct loop
*loop
)
400 return !optimize_loop_nest_for_speed_p (loop
);
403 /* Return true when edge E is likely to be well predictable by branch
407 predictable_edge_p (edge e
)
409 if (!e
->probability
.initialized_p ())
411 if ((e
->probability
.to_reg_br_prob_base ()
412 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100)
413 || (REG_BR_PROB_BASE
- e
->probability
.to_reg_br_prob_base ()
414 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME
) * REG_BR_PROB_BASE
/ 100))
420 /* Set RTL expansion for BB profile. */
423 rtl_profile_for_bb (basic_block bb
)
425 crtl
->maybe_hot_insn_p
= maybe_hot_bb_p (cfun
, bb
);
428 /* Set RTL expansion for edge profile. */
431 rtl_profile_for_edge (edge e
)
433 crtl
->maybe_hot_insn_p
= maybe_hot_edge_p (e
);
436 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
438 default_rtl_profile (void)
440 crtl
->maybe_hot_insn_p
= true;
443 /* Return true if the one of outgoing edges is already predicted by
447 rtl_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
450 if (!INSN_P (BB_END (bb
)))
452 for (note
= REG_NOTES (BB_END (bb
)); note
; note
= XEXP (note
, 1))
453 if (REG_NOTE_KIND (note
) == REG_BR_PRED
454 && INTVAL (XEXP (XEXP (note
, 0), 0)) == (int)predictor
)
459 /* Structure representing predictions in tree level. */
461 struct edge_prediction
{
462 struct edge_prediction
*ep_next
;
464 enum br_predictor ep_predictor
;
468 /* This map contains for a basic block the list of predictions for the
471 static hash_map
<const_basic_block
, edge_prediction
*> *bb_predictions
;
473 /* Return true if the one of outgoing edges is already predicted by
477 gimple_predicted_by_p (const_basic_block bb
, enum br_predictor predictor
)
479 struct edge_prediction
*i
;
480 edge_prediction
**preds
= bb_predictions
->get (bb
);
485 for (i
= *preds
; i
; i
= i
->ep_next
)
486 if (i
->ep_predictor
== predictor
)
491 /* Return true if the one of outgoing edges is already predicted by
492 PREDICTOR for edge E predicted as TAKEN. */
495 edge_predicted_by_p (edge e
, enum br_predictor predictor
, bool taken
)
497 struct edge_prediction
*i
;
498 basic_block bb
= e
->src
;
499 edge_prediction
**preds
= bb_predictions
->get (bb
);
503 int probability
= predictor_info
[(int) predictor
].hitrate
;
506 probability
= REG_BR_PROB_BASE
- probability
;
508 for (i
= *preds
; i
; i
= i
->ep_next
)
509 if (i
->ep_predictor
== predictor
511 && i
->ep_probability
== probability
)
516 /* Same predicate as above, working on edges. */
518 edge_probability_reliable_p (const_edge e
)
520 return e
->probability
.probably_reliable_p ();
523 /* Same predicate as edge_probability_reliable_p, working on notes. */
525 br_prob_note_reliable_p (const_rtx note
)
527 gcc_assert (REG_NOTE_KIND (note
) == REG_BR_PROB
);
528 return profile_probability::from_reg_br_prob_note
529 (XINT (note
, 0)).probably_reliable_p ();
533 predict_insn (rtx_insn
*insn
, enum br_predictor predictor
, int probability
)
535 gcc_assert (any_condjump_p (insn
));
536 if (!flag_guess_branch_prob
)
539 add_reg_note (insn
, REG_BR_PRED
,
540 gen_rtx_CONCAT (VOIDmode
,
541 GEN_INT ((int) predictor
),
542 GEN_INT ((int) probability
)));
545 /* Predict insn by given predictor. */
548 predict_insn_def (rtx_insn
*insn
, enum br_predictor predictor
,
549 enum prediction taken
)
551 int probability
= predictor_info
[(int) predictor
].hitrate
;
554 probability
= REG_BR_PROB_BASE
- probability
;
556 predict_insn (insn
, predictor
, probability
);
559 /* Predict edge E with given probability if possible. */
562 rtl_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
565 last_insn
= BB_END (e
->src
);
567 /* We can store the branch prediction information only about
568 conditional jumps. */
569 if (!any_condjump_p (last_insn
))
572 /* We always store probability of branching. */
573 if (e
->flags
& EDGE_FALLTHRU
)
574 probability
= REG_BR_PROB_BASE
- probability
;
576 predict_insn (last_insn
, predictor
, probability
);
579 /* Predict edge E with the given PROBABILITY. */
581 gimple_predict_edge (edge e
, enum br_predictor predictor
, int probability
)
583 if (e
->src
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
)
584 && EDGE_COUNT (e
->src
->succs
) > 1
585 && flag_guess_branch_prob
588 struct edge_prediction
*i
= XNEW (struct edge_prediction
);
589 edge_prediction
*&preds
= bb_predictions
->get_or_insert (e
->src
);
593 i
->ep_probability
= probability
;
594 i
->ep_predictor
= predictor
;
599 /* Filter edge predictions PREDS by a function FILTER. DATA are passed
600 to the filter function. */
603 filter_predictions (edge_prediction
**preds
,
604 bool (*filter
) (edge_prediction
*, void *), void *data
)
611 struct edge_prediction
**prediction
= preds
;
612 struct edge_prediction
*next
;
616 if ((*filter
) (*prediction
, data
))
617 prediction
= &((*prediction
)->ep_next
);
620 next
= (*prediction
)->ep_next
;
628 /* Filter function predicate that returns true for a edge predicate P
629 if its edge is equal to DATA. */
632 equal_edge_p (edge_prediction
*p
, void *data
)
634 return p
->ep_edge
== (edge
)data
;
637 /* Remove all predictions on given basic block that are attached
640 remove_predictions_associated_with_edge (edge e
)
645 edge_prediction
**preds
= bb_predictions
->get (e
->src
);
646 filter_predictions (preds
, equal_edge_p
, e
);
649 /* Clears the list of predictions stored for BB. */
652 clear_bb_predictions (basic_block bb
)
654 edge_prediction
**preds
= bb_predictions
->get (bb
);
655 struct edge_prediction
*pred
, *next
;
660 for (pred
= *preds
; pred
; pred
= next
)
662 next
= pred
->ep_next
;
668 /* Return true when we can store prediction on insn INSN.
669 At the moment we represent predictions only on conditional
670 jumps, not at computed jump or other complicated cases. */
672 can_predict_insn_p (const rtx_insn
*insn
)
674 return (JUMP_P (insn
)
675 && any_condjump_p (insn
)
676 && EDGE_COUNT (BLOCK_FOR_INSN (insn
)->succs
) >= 2);
679 /* Predict edge E by given predictor if possible. */
682 predict_edge_def (edge e
, enum br_predictor predictor
,
683 enum prediction taken
)
685 int probability
= predictor_info
[(int) predictor
].hitrate
;
688 probability
= REG_BR_PROB_BASE
- probability
;
690 predict_edge (e
, predictor
, probability
);
693 /* Invert all branch predictions or probability notes in the INSN. This needs
694 to be done each time we invert the condition used by the jump. */
697 invert_br_probabilities (rtx insn
)
701 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
702 if (REG_NOTE_KIND (note
) == REG_BR_PROB
)
703 XINT (note
, 0) = profile_probability::from_reg_br_prob_note
704 (XINT (note
, 0)).invert ().to_reg_br_prob_note ();
705 else if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
706 XEXP (XEXP (note
, 0), 1)
707 = GEN_INT (REG_BR_PROB_BASE
- INTVAL (XEXP (XEXP (note
, 0), 1)));
710 /* Dump information about the branch prediction to the output file. */
713 dump_prediction (FILE *file
, enum br_predictor predictor
, int probability
,
714 basic_block bb
, enum predictor_reason reason
= REASON_NONE
,
724 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
725 if (! (e
->flags
& EDGE_FALLTHRU
))
728 char edge_info_str
[128];
730 sprintf (edge_info_str
, " of edge %d->%d", ep_edge
->src
->index
,
731 ep_edge
->dest
->index
);
733 edge_info_str
[0] = '\0';
735 fprintf (file
, " %s heuristics%s%s: %.1f%%",
736 predictor_info
[predictor
].name
,
737 edge_info_str
, reason_messages
[reason
],
738 probability
* 100.0 / REG_BR_PROB_BASE
);
740 if (bb
->count
.initialized_p ())
742 fprintf (file
, " exec ");
743 bb
->count
.dump (file
);
746 fprintf (file
, " hit ");
747 e
->count
.dump (file
);
748 fprintf (file
, " (%.1f%%)", e
->count
.to_gcov_type() * 100.0
749 / bb
->count
.to_gcov_type ());
753 fprintf (file
, "\n");
756 /* Return true if STMT is known to be unlikely executed. */
759 unlikely_executed_stmt_p (gimple
*stmt
)
761 if (!is_gimple_call (stmt
))
763 /* NORETURN attribute alone is not strong enough: exit() may be quite
764 likely executed once during program run. */
765 if (gimple_call_fntype (stmt
)
766 && lookup_attribute ("cold",
767 TYPE_ATTRIBUTES (gimple_call_fntype (stmt
)))
768 && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
)))
770 tree decl
= gimple_call_fndecl (stmt
);
773 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl
))
774 && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
)))
777 cgraph_node
*n
= cgraph_node::get (decl
);
782 n
= n
->ultimate_alias_target (&avail
);
783 if (avail
< AVAIL_AVAILABLE
)
786 || n
->decl
== current_function_decl
)
788 return n
->frequency
== NODE_FREQUENCY_UNLIKELY_EXECUTED
;
791 /* Return true if BB is unlikely executed. */
794 unlikely_executed_bb_p (basic_block bb
)
796 if (bb
->count
== profile_count::zero ())
798 if (bb
== ENTRY_BLOCK_PTR_FOR_FN (cfun
) || bb
== EXIT_BLOCK_PTR_FOR_FN (cfun
))
800 for (gimple_stmt_iterator gsi
= gsi_start_bb (bb
);
801 !gsi_end_p (gsi
); gsi_next (&gsi
))
803 if (unlikely_executed_stmt_p (gsi_stmt (gsi
)))
805 if (stmt_can_terminate_bb_p (gsi_stmt (gsi
)))
811 /* We can not predict the probabilities of outgoing edges of bb. Set them
812 evenly and hope for the best. If UNLIKELY_EDGES is not null, distribute
813 even probability for all edges not mentioned in the set. These edges
814 are given PROB_VERY_UNLIKELY probability. */
817 set_even_probabilities (basic_block bb
,
818 hash_set
<edge
> *unlikely_edges
= NULL
)
820 unsigned nedges
= 0, unlikely_count
= 0;
823 profile_probability all
= profile_probability::always ();
825 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
826 if (e
->probability
.initialized_p ())
827 all
-= e
->probability
;
828 else if (!unlikely_executed_edge_p (e
))
831 if (unlikely_edges
!= NULL
&& unlikely_edges
->contains (e
))
833 all
-= profile_probability::very_unlikely ();
838 /* Make the distribution even if all edges are unlikely. */
839 if (unlikely_count
== nedges
)
841 unlikely_edges
= NULL
;
845 unsigned c
= nedges
- unlikely_count
;
847 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
848 if (e
->probability
.initialized_p ())
850 else if (!unlikely_executed_edge_p (e
))
852 if (unlikely_edges
!= NULL
&& unlikely_edges
->contains (e
))
853 e
->probability
= profile_probability::very_unlikely ();
855 e
->probability
= all
.apply_scale (1, c
).guessed ();
858 e
->probability
= profile_probability::never ();
861 /* Add REG_BR_PROB note to JUMP with PROB. */
864 add_reg_br_prob_note (rtx_insn
*jump
, profile_probability prob
)
866 gcc_checking_assert (JUMP_P (jump
) && !find_reg_note (jump
, REG_BR_PROB
, 0));
867 add_int_reg_note (jump
, REG_BR_PROB
, prob
.to_reg_br_prob_note ());
870 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
871 note if not already present. Remove now useless REG_BR_PRED notes. */
874 combine_predictions_for_insn (rtx_insn
*insn
, basic_block bb
)
879 int best_probability
= PROB_EVEN
;
880 enum br_predictor best_predictor
= END_PREDICTORS
;
881 int combined_probability
= REG_BR_PROB_BASE
/ 2;
883 bool first_match
= false;
886 if (!can_predict_insn_p (insn
))
888 set_even_probabilities (bb
);
892 prob_note
= find_reg_note (insn
, REG_BR_PROB
, 0);
893 pnote
= ®_NOTES (insn
);
895 fprintf (dump_file
, "Predictions for insn %i bb %i\n", INSN_UID (insn
),
898 /* We implement "first match" heuristics and use probability guessed
899 by predictor with smallest index. */
900 for (note
= REG_NOTES (insn
); note
; note
= XEXP (note
, 1))
901 if (REG_NOTE_KIND (note
) == REG_BR_PRED
)
903 enum br_predictor predictor
= ((enum br_predictor
)
904 INTVAL (XEXP (XEXP (note
, 0), 0)));
905 int probability
= INTVAL (XEXP (XEXP (note
, 0), 1));
908 if (best_predictor
> predictor
909 && predictor_info
[predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
910 best_probability
= probability
, best_predictor
= predictor
;
912 d
= (combined_probability
* probability
913 + (REG_BR_PROB_BASE
- combined_probability
)
914 * (REG_BR_PROB_BASE
- probability
));
916 /* Use FP math to avoid overflows of 32bit integers. */
918 /* If one probability is 0% and one 100%, avoid division by zero. */
919 combined_probability
= REG_BR_PROB_BASE
/ 2;
921 combined_probability
= (((double) combined_probability
) * probability
922 * REG_BR_PROB_BASE
/ d
+ 0.5);
925 /* Decide which heuristic to use. In case we didn't match anything,
926 use no_prediction heuristic, in case we did match, use either
927 first match or Dempster-Shaffer theory depending on the flags. */
929 if (best_predictor
!= END_PREDICTORS
)
933 dump_prediction (dump_file
, PRED_NO_PREDICTION
,
934 combined_probability
, bb
);
938 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
,
939 bb
, !first_match
? REASON_NONE
: REASON_IGNORED
);
941 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
,
942 bb
, first_match
? REASON_NONE
: REASON_IGNORED
);
946 combined_probability
= best_probability
;
947 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
);
951 if (REG_NOTE_KIND (*pnote
) == REG_BR_PRED
)
953 enum br_predictor predictor
= ((enum br_predictor
)
954 INTVAL (XEXP (XEXP (*pnote
, 0), 0)));
955 int probability
= INTVAL (XEXP (XEXP (*pnote
, 0), 1));
957 dump_prediction (dump_file
, predictor
, probability
, bb
,
958 (!first_match
|| best_predictor
== predictor
)
959 ? REASON_NONE
: REASON_IGNORED
);
960 *pnote
= XEXP (*pnote
, 1);
963 pnote
= &XEXP (*pnote
, 1);
968 profile_probability p
969 = profile_probability::from_reg_br_prob_base (combined_probability
);
970 add_reg_br_prob_note (insn
, p
);
972 /* Save the prediction into CFG in case we are seeing non-degenerated
974 if (!single_succ_p (bb
))
976 BRANCH_EDGE (bb
)->probability
= p
;
977 FALLTHRU_EDGE (bb
)->probability
978 = BRANCH_EDGE (bb
)->probability
.invert ();
981 else if (!single_succ_p (bb
))
983 profile_probability prob
= profile_probability::from_reg_br_prob_note
984 (XINT (prob_note
, 0));
986 BRANCH_EDGE (bb
)->probability
= prob
;
987 FALLTHRU_EDGE (bb
)->probability
= prob
.invert ();
990 single_succ_edge (bb
)->probability
= profile_probability::always ();
993 /* Edge prediction hash traits. */
995 struct predictor_hash
: pointer_hash
<edge_prediction
>
998 static inline hashval_t
hash (const edge_prediction
*);
999 static inline bool equal (const edge_prediction
*, const edge_prediction
*);
1002 /* Calculate hash value of an edge prediction P based on predictor and
1003 normalized probability. */
1006 predictor_hash::hash (const edge_prediction
*p
)
1008 inchash::hash hstate
;
1009 hstate
.add_int (p
->ep_predictor
);
1011 int prob
= p
->ep_probability
;
1012 if (prob
> REG_BR_PROB_BASE
/ 2)
1013 prob
= REG_BR_PROB_BASE
- prob
;
1015 hstate
.add_int (prob
);
1017 return hstate
.end ();
1020 /* Return true whether edge predictions P1 and P2 use the same predictor and
1021 have equal (or opposed probability). */
1024 predictor_hash::equal (const edge_prediction
*p1
, const edge_prediction
*p2
)
1026 return (p1
->ep_predictor
== p2
->ep_predictor
1027 && (p1
->ep_probability
== p2
->ep_probability
1028 || p1
->ep_probability
== REG_BR_PROB_BASE
- p2
->ep_probability
));
1031 struct predictor_hash_traits
: predictor_hash
,
1032 typed_noop_remove
<edge_prediction
*> {};
1034 /* Return true if edge prediction P is not in DATA hash set. */
1037 not_removed_prediction_p (edge_prediction
*p
, void *data
)
1039 hash_set
<edge_prediction
*> *remove
= (hash_set
<edge_prediction
*> *) data
;
1040 return !remove
->contains (p
);
1043 /* Prune predictions for a basic block BB. Currently we do following
1046 1) remove duplicate prediction that is guessed with the same probability
1047 (different than 1/2) to both edge
1048 2) remove duplicates for a prediction that belongs with the same probability
1054 prune_predictions_for_bb (basic_block bb
)
1056 edge_prediction
**preds
= bb_predictions
->get (bb
);
1060 hash_table
<predictor_hash_traits
> s (13);
1061 hash_set
<edge_prediction
*> remove
;
1063 /* Step 1: identify predictors that should be removed. */
1064 for (edge_prediction
*pred
= *preds
; pred
; pred
= pred
->ep_next
)
1066 edge_prediction
*existing
= s
.find (pred
);
1069 if (pred
->ep_edge
== existing
->ep_edge
1070 && pred
->ep_probability
== existing
->ep_probability
)
1072 /* Remove a duplicate predictor. */
1073 dump_prediction (dump_file
, pred
->ep_predictor
,
1074 pred
->ep_probability
, bb
,
1075 REASON_SINGLE_EDGE_DUPLICATE
, pred
->ep_edge
);
1079 else if (pred
->ep_edge
!= existing
->ep_edge
1080 && pred
->ep_probability
== existing
->ep_probability
1081 && pred
->ep_probability
!= REG_BR_PROB_BASE
/ 2)
1083 /* Remove both predictors as they predict the same
1085 dump_prediction (dump_file
, existing
->ep_predictor
,
1086 pred
->ep_probability
, bb
,
1087 REASON_EDGE_PAIR_DUPLICATE
,
1089 dump_prediction (dump_file
, pred
->ep_predictor
,
1090 pred
->ep_probability
, bb
,
1091 REASON_EDGE_PAIR_DUPLICATE
,
1094 remove
.add (existing
);
1099 edge_prediction
**slot2
= s
.find_slot (pred
, INSERT
);
1103 /* Step 2: Remove predictors. */
1104 filter_predictions (preds
, not_removed_prediction_p
, &remove
);
1108 /* Combine predictions into single probability and store them into CFG.
1109 Remove now useless prediction entries.
1110 If DRY_RUN is set, only produce dumps and do not modify profile. */
1113 combine_predictions_for_bb (basic_block bb
, bool dry_run
)
1115 int best_probability
= PROB_EVEN
;
1116 enum br_predictor best_predictor
= END_PREDICTORS
;
1117 int combined_probability
= REG_BR_PROB_BASE
/ 2;
1119 bool first_match
= false;
1121 struct edge_prediction
*pred
;
1123 edge e
, first
= NULL
, second
= NULL
;
1126 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1127 if (!unlikely_executed_edge_p (e
))
1130 if (first
&& !second
)
1135 else if (!e
->probability
.initialized_p ())
1136 e
->probability
= profile_probability::never ();
1138 /* When there is no successor or only one choice, prediction is easy.
1140 When we have a basic block with more than 2 successors, the situation
1141 is more complicated as DS theory cannot be used literally.
1142 More precisely, let's assume we predicted edge e1 with probability p1,
1143 thus: m1({b1}) = p1. As we're going to combine more than 2 edges, we
1144 need to find probability of e.g. m1({b2}), which we don't know.
1145 The only approximation is to equally distribute 1-p1 to all edges
1148 According to numbers we've got from SPEC2006 benchark, there's only
1149 one interesting reliable predictor (noreturn call), which can be
1150 handled with a bit easier approach. */
1153 hash_set
<edge
> unlikely_edges (4);
1155 /* Identify all edges that have a probability close to very unlikely.
1156 Doing the approach for very unlikely doesn't worth for doing as
1157 there's no such probability in SPEC2006 benchmark. */
1158 edge_prediction
**preds
= bb_predictions
->get (bb
);
1160 for (pred
= *preds
; pred
; pred
= pred
->ep_next
)
1161 if (pred
->ep_probability
<= PROB_VERY_UNLIKELY
)
1162 unlikely_edges
.add (pred
->ep_edge
);
1165 set_even_probabilities (bb
, &unlikely_edges
);
1166 clear_bb_predictions (bb
);
1169 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
1170 if (unlikely_edges
.elements () == 0)
1172 "%i edges in bb %i predicted to even probabilities\n",
1177 "%i edges in bb %i predicted with some unlikely edges\n",
1179 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
1180 if (!unlikely_executed_edge_p (e
))
1181 dump_prediction (dump_file
, PRED_COMBINED
,
1182 e
->probability
.to_reg_br_prob_base (), bb
, REASON_NONE
, e
);
1189 fprintf (dump_file
, "Predictions for bb %i\n", bb
->index
);
1191 prune_predictions_for_bb (bb
);
1193 edge_prediction
**preds
= bb_predictions
->get (bb
);
1197 /* We implement "first match" heuristics and use probability guessed
1198 by predictor with smallest index. */
1199 for (pred
= *preds
; pred
; pred
= pred
->ep_next
)
1201 enum br_predictor predictor
= pred
->ep_predictor
;
1202 int probability
= pred
->ep_probability
;
1204 if (pred
->ep_edge
!= first
)
1205 probability
= REG_BR_PROB_BASE
- probability
;
1208 /* First match heuristics would be widly confused if we predicted
1210 if (best_predictor
> predictor
1211 && predictor_info
[predictor
].flags
& PRED_FLAG_FIRST_MATCH
)
1213 struct edge_prediction
*pred2
;
1214 int prob
= probability
;
1216 for (pred2
= (struct edge_prediction
*) *preds
;
1217 pred2
; pred2
= pred2
->ep_next
)
1218 if (pred2
!= pred
&& pred2
->ep_predictor
== pred
->ep_predictor
)
1220 int probability2
= pred2
->ep_probability
;
1222 if (pred2
->ep_edge
!= first
)
1223 probability2
= REG_BR_PROB_BASE
- probability2
;
1225 if ((probability
< REG_BR_PROB_BASE
/ 2) !=
1226 (probability2
< REG_BR_PROB_BASE
/ 2))
1229 /* If the same predictor later gave better result, go for it! */
1230 if ((probability
>= REG_BR_PROB_BASE
/ 2 && (probability2
> probability
))
1231 || (probability
<= REG_BR_PROB_BASE
/ 2 && (probability2
< probability
)))
1232 prob
= probability2
;
1235 best_probability
= prob
, best_predictor
= predictor
;
1238 d
= (combined_probability
* probability
1239 + (REG_BR_PROB_BASE
- combined_probability
)
1240 * (REG_BR_PROB_BASE
- probability
));
1242 /* Use FP math to avoid overflows of 32bit integers. */
1244 /* If one probability is 0% and one 100%, avoid division by zero. */
1245 combined_probability
= REG_BR_PROB_BASE
/ 2;
1247 combined_probability
= (((double) combined_probability
)
1249 * REG_BR_PROB_BASE
/ d
+ 0.5);
1253 /* Decide which heuristic to use. In case we didn't match anything,
1254 use no_prediction heuristic, in case we did match, use either
1255 first match or Dempster-Shaffer theory depending on the flags. */
1257 if (best_predictor
!= END_PREDICTORS
)
1261 dump_prediction (dump_file
, PRED_NO_PREDICTION
, combined_probability
, bb
);
1265 dump_prediction (dump_file
, PRED_DS_THEORY
, combined_probability
, bb
,
1266 !first_match
? REASON_NONE
: REASON_IGNORED
);
1268 dump_prediction (dump_file
, PRED_FIRST_MATCH
, best_probability
, bb
,
1269 first_match
? REASON_NONE
: REASON_IGNORED
);
1273 combined_probability
= best_probability
;
1274 dump_prediction (dump_file
, PRED_COMBINED
, combined_probability
, bb
);
1278 for (pred
= (struct edge_prediction
*) *preds
; pred
; pred
= pred
->ep_next
)
1280 enum br_predictor predictor
= pred
->ep_predictor
;
1281 int probability
= pred
->ep_probability
;
1283 dump_prediction (dump_file
, predictor
, probability
, bb
,
1284 (!first_match
|| best_predictor
== predictor
)
1285 ? REASON_NONE
: REASON_IGNORED
, pred
->ep_edge
);
1288 clear_bb_predictions (bb
);
1290 if (!bb
->count
.initialized_p () && !dry_run
)
1293 = profile_probability::from_reg_br_prob_base (combined_probability
);
1294 second
->probability
= first
->probability
.invert ();
1298 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
1299 Return the SSA_NAME if the condition satisfies, NULL otherwise.
1301 T1 and T2 should be one of the following cases:
1302 1. T1 is SSA_NAME, T2 is NULL
1303 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
1304 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
1307 strips_small_constant (tree t1
, tree t2
)
1314 else if (TREE_CODE (t1
) == SSA_NAME
)
1316 else if (tree_fits_shwi_p (t1
))
1317 value
= tree_to_shwi (t1
);
1323 else if (tree_fits_shwi_p (t2
))
1324 value
= tree_to_shwi (t2
);
1325 else if (TREE_CODE (t2
) == SSA_NAME
)
1333 if (value
<= 4 && value
>= -4)
1339 /* Return the SSA_NAME in T or T's operands.
1340 Return NULL if SSA_NAME cannot be found. */
1343 get_base_value (tree t
)
1345 if (TREE_CODE (t
) == SSA_NAME
)
1348 if (!BINARY_CLASS_P (t
))
1351 switch (TREE_OPERAND_LENGTH (t
))
1354 return strips_small_constant (TREE_OPERAND (t
, 0), NULL
);
1356 return strips_small_constant (TREE_OPERAND (t
, 0),
1357 TREE_OPERAND (t
, 1));
1363 /* Check the compare STMT in LOOP. If it compares an induction
1364 variable to a loop invariant, return true, and save
1365 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1366 Otherwise return false and set LOOP_INVAIANT to NULL. */
1369 is_comparison_with_loop_invariant_p (gcond
*stmt
, struct loop
*loop
,
1370 tree
*loop_invariant
,
1371 enum tree_code
*compare_code
,
1375 tree op0
, op1
, bound
, base
;
1377 enum tree_code code
;
1380 code
= gimple_cond_code (stmt
);
1381 *loop_invariant
= NULL
;
1397 op0
= gimple_cond_lhs (stmt
);
1398 op1
= gimple_cond_rhs (stmt
);
1400 if ((TREE_CODE (op0
) != SSA_NAME
&& TREE_CODE (op0
) != INTEGER_CST
)
1401 || (TREE_CODE (op1
) != SSA_NAME
&& TREE_CODE (op1
) != INTEGER_CST
))
1403 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op0
, &iv0
, true))
1405 if (!simple_iv (loop
, loop_containing_stmt (stmt
), op1
, &iv1
, true))
1407 if (TREE_CODE (iv0
.step
) != INTEGER_CST
1408 || TREE_CODE (iv1
.step
) != INTEGER_CST
)
1410 if ((integer_zerop (iv0
.step
) && integer_zerop (iv1
.step
))
1411 || (!integer_zerop (iv0
.step
) && !integer_zerop (iv1
.step
)))
1414 if (integer_zerop (iv0
.step
))
1416 if (code
!= NE_EXPR
&& code
!= EQ_EXPR
)
1417 code
= invert_tree_comparison (code
, false);
1420 if (tree_fits_shwi_p (iv1
.step
))
1429 if (tree_fits_shwi_p (iv0
.step
))
1435 if (TREE_CODE (bound
) != INTEGER_CST
)
1436 bound
= get_base_value (bound
);
1439 if (TREE_CODE (base
) != INTEGER_CST
)
1440 base
= get_base_value (base
);
1444 *loop_invariant
= bound
;
1445 *compare_code
= code
;
1447 *loop_iv_base
= base
;
1451 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1454 expr_coherent_p (tree t1
, tree t2
)
1457 tree ssa_name_1
= NULL
;
1458 tree ssa_name_2
= NULL
;
1460 gcc_assert (TREE_CODE (t1
) == SSA_NAME
|| TREE_CODE (t1
) == INTEGER_CST
);
1461 gcc_assert (TREE_CODE (t2
) == SSA_NAME
|| TREE_CODE (t2
) == INTEGER_CST
);
1466 if (TREE_CODE (t1
) == INTEGER_CST
&& TREE_CODE (t2
) == INTEGER_CST
)
1468 if (TREE_CODE (t1
) == INTEGER_CST
|| TREE_CODE (t2
) == INTEGER_CST
)
1471 /* Check to see if t1 is expressed/defined with t2. */
1472 stmt
= SSA_NAME_DEF_STMT (t1
);
1473 gcc_assert (stmt
!= NULL
);
1474 if (is_gimple_assign (stmt
))
1476 ssa_name_1
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1477 if (ssa_name_1
&& ssa_name_1
== t2
)
1481 /* Check to see if t2 is expressed/defined with t1. */
1482 stmt
= SSA_NAME_DEF_STMT (t2
);
1483 gcc_assert (stmt
!= NULL
);
1484 if (is_gimple_assign (stmt
))
1486 ssa_name_2
= SINGLE_SSA_TREE_OPERAND (stmt
, SSA_OP_USE
);
1487 if (ssa_name_2
&& ssa_name_2
== t1
)
1491 /* Compare if t1 and t2's def_stmts are identical. */
1492 if (ssa_name_2
!= NULL
&& ssa_name_1
== ssa_name_2
)
1498 /* Return true if E is predicted by one of loop heuristics. */
1501 predicted_by_loop_heuristics_p (basic_block bb
)
1503 struct edge_prediction
*i
;
1504 edge_prediction
**preds
= bb_predictions
->get (bb
);
1509 for (i
= *preds
; i
; i
= i
->ep_next
)
1510 if (i
->ep_predictor
== PRED_LOOP_ITERATIONS_GUESSED
1511 || i
->ep_predictor
== PRED_LOOP_ITERATIONS_MAX
1512 || i
->ep_predictor
== PRED_LOOP_ITERATIONS
1513 || i
->ep_predictor
== PRED_LOOP_EXIT
1514 || i
->ep_predictor
== PRED_LOOP_EXIT_WITH_RECURSION
1515 || i
->ep_predictor
== PRED_LOOP_EXTRA_EXIT
)
1520 /* Predict branch probability of BB when BB contains a branch that compares
1521 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1522 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1525 for (int i = 0; i < bound; i++) {
1532 In this loop, we will predict the branch inside the loop to be taken. */
1535 predict_iv_comparison (struct loop
*loop
, basic_block bb
,
1536 tree loop_bound_var
,
1537 tree loop_iv_base_var
,
1538 enum tree_code loop_bound_code
,
1539 int loop_bound_step
)
1542 tree compare_var
, compare_base
;
1543 enum tree_code compare_code
;
1544 tree compare_step_var
;
1548 if (predicted_by_loop_heuristics_p (bb
))
1551 stmt
= last_stmt (bb
);
1552 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
1554 if (!is_comparison_with_loop_invariant_p (as_a
<gcond
*> (stmt
),
1561 /* Find the taken edge. */
1562 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
1563 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
1566 /* When comparing an IV to a loop invariant, NE is more likely to be
1567 taken while EQ is more likely to be not-taken. */
1568 if (compare_code
== NE_EXPR
)
1570 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1573 else if (compare_code
== EQ_EXPR
)
1575 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1579 if (!expr_coherent_p (loop_iv_base_var
, compare_base
))
1582 /* If loop bound, base and compare bound are all constants, we can
1583 calculate the probability directly. */
1584 if (tree_fits_shwi_p (loop_bound_var
)
1585 && tree_fits_shwi_p (compare_var
)
1586 && tree_fits_shwi_p (compare_base
))
1589 bool overflow
, overall_overflow
= false;
1590 widest_int compare_count
, tem
;
1592 /* (loop_bound - base) / compare_step */
1593 tem
= wi::sub (wi::to_widest (loop_bound_var
),
1594 wi::to_widest (compare_base
), SIGNED
, &overflow
);
1595 overall_overflow
|= overflow
;
1596 widest_int loop_count
= wi::div_trunc (tem
,
1597 wi::to_widest (compare_step_var
),
1599 overall_overflow
|= overflow
;
1601 if (!wi::neg_p (wi::to_widest (compare_step_var
))
1602 ^ (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1604 /* (loop_bound - compare_bound) / compare_step */
1605 tem
= wi::sub (wi::to_widest (loop_bound_var
),
1606 wi::to_widest (compare_var
), SIGNED
, &overflow
);
1607 overall_overflow
|= overflow
;
1608 compare_count
= wi::div_trunc (tem
, wi::to_widest (compare_step_var
),
1610 overall_overflow
|= overflow
;
1614 /* (compare_bound - base) / compare_step */
1615 tem
= wi::sub (wi::to_widest (compare_var
),
1616 wi::to_widest (compare_base
), SIGNED
, &overflow
);
1617 overall_overflow
|= overflow
;
1618 compare_count
= wi::div_trunc (tem
, wi::to_widest (compare_step_var
),
1620 overall_overflow
|= overflow
;
1622 if (compare_code
== LE_EXPR
|| compare_code
== GE_EXPR
)
1624 if (loop_bound_code
== LE_EXPR
|| loop_bound_code
== GE_EXPR
)
1626 if (wi::neg_p (compare_count
))
1628 if (wi::neg_p (loop_count
))
1630 if (loop_count
== 0)
1632 else if (wi::cmps (compare_count
, loop_count
) == 1)
1633 probability
= REG_BR_PROB_BASE
;
1636 tem
= compare_count
* REG_BR_PROB_BASE
;
1637 tem
= wi::udiv_trunc (tem
, loop_count
);
1638 probability
= tem
.to_uhwi ();
1641 /* FIXME: The branch prediction seems broken. It has only 20% hitrate. */
1642 if (!overall_overflow
)
1643 predict_edge (then_edge
, PRED_LOOP_IV_COMPARE
, probability
);
1648 if (expr_coherent_p (loop_bound_var
, compare_var
))
1650 if ((loop_bound_code
== LT_EXPR
|| loop_bound_code
== LE_EXPR
)
1651 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1652 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1653 else if ((loop_bound_code
== GT_EXPR
|| loop_bound_code
== GE_EXPR
)
1654 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1655 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1656 else if (loop_bound_code
== NE_EXPR
)
1658 /* If the loop backedge condition is "(i != bound)", we do
1659 the comparison based on the step of IV:
1660 * step < 0 : backedge condition is like (i > bound)
1661 * step > 0 : backedge condition is like (i < bound) */
1662 gcc_assert (loop_bound_step
!= 0);
1663 if (loop_bound_step
> 0
1664 && (compare_code
== LT_EXPR
1665 || compare_code
== LE_EXPR
))
1666 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1667 else if (loop_bound_step
< 0
1668 && (compare_code
== GT_EXPR
1669 || compare_code
== GE_EXPR
))
1670 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1672 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1675 /* The branch is predicted not-taken if loop_bound_code is
1676 opposite with compare_code. */
1677 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1679 else if (expr_coherent_p (loop_iv_base_var
, compare_var
))
1682 for (i = s; i < h; i++)
1684 The branch should be predicted taken. */
1685 if (loop_bound_step
> 0
1686 && (compare_code
== GT_EXPR
|| compare_code
== GE_EXPR
))
1687 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1688 else if (loop_bound_step
< 0
1689 && (compare_code
== LT_EXPR
|| compare_code
== LE_EXPR
))
1690 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, TAKEN
);
1692 predict_edge_def (then_edge
, PRED_LOOP_IV_COMPARE_GUESS
, NOT_TAKEN
);
1696 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1697 exits are resulted from short-circuit conditions that will generate an
1700 if (foo() || global > 10)
1703 This will be translated into:
1708 if foo() goto BB6 else goto BB5
1710 if global > 10 goto BB6 else goto BB7
1714 iftmp = (PHI 0(BB5), 1(BB6))
1715 if iftmp == 1 goto BB8 else goto BB3
1717 outside of the loop...
1719 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1720 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1721 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1722 exits to predict them using PRED_LOOP_EXTRA_EXIT. */
1725 predict_extra_loop_exits (edge exit_edge
)
1728 bool check_value_one
;
1729 gimple
*lhs_def_stmt
;
1731 tree cmp_rhs
, cmp_lhs
;
1735 last
= last_stmt (exit_edge
->src
);
1738 cmp_stmt
= dyn_cast
<gcond
*> (last
);
1742 cmp_rhs
= gimple_cond_rhs (cmp_stmt
);
1743 cmp_lhs
= gimple_cond_lhs (cmp_stmt
);
1744 if (!TREE_CONSTANT (cmp_rhs
)
1745 || !(integer_zerop (cmp_rhs
) || integer_onep (cmp_rhs
)))
1747 if (TREE_CODE (cmp_lhs
) != SSA_NAME
)
1750 /* If check_value_one is true, only the phi_args with value '1' will lead
1751 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1753 check_value_one
= (((integer_onep (cmp_rhs
))
1754 ^ (gimple_cond_code (cmp_stmt
) == EQ_EXPR
))
1755 ^ ((exit_edge
->flags
& EDGE_TRUE_VALUE
) != 0));
1757 lhs_def_stmt
= SSA_NAME_DEF_STMT (cmp_lhs
);
1761 phi_stmt
= dyn_cast
<gphi
*> (lhs_def_stmt
);
1765 for (i
= 0; i
< gimple_phi_num_args (phi_stmt
); i
++)
1769 tree val
= gimple_phi_arg_def (phi_stmt
, i
);
1770 edge e
= gimple_phi_arg_edge (phi_stmt
, i
);
1772 if (!TREE_CONSTANT (val
) || !(integer_zerop (val
) || integer_onep (val
)))
1774 if ((check_value_one
^ integer_onep (val
)) == 1)
1776 if (EDGE_COUNT (e
->src
->succs
) != 1)
1778 predict_paths_leading_to_edge (e
, PRED_LOOP_EXTRA_EXIT
, NOT_TAKEN
);
1782 FOR_EACH_EDGE (e1
, ei
, e
->src
->preds
)
1783 predict_paths_leading_to_edge (e1
, PRED_LOOP_EXTRA_EXIT
, NOT_TAKEN
);
1788 /* Predict edge probabilities by exploiting loop structure. */
1791 predict_loops (void)
1795 hash_set
<struct loop
*> with_recursion(10);
1797 FOR_EACH_BB_FN (bb
, cfun
)
1799 gimple_stmt_iterator gsi
;
1802 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
1803 if (is_gimple_call (gsi_stmt (gsi
))
1804 && (decl
= gimple_call_fndecl (gsi_stmt (gsi
))) != NULL
1805 && recursive_call_p (current_function_decl
, decl
))
1807 loop
= bb
->loop_father
;
1808 while (loop
&& !with_recursion
.add (loop
))
1809 loop
= loop_outer (loop
);
1813 /* Try to predict out blocks in a loop that are not part of a
1815 FOR_EACH_LOOP (loop
, LI_FROM_INNERMOST
)
1817 basic_block bb
, *bbs
;
1818 unsigned j
, n_exits
= 0;
1820 struct tree_niter_desc niter_desc
;
1822 struct nb_iter_bound
*nb_iter
;
1823 enum tree_code loop_bound_code
= ERROR_MARK
;
1824 tree loop_bound_step
= NULL
;
1825 tree loop_bound_var
= NULL
;
1826 tree loop_iv_base
= NULL
;
1828 bool recursion
= with_recursion
.contains (loop
);
1830 exits
= get_loop_exit_edges (loop
);
1831 FOR_EACH_VEC_ELT (exits
, j
, ex
)
1832 if (!unlikely_executed_edge_p (ex
) && !(ex
->flags
& EDGE_ABNORMAL_CALL
))
1840 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1841 fprintf (dump_file
, "Predicting loop %i%s with %i exits.\n",
1842 loop
->num
, recursion
? " (with recursion)":"", n_exits
);
1843 if (dump_file
&& (dump_flags
& TDF_DETAILS
)
1844 && max_loop_iterations_int (loop
) >= 0)
1847 "Loop %d iterates at most %i times.\n", loop
->num
,
1848 (int)max_loop_iterations_int (loop
));
1850 if (dump_file
&& (dump_flags
& TDF_DETAILS
)
1851 && likely_max_loop_iterations_int (loop
) >= 0)
1853 fprintf (dump_file
, "Loop %d likely iterates at most %i times.\n",
1854 loop
->num
, (int)likely_max_loop_iterations_int (loop
));
1857 FOR_EACH_VEC_ELT (exits
, j
, ex
)
1860 HOST_WIDE_INT nitercst
;
1861 int max
= PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS
);
1863 enum br_predictor predictor
;
1866 if (unlikely_executed_edge_p (ex
)
1867 || (ex
->flags
& EDGE_ABNORMAL_CALL
))
1869 /* Loop heuristics do not expect exit conditional to be inside
1870 inner loop. We predict from innermost to outermost loop. */
1871 if (predicted_by_loop_heuristics_p (ex
->src
))
1873 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1874 fprintf (dump_file
, "Skipping exit %i->%i because "
1875 "it is already predicted.\n",
1876 ex
->src
->index
, ex
->dest
->index
);
1879 predict_extra_loop_exits (ex
);
1881 if (number_of_iterations_exit (loop
, ex
, &niter_desc
, false, false))
1882 niter
= niter_desc
.niter
;
1883 if (!niter
|| TREE_CODE (niter_desc
.niter
) != INTEGER_CST
)
1884 niter
= loop_niter_by_eval (loop
, ex
);
1885 if (dump_file
&& (dump_flags
& TDF_DETAILS
)
1886 && TREE_CODE (niter
) == INTEGER_CST
)
1888 fprintf (dump_file
, "Exit %i->%i %d iterates ",
1889 ex
->src
->index
, ex
->dest
->index
,
1891 print_generic_expr (dump_file
, niter
, TDF_SLIM
);
1892 fprintf (dump_file
, " times.\n");
1895 if (TREE_CODE (niter
) == INTEGER_CST
)
1897 if (tree_fits_uhwi_p (niter
)
1899 && compare_tree_int (niter
, max
- 1) == -1)
1900 nitercst
= tree_to_uhwi (niter
) + 1;
1903 predictor
= PRED_LOOP_ITERATIONS
;
1905 /* If we have just one exit and we can derive some information about
1906 the number of iterations of the loop from the statements inside
1907 the loop, use it to predict this exit. */
1908 else if (n_exits
== 1
1909 && estimated_stmt_executions (loop
, &nit
))
1911 if (wi::gtu_p (nit
, max
))
1914 nitercst
= nit
.to_shwi ();
1915 predictor
= PRED_LOOP_ITERATIONS_GUESSED
;
1917 /* If we have likely upper bound, trust it for very small iteration
1918 counts. Such loops would otherwise get mispredicted by standard
1919 LOOP_EXIT heuristics. */
1920 else if (n_exits
== 1
1921 && likely_max_stmt_executions (loop
, &nit
)
1923 RDIV (REG_BR_PROB_BASE
,
1927 ? PRED_LOOP_EXIT_WITH_RECURSION
1928 : PRED_LOOP_EXIT
].hitrate
)))
1930 nitercst
= nit
.to_shwi ();
1931 predictor
= PRED_LOOP_ITERATIONS_MAX
;
1935 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1936 fprintf (dump_file
, "Nothing known about exit %i->%i.\n",
1937 ex
->src
->index
, ex
->dest
->index
);
1941 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1942 fprintf (dump_file
, "Recording prediction to %i iterations by %s.\n",
1943 (int)nitercst
, predictor_info
[predictor
].name
);
1944 /* If the prediction for number of iterations is zero, do not
1945 predict the exit edges. */
1949 probability
= RDIV (REG_BR_PROB_BASE
, nitercst
);
1950 predict_edge (ex
, predictor
, probability
);
1954 /* Find information about loop bound variables. */
1955 for (nb_iter
= loop
->bounds
; nb_iter
;
1956 nb_iter
= nb_iter
->next
)
1958 && gimple_code (nb_iter
->stmt
) == GIMPLE_COND
)
1960 stmt
= as_a
<gcond
*> (nb_iter
->stmt
);
1963 if (!stmt
&& last_stmt (loop
->header
)
1964 && gimple_code (last_stmt (loop
->header
)) == GIMPLE_COND
)
1965 stmt
= as_a
<gcond
*> (last_stmt (loop
->header
));
1967 is_comparison_with_loop_invariant_p (stmt
, loop
,
1973 bbs
= get_loop_body (loop
);
1975 for (j
= 0; j
< loop
->num_nodes
; j
++)
1982 /* Bypass loop heuristics on continue statement. These
1983 statements construct loops via "non-loop" constructs
1984 in the source language and are better to be handled
1986 if (predicted_by_p (bb
, PRED_CONTINUE
))
1988 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
1989 fprintf (dump_file
, "BB %i predicted by continue.\n",
1994 /* If we already used more reliable loop exit predictors, do not
1995 bother with PRED_LOOP_EXIT. */
1996 if (!predicted_by_loop_heuristics_p (bb
))
1998 /* For loop with many exits we don't want to predict all exits
1999 with the pretty large probability, because if all exits are
2000 considered in row, the loop would be predicted to iterate
2001 almost never. The code to divide probability by number of
2002 exits is very rough. It should compute the number of exits
2003 taken in each patch through function (not the overall number
2004 of exits that might be a lot higher for loops with wide switch
2005 statements in them) and compute n-th square root.
2007 We limit the minimal probability by 2% to avoid
2008 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
2009 as this was causing regression in perl benchmark containing such
2012 int probability
= ((REG_BR_PROB_BASE
2015 ? PRED_LOOP_EXIT_WITH_RECURSION
2016 : PRED_LOOP_EXIT
].hitrate
)
2018 if (probability
< HITRATE (2))
2019 probability
= HITRATE (2);
2020 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2021 if (e
->dest
->index
< NUM_FIXED_BLOCKS
2022 || !flow_bb_inside_loop_p (loop
, e
->dest
))
2024 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
2026 "Predicting exit %i->%i with prob %i.\n",
2027 e
->src
->index
, e
->dest
->index
, probability
);
2029 recursion
? PRED_LOOP_EXIT_WITH_RECURSION
2030 : PRED_LOOP_EXIT
, probability
);
2034 predict_iv_comparison (loop
, bb
, loop_bound_var
, loop_iv_base
,
2036 tree_to_shwi (loop_bound_step
));
2039 /* In the following code
2044 guess that cond is unlikely. */
2045 if (loop_outer (loop
)->num
)
2047 basic_block bb
= NULL
;
2048 edge preheader_edge
= loop_preheader_edge (loop
);
2050 if (single_pred_p (preheader_edge
->src
)
2051 && single_succ_p (preheader_edge
->src
))
2052 preheader_edge
= single_pred_edge (preheader_edge
->src
);
2054 gimple
*stmt
= last_stmt (preheader_edge
->src
);
2055 /* Pattern match fortran loop preheader:
2056 _16 = BUILTIN_EXPECT (_15, 1, PRED_FORTRAN_LOOP_PREHEADER);
2057 _17 = (logical(kind=4)) _16;
2063 Loop guard branch prediction says nothing about duplicated loop
2064 headers produced by fortran frontend and in this case we want
2065 to predict paths leading to this preheader. */
2068 && gimple_code (stmt
) == GIMPLE_COND
2069 && gimple_cond_code (stmt
) == NE_EXPR
2070 && TREE_CODE (gimple_cond_lhs (stmt
)) == SSA_NAME
2071 && integer_zerop (gimple_cond_rhs (stmt
)))
2073 gimple
*call_stmt
= SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt
));
2074 if (gimple_code (call_stmt
) == GIMPLE_ASSIGN
2075 && gimple_expr_code (call_stmt
) == NOP_EXPR
2076 && TREE_CODE (gimple_assign_rhs1 (call_stmt
)) == SSA_NAME
)
2077 call_stmt
= SSA_NAME_DEF_STMT (gimple_assign_rhs1 (call_stmt
));
2078 if (gimple_call_internal_p (call_stmt
, IFN_BUILTIN_EXPECT
)
2079 && TREE_CODE (gimple_call_arg (call_stmt
, 2)) == INTEGER_CST
2080 && tree_fits_uhwi_p (gimple_call_arg (call_stmt
, 2))
2081 && tree_to_uhwi (gimple_call_arg (call_stmt
, 2))
2082 == PRED_FORTRAN_LOOP_PREHEADER
)
2083 bb
= preheader_edge
->src
;
2087 if (!dominated_by_p (CDI_DOMINATORS
,
2088 loop_outer (loop
)->latch
, loop
->header
))
2089 predict_paths_leading_to_edge (loop_preheader_edge (loop
),
2091 ? PRED_LOOP_GUARD_WITH_RECURSION
2098 if (!dominated_by_p (CDI_DOMINATORS
,
2099 loop_outer (loop
)->latch
, bb
))
2100 predict_paths_leading_to (bb
,
2102 ? PRED_LOOP_GUARD_WITH_RECURSION
2109 /* Free basic blocks from get_loop_body. */
2114 /* Attempt to predict probabilities of BB outgoing edges using local
2117 bb_estimate_probability_locally (basic_block bb
)
2119 rtx_insn
*last_insn
= BB_END (bb
);
2122 if (! can_predict_insn_p (last_insn
))
2124 cond
= get_condition (last_insn
, NULL
, false, false);
2128 /* Try "pointer heuristic."
2129 A comparison ptr == 0 is predicted as false.
2130 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2131 if (COMPARISON_P (cond
)
2132 && ((REG_P (XEXP (cond
, 0)) && REG_POINTER (XEXP (cond
, 0)))
2133 || (REG_P (XEXP (cond
, 1)) && REG_POINTER (XEXP (cond
, 1)))))
2135 if (GET_CODE (cond
) == EQ
)
2136 predict_insn_def (last_insn
, PRED_POINTER
, NOT_TAKEN
);
2137 else if (GET_CODE (cond
) == NE
)
2138 predict_insn_def (last_insn
, PRED_POINTER
, TAKEN
);
2142 /* Try "opcode heuristic."
2143 EQ tests are usually false and NE tests are usually true. Also,
2144 most quantities are positive, so we can make the appropriate guesses
2145 about signed comparisons against zero. */
2146 switch (GET_CODE (cond
))
2149 /* Unconditional branch. */
2150 predict_insn_def (last_insn
, PRED_UNCONDITIONAL
,
2151 cond
== const0_rtx
? NOT_TAKEN
: TAKEN
);
2156 /* Floating point comparisons appears to behave in a very
2157 unpredictable way because of special role of = tests in
2159 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
2161 /* Comparisons with 0 are often used for booleans and there is
2162 nothing useful to predict about them. */
2163 else if (XEXP (cond
, 1) == const0_rtx
2164 || XEXP (cond
, 0) == const0_rtx
)
2167 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, NOT_TAKEN
);
2172 /* Floating point comparisons appears to behave in a very
2173 unpredictable way because of special role of = tests in
2175 if (FLOAT_MODE_P (GET_MODE (XEXP (cond
, 0))))
2177 /* Comparisons with 0 are often used for booleans and there is
2178 nothing useful to predict about them. */
2179 else if (XEXP (cond
, 1) == const0_rtx
2180 || XEXP (cond
, 0) == const0_rtx
)
2183 predict_insn_def (last_insn
, PRED_OPCODE_NONEQUAL
, TAKEN
);
2187 predict_insn_def (last_insn
, PRED_FPOPCODE
, TAKEN
);
2191 predict_insn_def (last_insn
, PRED_FPOPCODE
, NOT_TAKEN
);
2196 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
2197 || XEXP (cond
, 1) == constm1_rtx
)
2198 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, NOT_TAKEN
);
2203 if (XEXP (cond
, 1) == const0_rtx
|| XEXP (cond
, 1) == const1_rtx
2204 || XEXP (cond
, 1) == constm1_rtx
)
2205 predict_insn_def (last_insn
, PRED_OPCODE_POSITIVE
, TAKEN
);
2213 /* Set edge->probability for each successor edge of BB. */
2215 guess_outgoing_edge_probabilities (basic_block bb
)
2217 bb_estimate_probability_locally (bb
);
2218 combine_predictions_for_insn (BB_END (bb
), bb
);
2221 static tree
expr_expected_value (tree
, bitmap
, enum br_predictor
*predictor
);
2223 /* Helper function for expr_expected_value. */
2226 expr_expected_value_1 (tree type
, tree op0
, enum tree_code code
,
2227 tree op1
, bitmap visited
, enum br_predictor
*predictor
)
2232 *predictor
= PRED_UNCONDITIONAL
;
2234 if (get_gimple_rhs_class (code
) == GIMPLE_SINGLE_RHS
)
2236 if (TREE_CONSTANT (op0
))
2239 if (code
== IMAGPART_EXPR
)
2241 if (TREE_CODE (TREE_OPERAND (op0
, 0)) == SSA_NAME
)
2243 def
= SSA_NAME_DEF_STMT (TREE_OPERAND (op0
, 0));
2244 if (is_gimple_call (def
)
2245 && gimple_call_internal_p (def
)
2246 && (gimple_call_internal_fn (def
)
2247 == IFN_ATOMIC_COMPARE_EXCHANGE
))
2249 /* Assume that any given atomic operation has low contention,
2250 and thus the compare-and-swap operation succeeds. */
2252 *predictor
= PRED_COMPARE_AND_SWAP
;
2253 return build_one_cst (TREE_TYPE (op0
));
2258 if (code
!= SSA_NAME
)
2261 def
= SSA_NAME_DEF_STMT (op0
);
2263 /* If we were already here, break the infinite cycle. */
2264 if (!bitmap_set_bit (visited
, SSA_NAME_VERSION (op0
)))
2267 if (gimple_code (def
) == GIMPLE_PHI
)
2269 /* All the arguments of the PHI node must have the same constant
2271 int i
, n
= gimple_phi_num_args (def
);
2272 tree val
= NULL
, new_val
;
2274 for (i
= 0; i
< n
; i
++)
2276 tree arg
= PHI_ARG_DEF (def
, i
);
2277 enum br_predictor predictor2
;
2279 /* If this PHI has itself as an argument, we cannot
2280 determine the string length of this argument. However,
2281 if we can find an expected constant value for the other
2282 PHI args then we can still be sure that this is
2283 likely a constant. So be optimistic and just
2284 continue with the next argument. */
2285 if (arg
== PHI_RESULT (def
))
2288 new_val
= expr_expected_value (arg
, visited
, &predictor2
);
2290 /* It is difficult to combine value predictors. Simply assume
2291 that later predictor is weaker and take its prediction. */
2292 if (predictor
&& *predictor
< predictor2
)
2293 *predictor
= predictor2
;
2298 else if (!operand_equal_p (val
, new_val
, false))
2303 if (is_gimple_assign (def
))
2305 if (gimple_assign_lhs (def
) != op0
)
2308 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def
)),
2309 gimple_assign_rhs1 (def
),
2310 gimple_assign_rhs_code (def
),
2311 gimple_assign_rhs2 (def
),
2312 visited
, predictor
);
2315 if (is_gimple_call (def
))
2317 tree decl
= gimple_call_fndecl (def
);
2320 if (gimple_call_internal_p (def
)
2321 && gimple_call_internal_fn (def
) == IFN_BUILTIN_EXPECT
)
2323 gcc_assert (gimple_call_num_args (def
) == 3);
2324 tree val
= gimple_call_arg (def
, 0);
2325 if (TREE_CONSTANT (val
))
2329 tree val2
= gimple_call_arg (def
, 2);
2330 gcc_assert (TREE_CODE (val2
) == INTEGER_CST
2331 && tree_fits_uhwi_p (val2
)
2332 && tree_to_uhwi (val2
) < END_PREDICTORS
);
2333 *predictor
= (enum br_predictor
) tree_to_uhwi (val2
);
2335 return gimple_call_arg (def
, 1);
2339 if (DECL_BUILT_IN_CLASS (decl
) == BUILT_IN_NORMAL
)
2340 switch (DECL_FUNCTION_CODE (decl
))
2342 case BUILT_IN_EXPECT
:
2345 if (gimple_call_num_args (def
) != 2)
2347 val
= gimple_call_arg (def
, 0);
2348 if (TREE_CONSTANT (val
))
2351 *predictor
= PRED_BUILTIN_EXPECT
;
2352 return gimple_call_arg (def
, 1);
2355 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
:
2356 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1
:
2357 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2
:
2358 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4
:
2359 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8
:
2360 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16
:
2361 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE
:
2362 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N
:
2363 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1
:
2364 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2
:
2365 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4
:
2366 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8
:
2367 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16
:
2368 /* Assume that any given atomic operation has low contention,
2369 and thus the compare-and-swap operation succeeds. */
2371 *predictor
= PRED_COMPARE_AND_SWAP
;
2372 return boolean_true_node
;
2381 if (get_gimple_rhs_class (code
) == GIMPLE_BINARY_RHS
)
2384 enum br_predictor predictor2
;
2385 op0
= expr_expected_value (op0
, visited
, predictor
);
2388 op1
= expr_expected_value (op1
, visited
, &predictor2
);
2389 if (predictor
&& *predictor
< predictor2
)
2390 *predictor
= predictor2
;
2393 res
= fold_build2 (code
, type
, op0
, op1
);
2394 if (TREE_CONSTANT (res
))
2398 if (get_gimple_rhs_class (code
) == GIMPLE_UNARY_RHS
)
2401 op0
= expr_expected_value (op0
, visited
, predictor
);
2404 res
= fold_build1 (code
, type
, op0
);
2405 if (TREE_CONSTANT (res
))
2412 /* Return constant EXPR will likely have at execution time, NULL if unknown.
2413 The function is used by builtin_expect branch predictor so the evidence
2414 must come from this construct and additional possible constant folding.
2416 We may want to implement more involved value guess (such as value range
2417 propagation based prediction), but such tricks shall go to new
2421 expr_expected_value (tree expr
, bitmap visited
,
2422 enum br_predictor
*predictor
)
2424 enum tree_code code
;
2427 if (TREE_CONSTANT (expr
))
2430 *predictor
= PRED_UNCONDITIONAL
;
2434 extract_ops_from_tree (expr
, &code
, &op0
, &op1
);
2435 return expr_expected_value_1 (TREE_TYPE (expr
),
2436 op0
, code
, op1
, visited
, predictor
);
2439 /* Predict using opcode of the last statement in basic block. */
2441 tree_predict_by_opcode (basic_block bb
)
2443 gimple
*stmt
= last_stmt (bb
);
2450 enum br_predictor predictor
;
2452 if (!stmt
|| gimple_code (stmt
) != GIMPLE_COND
)
2454 FOR_EACH_EDGE (then_edge
, ei
, bb
->succs
)
2455 if (then_edge
->flags
& EDGE_TRUE_VALUE
)
2457 op0
= gimple_cond_lhs (stmt
);
2458 op1
= gimple_cond_rhs (stmt
);
2459 cmp
= gimple_cond_code (stmt
);
2460 type
= TREE_TYPE (op0
);
2461 val
= expr_expected_value_1 (boolean_type_node
, op0
, cmp
, op1
, auto_bitmap (),
2463 if (val
&& TREE_CODE (val
) == INTEGER_CST
)
2465 if (predictor
== PRED_BUILTIN_EXPECT
)
2467 int percent
= PARAM_VALUE (BUILTIN_EXPECT_PROBABILITY
);
2469 gcc_assert (percent
>= 0 && percent
<= 100);
2470 if (integer_zerop (val
))
2471 percent
= 100 - percent
;
2472 predict_edge (then_edge
, PRED_BUILTIN_EXPECT
, HITRATE (percent
));
2475 predict_edge_def (then_edge
, predictor
,
2476 integer_zerop (val
) ? NOT_TAKEN
: TAKEN
);
2478 /* Try "pointer heuristic."
2479 A comparison ptr == 0 is predicted as false.
2480 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2481 if (POINTER_TYPE_P (type
))
2484 predict_edge_def (then_edge
, PRED_TREE_POINTER
, NOT_TAKEN
);
2485 else if (cmp
== NE_EXPR
)
2486 predict_edge_def (then_edge
, PRED_TREE_POINTER
, TAKEN
);
2490 /* Try "opcode heuristic."
2491 EQ tests are usually false and NE tests are usually true. Also,
2492 most quantities are positive, so we can make the appropriate guesses
2493 about signed comparisons against zero. */
2498 /* Floating point comparisons appears to behave in a very
2499 unpredictable way because of special role of = tests in
2501 if (FLOAT_TYPE_P (type
))
2503 /* Comparisons with 0 are often used for booleans and there is
2504 nothing useful to predict about them. */
2505 else if (integer_zerop (op0
) || integer_zerop (op1
))
2508 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, NOT_TAKEN
);
2513 /* Floating point comparisons appears to behave in a very
2514 unpredictable way because of special role of = tests in
2516 if (FLOAT_TYPE_P (type
))
2518 /* Comparisons with 0 are often used for booleans and there is
2519 nothing useful to predict about them. */
2520 else if (integer_zerop (op0
)
2521 || integer_zerop (op1
))
2524 predict_edge_def (then_edge
, PRED_TREE_OPCODE_NONEQUAL
, TAKEN
);
2528 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, TAKEN
);
2531 case UNORDERED_EXPR
:
2532 predict_edge_def (then_edge
, PRED_TREE_FPOPCODE
, NOT_TAKEN
);
2537 if (integer_zerop (op1
)
2538 || integer_onep (op1
)
2539 || integer_all_onesp (op1
)
2542 || real_minus_onep (op1
))
2543 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, NOT_TAKEN
);
2548 if (integer_zerop (op1
)
2549 || integer_onep (op1
)
2550 || integer_all_onesp (op1
)
2553 || real_minus_onep (op1
))
2554 predict_edge_def (then_edge
, PRED_TREE_OPCODE_POSITIVE
, TAKEN
);
2562 /* Returns TRUE if the STMT is exit(0) like statement. */
2565 is_exit_with_zero_arg (const gimple
*stmt
)
2567 /* This is not exit, _exit or _Exit. */
2568 if (!gimple_call_builtin_p (stmt
, BUILT_IN_EXIT
)
2569 && !gimple_call_builtin_p (stmt
, BUILT_IN__EXIT
)
2570 && !gimple_call_builtin_p (stmt
, BUILT_IN__EXIT2
))
2573 /* Argument is an interger zero. */
2574 return integer_zerop (gimple_call_arg (stmt
, 0));
2577 /* Try to guess whether the value of return means error code. */
2579 static enum br_predictor
2580 return_prediction (tree val
, enum prediction
*prediction
)
2584 return PRED_NO_PREDICTION
;
2585 /* Different heuristics for pointers and scalars. */
2586 if (POINTER_TYPE_P (TREE_TYPE (val
)))
2588 /* NULL is usually not returned. */
2589 if (integer_zerop (val
))
2591 *prediction
= NOT_TAKEN
;
2592 return PRED_NULL_RETURN
;
2595 else if (INTEGRAL_TYPE_P (TREE_TYPE (val
)))
2597 /* Negative return values are often used to indicate
2599 if (TREE_CODE (val
) == INTEGER_CST
2600 && tree_int_cst_sgn (val
) < 0)
2602 *prediction
= NOT_TAKEN
;
2603 return PRED_NEGATIVE_RETURN
;
2605 /* Constant return values seems to be commonly taken.
2606 Zero/one often represent booleans so exclude them from the
2608 if (TREE_CONSTANT (val
)
2609 && (!integer_zerop (val
) && !integer_onep (val
)))
2611 *prediction
= NOT_TAKEN
;
2612 return PRED_CONST_RETURN
;
2615 return PRED_NO_PREDICTION
;
2618 /* Find the basic block with return expression and look up for possible
2619 return value trying to apply RETURN_PREDICTION heuristics. */
2621 apply_return_prediction (void)
2623 greturn
*return_stmt
= NULL
;
2627 int phi_num_args
, i
;
2628 enum br_predictor pred
;
2629 enum prediction direction
;
2632 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
)
2634 gimple
*last
= last_stmt (e
->src
);
2636 && gimple_code (last
) == GIMPLE_RETURN
)
2638 return_stmt
= as_a
<greturn
*> (last
);
2644 return_val
= gimple_return_retval (return_stmt
);
2647 if (TREE_CODE (return_val
) != SSA_NAME
2648 || !SSA_NAME_DEF_STMT (return_val
)
2649 || gimple_code (SSA_NAME_DEF_STMT (return_val
)) != GIMPLE_PHI
)
2651 phi
= as_a
<gphi
*> (SSA_NAME_DEF_STMT (return_val
));
2652 phi_num_args
= gimple_phi_num_args (phi
);
2653 pred
= return_prediction (PHI_ARG_DEF (phi
, 0), &direction
);
2655 /* Avoid the degenerate case where all return values form the function
2656 belongs to same category (ie they are all positive constants)
2657 so we can hardly say something about them. */
2658 for (i
= 1; i
< phi_num_args
; i
++)
2659 if (pred
!= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
))
2661 if (i
!= phi_num_args
)
2662 for (i
= 0; i
< phi_num_args
; i
++)
2664 pred
= return_prediction (PHI_ARG_DEF (phi
, i
), &direction
);
2665 if (pred
!= PRED_NO_PREDICTION
)
2666 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi
, i
), pred
,
2671 /* Look for basic block that contains unlikely to happen events
2672 (such as noreturn calls) and mark all paths leading to execution
2673 of this basic blocks as unlikely. */
2676 tree_bb_level_predictions (void)
2679 bool has_return_edges
= false;
2683 FOR_EACH_EDGE (e
, ei
, EXIT_BLOCK_PTR_FOR_FN (cfun
)->preds
)
2684 if (!unlikely_executed_edge_p (e
) && !(e
->flags
& EDGE_ABNORMAL_CALL
))
2686 has_return_edges
= true;
2690 apply_return_prediction ();
2692 FOR_EACH_BB_FN (bb
, cfun
)
2694 gimple_stmt_iterator gsi
;
2696 for (gsi
= gsi_start_bb (bb
); !gsi_end_p (gsi
); gsi_next (&gsi
))
2698 gimple
*stmt
= gsi_stmt (gsi
);
2701 if (is_gimple_call (stmt
))
2703 if (gimple_call_noreturn_p (stmt
)
2705 && !is_exit_with_zero_arg (stmt
))
2706 predict_paths_leading_to (bb
, PRED_NORETURN
,
2708 decl
= gimple_call_fndecl (stmt
);
2710 && lookup_attribute ("cold",
2711 DECL_ATTRIBUTES (decl
)))
2712 predict_paths_leading_to (bb
, PRED_COLD_FUNCTION
,
2714 if (decl
&& recursive_call_p (current_function_decl
, decl
))
2715 predict_paths_leading_to (bb
, PRED_RECURSIVE_CALL
,
2718 else if (gimple_code (stmt
) == GIMPLE_PREDICT
)
2720 predict_paths_leading_to (bb
, gimple_predict_predictor (stmt
),
2721 gimple_predict_outcome (stmt
));
2722 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2723 hints to callers. */
2729 /* Callback for hash_map::traverse, asserts that the pointer map is
2733 assert_is_empty (const_basic_block
const &, edge_prediction
*const &value
,
2736 gcc_assert (!value
);
2740 /* Predict branch probabilities and estimate profile for basic block BB.
2741 When LOCAL_ONLY is set do not use any global properties of CFG. */
2744 tree_estimate_probability_bb (basic_block bb
, bool local_only
)
2749 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
2751 /* Look for block we are guarding (ie we dominate it,
2752 but it doesn't postdominate us). */
2753 if (e
->dest
!= EXIT_BLOCK_PTR_FOR_FN (cfun
) && e
->dest
!= bb
2755 && dominated_by_p (CDI_DOMINATORS
, e
->dest
, e
->src
)
2756 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e
->dest
))
2758 gimple_stmt_iterator bi
;
2760 /* The call heuristic claims that a guarded function call
2761 is improbable. This is because such calls are often used
2762 to signal exceptional situations such as printing error
2764 for (bi
= gsi_start_bb (e
->dest
); !gsi_end_p (bi
);
2767 gimple
*stmt
= gsi_stmt (bi
);
2768 if (is_gimple_call (stmt
)
2769 && !gimple_inexpensive_call_p (as_a
<gcall
*> (stmt
))
2770 /* Constant and pure calls are hardly used to signalize
2771 something exceptional. */
2772 && gimple_has_side_effects (stmt
))
2774 if (gimple_call_fndecl (stmt
))
2775 predict_edge_def (e
, PRED_CALL
, NOT_TAKEN
);
2776 else if (virtual_method_call_p (gimple_call_fn (stmt
)))
2777 predict_edge_def (e
, PRED_POLYMORPHIC_CALL
, NOT_TAKEN
);
2779 predict_edge_def (e
, PRED_INDIR_CALL
, TAKEN
);
2785 tree_predict_by_opcode (bb
);
2788 /* Predict branch probabilities and estimate profile of the tree CFG.
2789 This function can be called from the loop optimizers to recompute
2790 the profile information.
2791 If DRY_RUN is set, do not modify CFG and only produce dump files. */
2794 tree_estimate_probability (bool dry_run
)
2798 add_noreturn_fake_exit_edges ();
2799 connect_infinite_loops_to_exit ();
2800 /* We use loop_niter_by_eval, which requires that the loops have
2802 create_preheaders (CP_SIMPLE_PREHEADERS
);
2803 calculate_dominance_info (CDI_POST_DOMINATORS
);
2805 bb_predictions
= new hash_map
<const_basic_block
, edge_prediction
*>;
2806 tree_bb_level_predictions ();
2807 record_loop_exits ();
2809 if (number_of_loops (cfun
) > 1)
2812 FOR_EACH_BB_FN (bb
, cfun
)
2813 tree_estimate_probability_bb (bb
, false);
2815 FOR_EACH_BB_FN (bb
, cfun
)
2816 combine_predictions_for_bb (bb
, dry_run
);
2819 bb_predictions
->traverse
<void *, assert_is_empty
> (NULL
);
2821 delete bb_predictions
;
2822 bb_predictions
= NULL
;
2825 estimate_bb_frequencies (false);
2826 free_dominance_info (CDI_POST_DOMINATORS
);
2827 remove_fake_exit_edges ();
2830 /* Set edge->probability for each successor edge of BB. */
2832 tree_guess_outgoing_edge_probabilities (basic_block bb
)
2834 bb_predictions
= new hash_map
<const_basic_block
, edge_prediction
*>;
2835 tree_estimate_probability_bb (bb
, true);
2836 combine_predictions_for_bb (bb
, false);
2838 bb_predictions
->traverse
<void *, assert_is_empty
> (NULL
);
2839 delete bb_predictions
;
2840 bb_predictions
= NULL
;
2843 /* Predict edges to successors of CUR whose sources are not postdominated by
2844 BB by PRED and recurse to all postdominators. */
2847 predict_paths_for_bb (basic_block cur
, basic_block bb
,
2848 enum br_predictor pred
,
2849 enum prediction taken
,
2850 bitmap visited
, struct loop
*in_loop
= NULL
)
2856 /* If we exited the loop or CUR is unconditional in the loop, there is
2859 && (!flow_bb_inside_loop_p (in_loop
, cur
)
2860 || dominated_by_p (CDI_DOMINATORS
, in_loop
->latch
, cur
)))
2863 /* We are looking for all edges forming edge cut induced by
2864 set of all blocks postdominated by BB. */
2865 FOR_EACH_EDGE (e
, ei
, cur
->preds
)
2866 if (e
->src
->index
>= NUM_FIXED_BLOCKS
2867 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, bb
))
2873 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2874 if (unlikely_executed_edge_p (e
))
2876 gcc_assert (bb
== cur
|| dominated_by_p (CDI_POST_DOMINATORS
, cur
, bb
));
2878 /* See if there is an edge from e->src that is not abnormal
2879 and does not lead to BB and does not exit the loop. */
2880 FOR_EACH_EDGE (e2
, ei2
, e
->src
->succs
)
2882 && !unlikely_executed_edge_p (e2
)
2883 && !dominated_by_p (CDI_POST_DOMINATORS
, e2
->dest
, bb
)
2884 && (!in_loop
|| !loop_exit_edge_p (in_loop
, e2
)))
2890 /* If there is non-abnormal path leaving e->src, predict edge
2891 using predictor. Otherwise we need to look for paths
2894 The second may lead to infinite loop in the case we are predicitng
2895 regions that are only reachable by abnormal edges. We simply
2896 prevent visiting given BB twice. */
2899 if (!edge_predicted_by_p (e
, pred
, taken
))
2900 predict_edge_def (e
, pred
, taken
);
2902 else if (bitmap_set_bit (visited
, e
->src
->index
))
2903 predict_paths_for_bb (e
->src
, e
->src
, pred
, taken
, visited
, in_loop
);
2905 for (son
= first_dom_son (CDI_POST_DOMINATORS
, cur
);
2907 son
= next_dom_son (CDI_POST_DOMINATORS
, son
))
2908 predict_paths_for_bb (son
, bb
, pred
, taken
, visited
, in_loop
);
2911 /* Sets branch probabilities according to PREDiction and
2915 predict_paths_leading_to (basic_block bb
, enum br_predictor pred
,
2916 enum prediction taken
, struct loop
*in_loop
)
2918 predict_paths_for_bb (bb
, bb
, pred
, taken
, auto_bitmap (), in_loop
);
2921 /* Like predict_paths_leading_to but take edge instead of basic block. */
2924 predict_paths_leading_to_edge (edge e
, enum br_predictor pred
,
2925 enum prediction taken
, struct loop
*in_loop
)
2927 bool has_nonloop_edge
= false;
2931 basic_block bb
= e
->src
;
2932 FOR_EACH_EDGE (e2
, ei
, bb
->succs
)
2933 if (e2
->dest
!= e
->src
&& e2
->dest
!= e
->dest
2934 && !unlikely_executed_edge_p (e
)
2935 && !dominated_by_p (CDI_POST_DOMINATORS
, e
->src
, e2
->dest
))
2937 has_nonloop_edge
= true;
2940 if (!has_nonloop_edge
)
2942 predict_paths_for_bb (bb
, bb
, pred
, taken
, auto_bitmap (), in_loop
);
2945 predict_edge_def (e
, pred
, taken
);
2948 /* This is used to carry information about basic blocks. It is
2949 attached to the AUX field of the standard CFG block. */
2953 /* Estimated frequency of execution of basic_block. */
2956 /* To keep queue of basic blocks to process. */
2959 /* Number of predecessors we need to visit first. */
2963 /* Similar information for edges. */
2964 struct edge_prob_info
2966 /* In case edge is a loopback edge, the probability edge will be reached
2967 in case header is. Estimated number of iterations of the loop can be
2968 then computed as 1 / (1 - back_edge_prob). */
2969 sreal back_edge_prob
;
2970 /* True if the edge is a loopback edge in the natural loop. */
2971 unsigned int back_edge
:1;
2974 #define BLOCK_INFO(B) ((block_info *) (B)->aux)
2976 #define EDGE_INFO(E) ((edge_prob_info *) (E)->aux)
2978 /* Helper function for estimate_bb_frequencies.
2979 Propagate the frequencies in blocks marked in
2980 TOVISIT, starting in HEAD. */
2983 propagate_freq (basic_block head
, bitmap tovisit
)
2992 /* For each basic block we need to visit count number of his predecessors
2993 we need to visit first. */
2994 EXECUTE_IF_SET_IN_BITMAP (tovisit
, 0, i
, bi
)
2999 bb
= BASIC_BLOCK_FOR_FN (cfun
, i
);
3001 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3003 bool visit
= bitmap_bit_p (tovisit
, e
->src
->index
);
3005 if (visit
&& !(e
->flags
& EDGE_DFS_BACK
))
3007 else if (visit
&& dump_file
&& !EDGE_INFO (e
)->back_edge
)
3009 "Irreducible region hit, ignoring edge to %i->%i\n",
3010 e
->src
->index
, bb
->index
);
3012 BLOCK_INFO (bb
)->npredecessors
= count
;
3013 /* When function never returns, we will never process exit block. */
3014 if (!count
&& bb
== EXIT_BLOCK_PTR_FOR_FN (cfun
))
3016 bb
->count
= profile_count::zero ();
3021 BLOCK_INFO (head
)->frequency
= 1;
3023 for (bb
= head
; bb
; bb
= nextbb
)
3026 sreal cyclic_probability
= 0;
3027 sreal frequency
= 0;
3029 nextbb
= BLOCK_INFO (bb
)->next
;
3030 BLOCK_INFO (bb
)->next
= NULL
;
3032 /* Compute frequency of basic block. */
3036 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3037 gcc_assert (!bitmap_bit_p (tovisit
, e
->src
->index
)
3038 || (e
->flags
& EDGE_DFS_BACK
));
3040 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3041 if (EDGE_INFO (e
)->back_edge
)
3043 cyclic_probability
+= EDGE_INFO (e
)->back_edge_prob
;
3045 else if (!(e
->flags
& EDGE_DFS_BACK
))
3047 /* frequency += (e->probability
3048 * BLOCK_INFO (e->src)->frequency /
3049 REG_BR_PROB_BASE); */
3051 sreal tmp
= e
->probability
.to_reg_br_prob_base ();
3052 tmp
*= BLOCK_INFO (e
->src
)->frequency
;
3053 tmp
*= real_inv_br_prob_base
;
3057 if (cyclic_probability
== 0)
3059 BLOCK_INFO (bb
)->frequency
= frequency
;
3063 if (cyclic_probability
> real_almost_one
)
3064 cyclic_probability
= real_almost_one
;
3066 /* BLOCK_INFO (bb)->frequency = frequency
3067 / (1 - cyclic_probability) */
3069 cyclic_probability
= sreal (1) - cyclic_probability
;
3070 BLOCK_INFO (bb
)->frequency
= frequency
/ cyclic_probability
;
3074 bitmap_clear_bit (tovisit
, bb
->index
);
3076 e
= find_edge (bb
, head
);
3079 /* EDGE_INFO (e)->back_edge_prob
3080 = ((e->probability * BLOCK_INFO (bb)->frequency)
3081 / REG_BR_PROB_BASE); */
3083 sreal tmp
= e
->probability
.to_reg_br_prob_base ();
3084 tmp
*= BLOCK_INFO (bb
)->frequency
;
3085 EDGE_INFO (e
)->back_edge_prob
= tmp
* real_inv_br_prob_base
;
3088 /* Propagate to successor blocks. */
3089 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3090 if (!(e
->flags
& EDGE_DFS_BACK
)
3091 && BLOCK_INFO (e
->dest
)->npredecessors
)
3093 BLOCK_INFO (e
->dest
)->npredecessors
--;
3094 if (!BLOCK_INFO (e
->dest
)->npredecessors
)
3099 BLOCK_INFO (last
)->next
= e
->dest
;
3107 /* Estimate frequencies in loops at same nest level. */
3110 estimate_loops_at_level (struct loop
*first_loop
)
3114 for (loop
= first_loop
; loop
; loop
= loop
->next
)
3119 auto_bitmap tovisit
;
3121 estimate_loops_at_level (loop
->inner
);
3123 /* Find current loop back edge and mark it. */
3124 e
= loop_latch_edge (loop
);
3125 EDGE_INFO (e
)->back_edge
= 1;
3127 bbs
= get_loop_body (loop
);
3128 for (i
= 0; i
< loop
->num_nodes
; i
++)
3129 bitmap_set_bit (tovisit
, bbs
[i
]->index
);
3131 propagate_freq (loop
->header
, tovisit
);
3135 /* Propagates frequencies through structure of loops. */
3138 estimate_loops (void)
3140 auto_bitmap tovisit
;
3143 /* Start by estimating the frequencies in the loops. */
3144 if (number_of_loops (cfun
) > 1)
3145 estimate_loops_at_level (current_loops
->tree_root
->inner
);
3147 /* Now propagate the frequencies through all the blocks. */
3148 FOR_ALL_BB_FN (bb
, cfun
)
3150 bitmap_set_bit (tovisit
, bb
->index
);
3152 propagate_freq (ENTRY_BLOCK_PTR_FOR_FN (cfun
), tovisit
);
3155 /* Drop the profile for NODE to guessed, and update its frequency based on
3156 whether it is expected to be hot given the CALL_COUNT. */
3159 drop_profile (struct cgraph_node
*node
, profile_count call_count
)
3161 struct function
*fn
= DECL_STRUCT_FUNCTION (node
->decl
);
3162 /* In the case where this was called by another function with a
3163 dropped profile, call_count will be 0. Since there are no
3164 non-zero call counts to this function, we don't know for sure
3165 whether it is hot, and therefore it will be marked normal below. */
3166 bool hot
= maybe_hot_count_p (NULL
, call_count
);
3170 "Dropping 0 profile for %s. %s based on calls.\n",
3172 hot
? "Function is hot" : "Function is normal");
3173 /* We only expect to miss profiles for functions that are reached
3174 via non-zero call edges in cases where the function may have
3175 been linked from another module or library (COMDATs and extern
3176 templates). See the comments below for handle_missing_profiles.
3177 Also, only warn in cases where the missing counts exceed the
3178 number of training runs. In certain cases with an execv followed
3179 by a no-return call the profile for the no-return call is not
3180 dumped and there can be a mismatch. */
3181 if (!DECL_COMDAT (node
->decl
) && !DECL_EXTERNAL (node
->decl
)
3182 && call_count
> profile_info
->runs
)
3184 if (flag_profile_correction
)
3188 "Missing counts for called function %s\n",
3189 node
->dump_name ());
3192 warning (0, "Missing counts for called function %s",
3193 node
->dump_name ());
3197 FOR_ALL_BB_FN (bb
, fn
)
3199 bb
->count
= profile_count::uninitialized ();
3203 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3204 e
->count
= profile_count::uninitialized ();
3207 struct cgraph_edge
*e
;
3208 for (e
= node
->callees
; e
; e
= e
->next_caller
)
3210 e
->count
= profile_count::uninitialized ();
3211 e
->frequency
= compute_call_stmt_bb_frequency (e
->caller
->decl
,
3212 gimple_bb (e
->call_stmt
));
3214 node
->count
= profile_count::uninitialized ();
3216 profile_status_for_fn (fn
)
3217 = (flag_guess_branch_prob
? PROFILE_GUESSED
: PROFILE_ABSENT
);
3219 = hot
? NODE_FREQUENCY_HOT
: NODE_FREQUENCY_NORMAL
;
3222 /* In the case of COMDAT routines, multiple object files will contain the same
3223 function and the linker will select one for the binary. In that case
3224 all the other copies from the profile instrument binary will be missing
3225 profile counts. Look for cases where this happened, due to non-zero
3226 call counts going to 0-count functions, and drop the profile to guessed
3227 so that we can use the estimated probabilities and avoid optimizing only
3230 The other case where the profile may be missing is when the routine
3231 is not going to be emitted to the object file, e.g. for "extern template"
3232 class methods. Those will be marked DECL_EXTERNAL. Emit a warning in
3233 all other cases of non-zero calls to 0-count functions. */
3236 handle_missing_profiles (void)
3238 struct cgraph_node
*node
;
3239 int unlikely_count_fraction
= PARAM_VALUE (UNLIKELY_BB_COUNT_FRACTION
);
3240 auto_vec
<struct cgraph_node
*, 64> worklist
;
3242 /* See if 0 count function has non-0 count callers. In this case we
3243 lost some profile. Drop its function profile to PROFILE_GUESSED. */
3244 FOR_EACH_DEFINED_FUNCTION (node
)
3246 struct cgraph_edge
*e
;
3247 profile_count call_count
= profile_count::zero ();
3248 gcov_type max_tp_first_run
= 0;
3249 struct function
*fn
= DECL_STRUCT_FUNCTION (node
->decl
);
3251 if (!(node
->count
== profile_count::zero ()))
3253 for (e
= node
->callers
; e
; e
= e
->next_caller
)
3254 if (e
->count
.initialized_p () && e
->count
> 0)
3256 call_count
= call_count
+ e
->count
;
3258 if (e
->caller
->tp_first_run
> max_tp_first_run
)
3259 max_tp_first_run
= e
->caller
->tp_first_run
;
3262 /* If time profile is missing, let assign the maximum that comes from
3263 caller functions. */
3264 if (!node
->tp_first_run
&& max_tp_first_run
)
3265 node
->tp_first_run
= max_tp_first_run
+ 1;
3269 && (call_count
.apply_scale (unlikely_count_fraction
, 1)
3270 >= profile_info
->runs
))
3272 drop_profile (node
, call_count
);
3273 worklist
.safe_push (node
);
3277 /* Propagate the profile dropping to other 0-count COMDATs that are
3278 potentially called by COMDATs we already dropped the profile on. */
3279 while (worklist
.length () > 0)
3281 struct cgraph_edge
*e
;
3283 node
= worklist
.pop ();
3284 for (e
= node
->callees
; e
; e
= e
->next_caller
)
3286 struct cgraph_node
*callee
= e
->callee
;
3287 struct function
*fn
= DECL_STRUCT_FUNCTION (callee
->decl
);
3289 if (callee
->count
> 0)
3291 if ((DECL_COMDAT (callee
->decl
) || DECL_EXTERNAL (callee
->decl
))
3293 && profile_status_for_fn (fn
) == PROFILE_READ
)
3295 drop_profile (node
, profile_count::zero ());
3296 worklist
.safe_push (callee
);
3302 /* Convert counts measured by profile driven feedback to frequencies.
3303 Return nonzero iff there was any nonzero execution count. */
3306 counts_to_freqs (void)
3308 gcov_type count_max
;
3309 profile_count true_count_max
= profile_count::zero ();
3312 /* Don't overwrite the estimated frequencies when the profile for
3313 the function is missing. We may drop this function PROFILE_GUESSED
3314 later in drop_profile (). */
3315 if (!ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
.initialized_p ()
3316 || ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
== profile_count::zero ())
3319 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
3320 if (bb
->count
> true_count_max
)
3321 true_count_max
= bb
->count
;
3323 /* If we have no counts to base frequencies on, keep those that are
3325 if (!(true_count_max
> 0))
3328 count_max
= true_count_max
.to_gcov_type ();
3330 FOR_ALL_BB_FN (bb
, cfun
)
3331 if (bb
->count
.initialized_p ())
3332 bb
->frequency
= RDIV (bb
->count
.to_gcov_type () * BB_FREQ_MAX
, count_max
);
3337 /* Return true if function is likely to be expensive, so there is no point to
3338 optimize performance of prologue, epilogue or do inlining at the expense
3339 of code size growth. THRESHOLD is the limit of number of instructions
3340 function can execute at average to be still considered not expensive. */
3343 expensive_function_p (int threshold
)
3345 unsigned int sum
= 0;
3349 /* We can not compute accurately for large thresholds due to scaled
3351 gcc_assert (threshold
<= BB_FREQ_MAX
);
3353 /* Frequencies are out of range. This either means that function contains
3354 internal loop executing more than BB_FREQ_MAX times or profile feedback
3355 is available and function has not been executed at all. */
3356 if (ENTRY_BLOCK_PTR_FOR_FN (cfun
)->frequency
== 0)
3359 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
3360 limit
= ENTRY_BLOCK_PTR_FOR_FN (cfun
)->frequency
* threshold
;
3361 FOR_EACH_BB_FN (bb
, cfun
)
3365 FOR_BB_INSNS (bb
, insn
)
3366 if (active_insn_p (insn
))
3368 sum
+= bb
->frequency
;
3377 /* Determine basic blocks/edges that are known to be unlikely executed and set
3378 their counters to zero.
3379 This is done with first identifying obviously unlikely BBs/edges and then
3380 propagating in both directions. */
3383 determine_unlikely_bbs ()
3386 auto_vec
<basic_block
, 64> worklist
;
3390 FOR_EACH_BB_FN (bb
, cfun
)
3392 if (!(bb
->count
== profile_count::zero ())
3393 && unlikely_executed_bb_p (bb
))
3395 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3396 fprintf (dump_file
, "Basic block %i is locally unlikely\n",
3398 bb
->count
= profile_count::zero ();
3401 if (bb
->count
== profile_count::zero ())
3404 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3405 e
->count
= profile_count::zero ();
3408 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3409 if (!(e
->count
== profile_count::zero ())
3410 && unlikely_executed_edge_p (e
))
3412 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3413 fprintf (dump_file
, "Edge %i->%i is locally unlikely\n",
3414 bb
->index
, e
->dest
->index
);
3415 e
->count
= profile_count::zero ();
3418 gcc_checking_assert (!bb
->aux
);
3421 if (!(ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
== profile_count::zero ()))
3423 ENTRY_BLOCK_PTR_FOR_FN (cfun
)->aux
= (void *)(size_t) 1;
3424 worklist
.safe_push (ENTRY_BLOCK_PTR_FOR_FN (cfun
));
3426 while (worklist
.length () > 0)
3428 bb
= worklist
.pop ();
3429 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3430 if (!(e
->count
== profile_count::zero ())
3431 && !(e
->dest
->count
== profile_count::zero ())
3434 e
->dest
->aux
= (void *)(size_t) 1;
3435 worklist
.safe_push (e
->dest
);
3440 FOR_ALL_BB_FN (bb
, cfun
)
3444 if (!(bb
->count
== profile_count::zero ())
3445 && (dump_file
&& (dump_flags
& TDF_DETAILS
)))
3447 "Basic block %i is marked unlikely by forward prop\n",
3449 bb
->count
= profile_count::zero ();
3451 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3452 e
->count
= profile_count::zero ();
3458 auto_vec
<int, 64> nsuccs
;
3459 nsuccs
.safe_grow_cleared (last_basic_block_for_fn (cfun
));
3460 FOR_ALL_BB_FN (bb
, cfun
)
3461 if (!(bb
->count
== profile_count::zero ())
3462 && bb
!= EXIT_BLOCK_PTR_FOR_FN (cfun
))
3464 nsuccs
[bb
->index
] = 0;
3465 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3466 if (!(e
->count
== profile_count::zero ()))
3467 nsuccs
[bb
->index
]++;
3468 if (!nsuccs
[bb
->index
])
3469 worklist
.safe_push (bb
);
3471 while (worklist
.length () > 0)
3473 bb
= worklist
.pop ();
3474 if (bb
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
))
3477 for (gimple_stmt_iterator gsi
= gsi_start_bb (bb
);
3478 !gsi_end_p (gsi
); gsi_next (&gsi
))
3479 if (stmt_can_terminate_bb_p (gsi_stmt (gsi
))
3480 /* stmt_can_terminate_bb_p special cases noreturns because it
3481 assumes that fake edges are created. We want to know that
3482 noreturn alone does not imply BB to be unlikely. */
3483 || (is_gimple_call (gsi_stmt (gsi
))
3484 && (gimple_call_flags (gsi_stmt (gsi
)) & ECF_NORETURN
)))
3492 if (!(bb
->count
== profile_count::zero ())
3493 && (dump_file
&& (dump_flags
& TDF_DETAILS
)))
3495 "Basic block %i is marked unlikely by backward prop\n",
3497 bb
->count
= profile_count::zero ();
3499 FOR_EACH_EDGE (e
, ei
, bb
->preds
)
3500 if (!(e
->count
== profile_count::zero ()))
3502 e
->count
= profile_count::zero ();
3503 if (!(e
->src
->count
== profile_count::zero ()))
3505 nsuccs
[e
->src
->index
]--;
3506 if (!nsuccs
[e
->src
->index
])
3507 worklist
.safe_push (e
->src
);
3513 /* Estimate and propagate basic block frequencies using the given branch
3514 probabilities. If FORCE is true, the frequencies are used to estimate
3515 the counts even when there are already non-zero profile counts. */
3518 estimate_bb_frequencies (bool force
)
3523 determine_unlikely_bbs ();
3525 if (force
|| profile_status_for_fn (cfun
) != PROFILE_READ
3526 || !counts_to_freqs ())
3528 static int real_values_initialized
= 0;
3530 if (!real_values_initialized
)
3532 real_values_initialized
= 1;
3533 real_br_prob_base
= REG_BR_PROB_BASE
;
3534 real_bb_freq_max
= BB_FREQ_MAX
;
3535 real_one_half
= sreal (1, -1);
3536 real_inv_br_prob_base
= sreal (1) / real_br_prob_base
;
3537 real_almost_one
= sreal (1) - real_inv_br_prob_base
;
3540 mark_dfs_back_edges ();
3542 single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun
))->probability
=
3543 profile_probability::always ();
3545 /* Set up block info for each basic block. */
3546 alloc_aux_for_blocks (sizeof (block_info
));
3547 alloc_aux_for_edges (sizeof (edge_prob_info
));
3548 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
3553 FOR_EACH_EDGE (e
, ei
, bb
->succs
)
3555 EDGE_INFO (e
)->back_edge_prob
3556 = e
->probability
.to_reg_br_prob_base ();
3557 EDGE_INFO (e
)->back_edge_prob
*= real_inv_br_prob_base
;
3561 /* First compute frequencies locally for each loop from innermost
3562 to outermost to examine frequencies for back edges. */
3566 FOR_EACH_BB_FN (bb
, cfun
)
3567 if (freq_max
< BLOCK_INFO (bb
)->frequency
)
3568 freq_max
= BLOCK_INFO (bb
)->frequency
;
3570 freq_max
= real_bb_freq_max
/ freq_max
;
3571 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
3573 sreal tmp
= BLOCK_INFO (bb
)->frequency
* freq_max
+ real_one_half
;
3574 bb
->frequency
= tmp
.to_int ();
3577 free_aux_for_blocks ();
3578 free_aux_for_edges ();
3580 compute_function_frequency ();
3583 /* Decide whether function is hot, cold or unlikely executed. */
3585 compute_function_frequency (void)
3588 struct cgraph_node
*node
= cgraph_node::get (current_function_decl
);
3590 if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
3591 || MAIN_NAME_P (DECL_NAME (current_function_decl
)))
3592 node
->only_called_at_startup
= true;
3593 if (DECL_STATIC_DESTRUCTOR (current_function_decl
))
3594 node
->only_called_at_exit
= true;
3596 if (profile_status_for_fn (cfun
) != PROFILE_READ
)
3598 int flags
= flags_from_decl_or_type (current_function_decl
);
3599 if (ENTRY_BLOCK_PTR_FOR_FN (cfun
)->count
== profile_count::zero ()
3600 || lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl
))
3602 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
3603 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl
))
3605 node
->frequency
= NODE_FREQUENCY_HOT
;
3606 else if (flags
& ECF_NORETURN
)
3607 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
3608 else if (MAIN_NAME_P (DECL_NAME (current_function_decl
)))
3609 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
3610 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl
)
3611 || DECL_STATIC_DESTRUCTOR (current_function_decl
))
3612 node
->frequency
= NODE_FREQUENCY_EXECUTED_ONCE
;
3616 /* Only first time try to drop function into unlikely executed.
3617 After inlining the roundoff errors may confuse us.
3618 Ipa-profile pass will drop functions only called from unlikely
3619 functions to unlikely and that is most of what we care about. */
3620 if (!cfun
->after_inlining
)
3621 node
->frequency
= NODE_FREQUENCY_UNLIKELY_EXECUTED
;
3622 FOR_EACH_BB_FN (bb
, cfun
)
3624 if (maybe_hot_bb_p (cfun
, bb
))
3626 node
->frequency
= NODE_FREQUENCY_HOT
;
3629 if (!probably_never_executed_bb_p (cfun
, bb
))
3630 node
->frequency
= NODE_FREQUENCY_NORMAL
;
3634 /* Build PREDICT_EXPR. */
3636 build_predict_expr (enum br_predictor predictor
, enum prediction taken
)
3638 tree t
= build1 (PREDICT_EXPR
, void_type_node
,
3639 build_int_cst (integer_type_node
, predictor
));
3640 SET_PREDICT_EXPR_OUTCOME (t
, taken
);
3645 predictor_name (enum br_predictor predictor
)
3647 return predictor_info
[predictor
].name
;
3650 /* Predict branch probabilities and estimate profile of the tree CFG. */
3654 const pass_data pass_data_profile
=
3656 GIMPLE_PASS
, /* type */
3657 "profile_estimate", /* name */
3658 OPTGROUP_NONE
, /* optinfo_flags */
3659 TV_BRANCH_PROB
, /* tv_id */
3660 PROP_cfg
, /* properties_required */
3661 0, /* properties_provided */
3662 0, /* properties_destroyed */
3663 0, /* todo_flags_start */
3664 0, /* todo_flags_finish */
3667 class pass_profile
: public gimple_opt_pass
3670 pass_profile (gcc::context
*ctxt
)
3671 : gimple_opt_pass (pass_data_profile
, ctxt
)
3674 /* opt_pass methods: */
3675 virtual bool gate (function
*) { return flag_guess_branch_prob
; }
3676 virtual unsigned int execute (function
*);
3678 }; // class pass_profile
3681 pass_profile::execute (function
*fun
)
3685 if (profile_status_for_fn (cfun
) == PROFILE_GUESSED
)
3688 loop_optimizer_init (LOOPS_NORMAL
);
3689 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3690 flow_loops_dump (dump_file
, NULL
, 0);
3692 mark_irreducible_loops ();
3694 nb_loops
= number_of_loops (fun
);
3698 tree_estimate_probability (false);
3703 loop_optimizer_finalize ();
3704 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3705 gimple_dump_cfg (dump_file
, dump_flags
);
3706 if (profile_status_for_fn (fun
) == PROFILE_ABSENT
)
3707 profile_status_for_fn (fun
) = PROFILE_GUESSED
;
3708 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3711 FOR_EACH_LOOP (loop
, LI_FROM_INNERMOST
)
3712 if (loop
->header
->frequency
)
3713 fprintf (dump_file
, "Loop got predicted %d to iterate %i times.\n",
3715 (int)expected_loop_iterations_unbounded (loop
));
3723 make_pass_profile (gcc::context
*ctxt
)
3725 return new pass_profile (ctxt
);
3730 const pass_data pass_data_strip_predict_hints
=
3732 GIMPLE_PASS
, /* type */
3733 "*strip_predict_hints", /* name */
3734 OPTGROUP_NONE
, /* optinfo_flags */
3735 TV_BRANCH_PROB
, /* tv_id */
3736 PROP_cfg
, /* properties_required */
3737 0, /* properties_provided */
3738 0, /* properties_destroyed */
3739 0, /* todo_flags_start */
3740 0, /* todo_flags_finish */
3743 class pass_strip_predict_hints
: public gimple_opt_pass
3746 pass_strip_predict_hints (gcc::context
*ctxt
)
3747 : gimple_opt_pass (pass_data_strip_predict_hints
, ctxt
)
3750 /* opt_pass methods: */
3751 opt_pass
* clone () { return new pass_strip_predict_hints (m_ctxt
); }
3752 virtual unsigned int execute (function
*);
3754 }; // class pass_strip_predict_hints
3756 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
3757 we no longer need. */
3759 pass_strip_predict_hints::execute (function
*fun
)
3764 bool changed
= false;
3766 FOR_EACH_BB_FN (bb
, fun
)
3768 gimple_stmt_iterator bi
;
3769 for (bi
= gsi_start_bb (bb
); !gsi_end_p (bi
);)
3771 gimple
*stmt
= gsi_stmt (bi
);
3773 if (gimple_code (stmt
) == GIMPLE_PREDICT
)
3775 gsi_remove (&bi
, true);
3779 else if (is_gimple_call (stmt
))
3781 tree fndecl
= gimple_call_fndecl (stmt
);
3784 && DECL_BUILT_IN_CLASS (fndecl
) == BUILT_IN_NORMAL
3785 && DECL_FUNCTION_CODE (fndecl
) == BUILT_IN_EXPECT
3786 && gimple_call_num_args (stmt
) == 2)
3787 || (gimple_call_internal_p (stmt
)
3788 && gimple_call_internal_fn (stmt
) == IFN_BUILTIN_EXPECT
))
3790 var
= gimple_call_lhs (stmt
);
3795 = gimple_build_assign (var
, gimple_call_arg (stmt
, 0));
3796 gsi_replace (&bi
, ass_stmt
, true);
3800 gsi_remove (&bi
, true);
3808 return changed
? TODO_cleanup_cfg
: 0;
3814 make_pass_strip_predict_hints (gcc::context
*ctxt
)
3816 return new pass_strip_predict_hints (ctxt
);
3819 /* Rebuild function frequencies. Passes are in general expected to
3820 maintain profile by hand, however in some cases this is not possible:
3821 for example when inlining several functions with loops freuqencies might run
3822 out of scale and thus needs to be recomputed. */
3825 rebuild_frequencies (void)
3827 timevar_push (TV_REBUILD_FREQUENCIES
);
3829 /* When the max bb count in the function is small, there is a higher
3830 chance that there were truncation errors in the integer scaling
3831 of counts by inlining and other optimizations. This could lead
3832 to incorrect classification of code as being cold when it isn't.
3833 In that case, force the estimation of bb counts/frequencies from the
3834 branch probabilities, rather than computing frequencies from counts,
3835 which may also lead to frequencies incorrectly reduced to 0. There
3836 is less precision in the probabilities, so we only do this for small
3838 profile_count count_max
= profile_count::zero ();
3840 FOR_BB_BETWEEN (bb
, ENTRY_BLOCK_PTR_FOR_FN (cfun
), NULL
, next_bb
)
3841 if (bb
->count
> count_max
)
3842 count_max
= bb
->count
;
3844 if (profile_status_for_fn (cfun
) == PROFILE_GUESSED
3845 || (!flag_auto_profile
&& profile_status_for_fn (cfun
) == PROFILE_READ
3846 && count_max
< REG_BR_PROB_BASE
/ 10))
3848 loop_optimizer_init (0);
3849 add_noreturn_fake_exit_edges ();
3850 mark_irreducible_loops ();
3851 connect_infinite_loops_to_exit ();
3852 estimate_bb_frequencies (true);
3853 remove_fake_exit_edges ();
3854 loop_optimizer_finalize ();
3856 else if (profile_status_for_fn (cfun
) == PROFILE_READ
)
3860 timevar_pop (TV_REBUILD_FREQUENCIES
);
3863 /* Perform a dry run of the branch prediction pass and report comparsion of
3864 the predicted and real profile into the dump file. */
3867 report_predictor_hitrates (void)
3871 loop_optimizer_init (LOOPS_NORMAL
);
3872 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3873 flow_loops_dump (dump_file
, NULL
, 0);
3875 mark_irreducible_loops ();
3877 nb_loops
= number_of_loops (cfun
);
3881 tree_estimate_probability (true);
3886 loop_optimizer_finalize ();
3889 /* Force edge E to be cold.
3890 If IMPOSSIBLE is true, for edge to have count and probability 0 otherwise
3891 keep low probability to represent possible error in a guess. This is used
3892 i.e. in case we predict loop to likely iterate given number of times but
3893 we are not 100% sure.
3895 This function locally updates profile without attempt to keep global
3896 consistency which can not be reached in full generality without full profile
3897 rebuild from probabilities alone. Doing so is not necessarily a good idea
3898 because frequencies and counts may be more realistic then probabilities.
3900 In some cases (such as for elimination of early exits during full loop
3901 unrolling) the caller can ensure that profile will get consistent
3905 force_edge_cold (edge e
, bool impossible
)
3907 profile_count count_sum
= profile_count::zero ();
3908 profile_probability prob_sum
= profile_probability::never ();
3911 profile_count old_count
= e
->count
;
3912 profile_probability old_probability
= e
->probability
;
3913 bool uninitialized_exit
= false;
3915 profile_probability goal
= (impossible
? profile_probability::never ()
3916 : profile_probability::very_unlikely ());
3918 /* If edge is already improbably or cold, just return. */
3919 if (e
->probability
<= goal
3920 && (!impossible
|| e
->count
== profile_count::zero ()))
3922 FOR_EACH_EDGE (e2
, ei
, e
->src
->succs
)
3925 if (e2
->count
.initialized_p ())
3926 count_sum
+= e2
->count
;
3928 uninitialized_exit
= true;
3929 if (e2
->probability
.initialized_p ())
3930 prob_sum
+= e2
->probability
;
3933 /* If there are other edges out of e->src, redistribute probabilitity
3935 if (prob_sum
> profile_probability::never ())
3937 if (!(e
->probability
< goal
))
3938 e
->probability
= goal
;
3940 e
->count
= profile_count::zero ();
3941 else if (old_probability
> profile_probability::never ())
3942 e
->count
= e
->count
.apply_probability (e
->probability
3945 e
->count
= e
->count
.apply_scale (1, REG_BR_PROB_BASE
);
3947 profile_probability prob_comp
= prob_sum
/ e
->probability
.invert ();
3949 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
3950 fprintf (dump_file
, "Making edge %i->%i %s by redistributing "
3951 "probability to other edges.\n",
3952 e
->src
->index
, e
->dest
->index
,
3953 impossible
? "impossible" : "cold");
3954 profile_count count_sum2
= count_sum
+ old_count
- e
->count
;
3955 FOR_EACH_EDGE (e2
, ei
, e
->src
->succs
)
3959 e2
->count
.apply_scale (count_sum2
, count_sum
);
3960 e2
->probability
/= prob_comp
;
3962 if (current_ir_type () != IR_GIMPLE
3963 && e
->src
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
))
3964 update_br_prob_note (e
->src
);
3966 /* If all edges out of e->src are unlikely, the basic block itself
3970 if (prob_sum
== profile_probability::never ())
3971 e
->probability
= profile_probability::always ();
3975 e
->probability
= profile_probability::never ();
3976 /* If BB has some edges out that are not impossible, we can not
3977 assume that BB itself is. */
3980 if (current_ir_type () != IR_GIMPLE
3981 && e
->src
!= ENTRY_BLOCK_PTR_FOR_FN (cfun
))
3982 update_br_prob_note (e
->src
);
3983 if (e
->src
->count
== profile_count::zero ())
3985 if (count_sum
== profile_count::zero () && !uninitialized_exit
3989 if (e
->src
== ENTRY_BLOCK_PTR_FOR_FN (cfun
))
3991 else if (current_ir_type () == IR_GIMPLE
)
3992 for (gimple_stmt_iterator gsi
= gsi_start_bb (e
->src
);
3993 !gsi_end_p (gsi
); gsi_next (&gsi
))
3995 if (stmt_can_terminate_bb_p (gsi_stmt (gsi
)))
4001 /* FIXME: Implement RTL path. */
4006 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4008 "Making bb %i impossible and dropping count to 0.\n",
4010 e
->count
= profile_count::zero ();
4011 e
->src
->count
= profile_count::zero ();
4012 FOR_EACH_EDGE (e2
, ei
, e
->src
->preds
)
4013 force_edge_cold (e2
, impossible
);
4018 /* If we did not adjusting, the source basic block has no likely edeges
4019 leaving other direction. In that case force that bb cold, too.
4020 This in general is difficult task to do, but handle special case when
4021 BB has only one predecestor. This is common case when we are updating
4022 after loop transforms. */
4023 if (!(prob_sum
> profile_probability::never ())
4024 && count_sum
== profile_count::zero ()
4025 && single_pred_p (e
->src
) && e
->src
->frequency
> (impossible
? 0 : 1))
4027 int old_frequency
= e
->src
->frequency
;
4028 if (dump_file
&& (dump_flags
& TDF_DETAILS
))
4029 fprintf (dump_file
, "Making bb %i %s.\n", e
->src
->index
,
4030 impossible
? "impossible" : "cold");
4031 e
->src
->frequency
= MIN (e
->src
->frequency
, impossible
? 0 : 1);
4033 e
->src
->count
= e
->count
= profile_count::zero ();
4035 e
->src
->count
= e
->count
= e
->count
.apply_scale (e
->src
->frequency
,
4037 force_edge_cold (single_pred_edge (e
->src
), impossible
);
4039 else if (dump_file
&& (dump_flags
& TDF_DETAILS
)
4040 && maybe_hot_bb_p (cfun
, e
->src
))
4041 fprintf (dump_file
, "Giving up on making bb %i %s.\n", e
->src
->index
,
4042 impossible
? "impossible" : "cold");
4048 namespace selftest
{
4050 /* Test that value range of predictor values defined in predict.def is
4051 within range (50, 100]. */
4053 struct branch_predictor
4056 unsigned probability
;
4059 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) { NAME, HITRATE },
4062 test_prediction_value_range ()
4064 branch_predictor predictors
[] = {
4065 #include "predict.def"
4069 for (unsigned i
= 0; predictors
[i
].name
!= NULL
; i
++)
4071 unsigned p
= 100 * predictors
[i
].probability
/ REG_BR_PROB_BASE
;
4072 ASSERT_TRUE (p
> 50 && p
<= 100);
4076 #undef DEF_PREDICTOR
4078 /* Run all of the selfests within this file. */
4083 test_prediction_value_range ();
4086 } // namespace selftest
4087 #endif /* CHECKING_P. */