PR c++/80972 - C++17 ICE with attribute packed.
[official-gcc.git] / gcc / predict.c
blob60d1a094d1061ab579b346724d676708a80d57f1
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
9 version.
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
14 for more details.
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/>. */
20 /* References:
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. */
30 #include "config.h"
31 #include "system.h"
32 #include "coretypes.h"
33 #include "backend.h"
34 #include "rtl.h"
35 #include "tree.h"
36 #include "gimple.h"
37 #include "cfghooks.h"
38 #include "tree-pass.h"
39 #include "ssa.h"
40 #include "memmodel.h"
41 #include "emit-rtl.h"
42 #include "cgraph.h"
43 #include "coverage.h"
44 #include "diagnostic-core.h"
45 #include "gimple-predict.h"
46 #include "fold-const.h"
47 #include "calls.h"
48 #include "cfganal.h"
49 #include "profile.h"
50 #include "sreal.h"
51 #include "params.h"
52 #include "cfgloop.h"
53 #include "gimple-iterator.h"
54 #include "tree-cfg.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"
60 #include "selftest.h"
62 /* Enum with reasons why a predictor is ignored. */
64 enum predictor_reason
66 REASON_NONE,
67 REASON_IGNORED,
68 REASON_SINGLE_EDGE_DUPLICATE,
69 REASON_EDGE_PAIR_DUPLICATE
72 /* String messages for the aforementioned enum. */
74 static const char *reason_messages[] = {"", " (ignored)",
75 " (single edge duplicate)", " (edge pair duplicate)"};
77 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
78 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
79 static sreal real_almost_one, real_br_prob_base,
80 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
82 static void combine_predictions_for_insn (rtx_insn *, basic_block);
83 static void dump_prediction (FILE *, enum br_predictor, int, basic_block,
84 enum predictor_reason, edge);
85 static void predict_paths_leading_to (basic_block, enum br_predictor,
86 enum prediction,
87 struct loop *in_loop = NULL);
88 static void predict_paths_leading_to_edge (edge, enum br_predictor,
89 enum prediction,
90 struct loop *in_loop = NULL);
91 static bool can_predict_insn_p (const rtx_insn *);
93 /* Information we hold about each branch predictor.
94 Filled using information from predict.def. */
96 struct predictor_info
98 const char *const name; /* Name used in the debugging dumps. */
99 const int hitrate; /* Expected hitrate used by
100 predict_insn_def call. */
101 const int flags;
104 /* Use given predictor without Dempster-Shaffer theory if it matches
105 using first_match heuristics. */
106 #define PRED_FLAG_FIRST_MATCH 1
108 /* Recompute hitrate in percent to our representation. */
110 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
112 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
113 static const struct predictor_info predictor_info[]= {
114 #include "predict.def"
116 /* Upper bound on predictors. */
117 {NULL, 0, 0}
119 #undef DEF_PREDICTOR
121 /* Return TRUE if frequency FREQ is considered to be hot. */
123 static inline bool
124 maybe_hot_frequency_p (struct function *fun, int freq)
126 struct cgraph_node *node = cgraph_node::get (fun->decl);
127 if (!profile_info || profile_status_for_fn (fun) != PROFILE_READ)
129 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
130 return false;
131 if (node->frequency == NODE_FREQUENCY_HOT)
132 return true;
134 if (profile_status_for_fn (fun) == PROFILE_ABSENT)
135 return true;
136 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
137 && freq < (ENTRY_BLOCK_PTR_FOR_FN (fun)->frequency * 2 / 3))
138 return false;
139 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION) == 0)
140 return false;
141 if (freq * PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)
142 < ENTRY_BLOCK_PTR_FOR_FN (fun)->frequency)
143 return false;
144 return true;
147 static gcov_type min_count = -1;
149 /* Determine the threshold for hot BB counts. */
151 gcov_type
152 get_hot_bb_threshold ()
154 gcov_working_set_t *ws;
155 if (min_count == -1)
157 ws = find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE));
158 gcc_assert (ws);
159 min_count = ws->min_counter;
161 return min_count;
164 /* Set the threshold for hot BB counts. */
166 void
167 set_hot_bb_threshold (gcov_type min)
169 min_count = min;
172 /* Return TRUE if frequency FREQ is considered to be hot. */
174 bool
175 maybe_hot_count_p (struct function *, profile_count count)
177 if (!count.initialized_p ())
178 return true;
179 /* Code executed at most once is not hot. */
180 if (count <= MAX (profile_info ? profile_info->runs : 1, 1))
181 return false;
182 return (count.to_gcov_type () >= get_hot_bb_threshold ());
185 /* Return true in case BB can be CPU intensive and should be optimized
186 for maximal performance. */
188 bool
189 maybe_hot_bb_p (struct function *fun, const_basic_block bb)
191 gcc_checking_assert (fun);
192 if (!maybe_hot_count_p (fun, bb->count))
193 return false;
194 return maybe_hot_frequency_p (fun, bb->frequency);
197 /* Return true in case BB can be CPU intensive and should be optimized
198 for maximal performance. */
200 bool
201 maybe_hot_edge_p (edge e)
203 if (!maybe_hot_count_p (cfun, e->count))
204 return false;
205 return maybe_hot_frequency_p (cfun, EDGE_FREQUENCY (e));
208 /* Return true if profile COUNT and FREQUENCY, or function FUN static
209 node frequency reflects never being executed. */
211 static bool
212 probably_never_executed (struct function *fun,
213 profile_count count, int)
215 gcc_checking_assert (fun);
216 if (count == profile_count::zero ())
217 return true;
218 if (count.initialized_p () && profile_status_for_fn (fun) == PROFILE_READ)
220 int unlikely_count_fraction = PARAM_VALUE (UNLIKELY_BB_COUNT_FRACTION);
221 if (count.apply_scale (unlikely_count_fraction, 1) >= profile_info->runs)
222 return false;
223 return true;
225 if ((!profile_info || profile_status_for_fn (fun) != PROFILE_READ)
226 && (cgraph_node::get (fun->decl)->frequency
227 == NODE_FREQUENCY_UNLIKELY_EXECUTED))
228 return true;
229 return false;
233 /* Return true in case BB is probably never executed. */
235 bool
236 probably_never_executed_bb_p (struct function *fun, const_basic_block bb)
238 return probably_never_executed (fun, bb->count, bb->frequency);
242 /* Return true if E is unlikely executed for obvious reasons. */
244 static bool
245 unlikely_executed_edge_p (edge e)
247 return e->count == profile_count::zero ()
248 || (e->flags & (EDGE_EH | EDGE_FAKE));
251 /* Return true in case edge E is probably never executed. */
253 bool
254 probably_never_executed_edge_p (struct function *fun, edge e)
256 if (e->count.initialized_p ())
257 unlikely_executed_edge_p (e);
258 return probably_never_executed (fun, e->count, EDGE_FREQUENCY (e));
261 /* Return true when current function should always be optimized for size. */
263 bool
264 optimize_function_for_size_p (struct function *fun)
266 if (!fun || !fun->decl)
267 return optimize_size;
268 cgraph_node *n = cgraph_node::get (fun->decl);
269 return n && n->optimize_for_size_p ();
272 /* Return true when current function should always be optimized for speed. */
274 bool
275 optimize_function_for_speed_p (struct function *fun)
277 return !optimize_function_for_size_p (fun);
280 /* Return the optimization type that should be used for the function FUN. */
282 optimization_type
283 function_optimization_type (struct function *fun)
285 return (optimize_function_for_speed_p (fun)
286 ? OPTIMIZE_FOR_SPEED
287 : OPTIMIZE_FOR_SIZE);
290 /* Return TRUE when BB should be optimized for size. */
292 bool
293 optimize_bb_for_size_p (const_basic_block bb)
295 return (optimize_function_for_size_p (cfun)
296 || (bb && !maybe_hot_bb_p (cfun, bb)));
299 /* Return TRUE when BB should be optimized for speed. */
301 bool
302 optimize_bb_for_speed_p (const_basic_block bb)
304 return !optimize_bb_for_size_p (bb);
307 /* Return the optimization type that should be used for block BB. */
309 optimization_type
310 bb_optimization_type (const_basic_block bb)
312 return (optimize_bb_for_speed_p (bb)
313 ? OPTIMIZE_FOR_SPEED
314 : OPTIMIZE_FOR_SIZE);
317 /* Return TRUE when BB should be optimized for size. */
319 bool
320 optimize_edge_for_size_p (edge e)
322 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
325 /* Return TRUE when BB should be optimized for speed. */
327 bool
328 optimize_edge_for_speed_p (edge e)
330 return !optimize_edge_for_size_p (e);
333 /* Return TRUE when BB should be optimized for size. */
335 bool
336 optimize_insn_for_size_p (void)
338 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
341 /* Return TRUE when BB should be optimized for speed. */
343 bool
344 optimize_insn_for_speed_p (void)
346 return !optimize_insn_for_size_p ();
349 /* Return TRUE when LOOP should be optimized for size. */
351 bool
352 optimize_loop_for_size_p (struct loop *loop)
354 return optimize_bb_for_size_p (loop->header);
357 /* Return TRUE when LOOP should be optimized for speed. */
359 bool
360 optimize_loop_for_speed_p (struct loop *loop)
362 return optimize_bb_for_speed_p (loop->header);
365 /* Return TRUE when LOOP nest should be optimized for speed. */
367 bool
368 optimize_loop_nest_for_speed_p (struct loop *loop)
370 struct loop *l = loop;
371 if (optimize_loop_for_speed_p (loop))
372 return true;
373 l = loop->inner;
374 while (l && l != loop)
376 if (optimize_loop_for_speed_p (l))
377 return true;
378 if (l->inner)
379 l = l->inner;
380 else if (l->next)
381 l = l->next;
382 else
384 while (l != loop && !l->next)
385 l = loop_outer (l);
386 if (l != loop)
387 l = l->next;
390 return false;
393 /* Return TRUE when LOOP nest should be optimized for size. */
395 bool
396 optimize_loop_nest_for_size_p (struct loop *loop)
398 return !optimize_loop_nest_for_speed_p (loop);
401 /* Return true when edge E is likely to be well predictable by branch
402 predictor. */
404 bool
405 predictable_edge_p (edge e)
407 if (profile_status_for_fn (cfun) == PROFILE_ABSENT)
408 return false;
409 if ((e->probability
410 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
411 || (REG_BR_PROB_BASE - e->probability
412 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
413 return true;
414 return false;
418 /* Set RTL expansion for BB profile. */
420 void
421 rtl_profile_for_bb (basic_block bb)
423 crtl->maybe_hot_insn_p = maybe_hot_bb_p (cfun, bb);
426 /* Set RTL expansion for edge profile. */
428 void
429 rtl_profile_for_edge (edge e)
431 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
434 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
435 void
436 default_rtl_profile (void)
438 crtl->maybe_hot_insn_p = true;
441 /* Return true if the one of outgoing edges is already predicted by
442 PREDICTOR. */
444 bool
445 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
447 rtx note;
448 if (!INSN_P (BB_END (bb)))
449 return false;
450 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
451 if (REG_NOTE_KIND (note) == REG_BR_PRED
452 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
453 return true;
454 return false;
457 /* Structure representing predictions in tree level. */
459 struct edge_prediction {
460 struct edge_prediction *ep_next;
461 edge ep_edge;
462 enum br_predictor ep_predictor;
463 int ep_probability;
466 /* This map contains for a basic block the list of predictions for the
467 outgoing edges. */
469 static hash_map<const_basic_block, edge_prediction *> *bb_predictions;
471 /* Return true if the one of outgoing edges is already predicted by
472 PREDICTOR. */
474 bool
475 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
477 struct edge_prediction *i;
478 edge_prediction **preds = bb_predictions->get (bb);
480 if (!preds)
481 return false;
483 for (i = *preds; i; i = i->ep_next)
484 if (i->ep_predictor == predictor)
485 return true;
486 return false;
489 /* Return true if the one of outgoing edges is already predicted by
490 PREDICTOR for edge E predicted as TAKEN. */
492 bool
493 edge_predicted_by_p (edge e, enum br_predictor predictor, bool taken)
495 struct edge_prediction *i;
496 basic_block bb = e->src;
497 edge_prediction **preds = bb_predictions->get (bb);
498 if (!preds)
499 return false;
501 int probability = predictor_info[(int) predictor].hitrate;
503 if (taken != TAKEN)
504 probability = REG_BR_PROB_BASE - probability;
506 for (i = *preds; i; i = i->ep_next)
507 if (i->ep_predictor == predictor
508 && i->ep_edge == e
509 && i->ep_probability == probability)
510 return true;
511 return false;
514 /* Return true when the probability of edge is reliable.
516 The profile guessing code is good at predicting branch outcome (ie.
517 taken/not taken), that is predicted right slightly over 75% of time.
518 It is however notoriously poor on predicting the probability itself.
519 In general the profile appear a lot flatter (with probabilities closer
520 to 50%) than the reality so it is bad idea to use it to drive optimization
521 such as those disabling dynamic branch prediction for well predictable
522 branches.
524 There are two exceptions - edges leading to noreturn edges and edges
525 predicted by number of iterations heuristics are predicted well. This macro
526 should be able to distinguish those, but at the moment it simply check for
527 noreturn heuristic that is only one giving probability over 99% or bellow
528 1%. In future we might want to propagate reliability information across the
529 CFG if we find this information useful on multiple places. */
530 static bool
531 probability_reliable_p (int prob)
533 return (profile_status_for_fn (cfun) == PROFILE_READ
534 || (profile_status_for_fn (cfun) == PROFILE_GUESSED
535 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
538 /* Same predicate as above, working on edges. */
539 bool
540 edge_probability_reliable_p (const_edge e)
542 return probability_reliable_p (e->probability);
545 /* Same predicate as edge_probability_reliable_p, working on notes. */
546 bool
547 br_prob_note_reliable_p (const_rtx note)
549 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
550 return probability_reliable_p (XINT (note, 0));
553 static void
554 predict_insn (rtx_insn *insn, enum br_predictor predictor, int probability)
556 gcc_assert (any_condjump_p (insn));
557 if (!flag_guess_branch_prob)
558 return;
560 add_reg_note (insn, REG_BR_PRED,
561 gen_rtx_CONCAT (VOIDmode,
562 GEN_INT ((int) predictor),
563 GEN_INT ((int) probability)));
566 /* Predict insn by given predictor. */
568 void
569 predict_insn_def (rtx_insn *insn, enum br_predictor predictor,
570 enum prediction taken)
572 int probability = predictor_info[(int) predictor].hitrate;
574 if (taken != TAKEN)
575 probability = REG_BR_PROB_BASE - probability;
577 predict_insn (insn, predictor, probability);
580 /* Predict edge E with given probability if possible. */
582 void
583 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
585 rtx_insn *last_insn;
586 last_insn = BB_END (e->src);
588 /* We can store the branch prediction information only about
589 conditional jumps. */
590 if (!any_condjump_p (last_insn))
591 return;
593 /* We always store probability of branching. */
594 if (e->flags & EDGE_FALLTHRU)
595 probability = REG_BR_PROB_BASE - probability;
597 predict_insn (last_insn, predictor, probability);
600 /* Predict edge E with the given PROBABILITY. */
601 void
602 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
604 if (e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun)
605 && EDGE_COUNT (e->src->succs) > 1
606 && flag_guess_branch_prob
607 && optimize)
609 struct edge_prediction *i = XNEW (struct edge_prediction);
610 edge_prediction *&preds = bb_predictions->get_or_insert (e->src);
612 i->ep_next = preds;
613 preds = i;
614 i->ep_probability = probability;
615 i->ep_predictor = predictor;
616 i->ep_edge = e;
620 /* Filter edge predictions PREDS by a function FILTER. DATA are passed
621 to the filter function. */
623 void
624 filter_predictions (edge_prediction **preds,
625 bool (*filter) (edge_prediction *, void *), void *data)
627 if (!bb_predictions)
628 return;
630 if (preds)
632 struct edge_prediction **prediction = preds;
633 struct edge_prediction *next;
635 while (*prediction)
637 if ((*filter) (*prediction, data))
638 prediction = &((*prediction)->ep_next);
639 else
641 next = (*prediction)->ep_next;
642 free (*prediction);
643 *prediction = next;
649 /* Filter function predicate that returns true for a edge predicate P
650 if its edge is equal to DATA. */
652 bool
653 equal_edge_p (edge_prediction *p, void *data)
655 return p->ep_edge == (edge)data;
658 /* Remove all predictions on given basic block that are attached
659 to edge E. */
660 void
661 remove_predictions_associated_with_edge (edge e)
663 if (!bb_predictions)
664 return;
666 edge_prediction **preds = bb_predictions->get (e->src);
667 filter_predictions (preds, equal_edge_p, e);
670 /* Clears the list of predictions stored for BB. */
672 static void
673 clear_bb_predictions (basic_block bb)
675 edge_prediction **preds = bb_predictions->get (bb);
676 struct edge_prediction *pred, *next;
678 if (!preds)
679 return;
681 for (pred = *preds; pred; pred = next)
683 next = pred->ep_next;
684 free (pred);
686 *preds = NULL;
689 /* Return true when we can store prediction on insn INSN.
690 At the moment we represent predictions only on conditional
691 jumps, not at computed jump or other complicated cases. */
692 static bool
693 can_predict_insn_p (const rtx_insn *insn)
695 return (JUMP_P (insn)
696 && any_condjump_p (insn)
697 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
700 /* Predict edge E by given predictor if possible. */
702 void
703 predict_edge_def (edge e, enum br_predictor predictor,
704 enum prediction taken)
706 int probability = predictor_info[(int) predictor].hitrate;
708 if (taken != TAKEN)
709 probability = REG_BR_PROB_BASE - probability;
711 predict_edge (e, predictor, probability);
714 /* Invert all branch predictions or probability notes in the INSN. This needs
715 to be done each time we invert the condition used by the jump. */
717 void
718 invert_br_probabilities (rtx insn)
720 rtx note;
722 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
723 if (REG_NOTE_KIND (note) == REG_BR_PROB)
724 XINT (note, 0) = REG_BR_PROB_BASE - XINT (note, 0);
725 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
726 XEXP (XEXP (note, 0), 1)
727 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
730 /* Dump information about the branch prediction to the output file. */
732 static void
733 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
734 basic_block bb, enum predictor_reason reason = REASON_NONE,
735 edge ep_edge = NULL)
737 edge e = ep_edge;
738 edge_iterator ei;
740 if (!file)
741 return;
743 if (e == NULL)
744 FOR_EACH_EDGE (e, ei, bb->succs)
745 if (! (e->flags & EDGE_FALLTHRU))
746 break;
748 char edge_info_str[128];
749 if (ep_edge)
750 sprintf (edge_info_str, " of edge %d->%d", ep_edge->src->index,
751 ep_edge->dest->index);
752 else
753 edge_info_str[0] = '\0';
755 fprintf (file, " %s heuristics%s%s: %.1f%%",
756 predictor_info[predictor].name,
757 edge_info_str, reason_messages[reason],
758 probability * 100.0 / REG_BR_PROB_BASE);
760 if (bb->count.initialized_p ())
762 fprintf (file, " exec ");
763 bb->count.dump (file);
764 if (e)
766 fprintf (file, " hit ");
767 e->count.dump (file);
768 fprintf (file, " (%.1f%%)", e->count.to_gcov_type() * 100.0
769 / bb->count.to_gcov_type ());
773 fprintf (file, "\n");
776 /* Return true if STMT is known to be unlikely executed. */
778 static bool
779 unlikely_executed_stmt_p (gimple *stmt)
781 if (!is_gimple_call (stmt))
782 return false;
783 /* NORETURN attribute alone is not strong enough: exit() may be quite
784 likely executed once during program run. */
785 if (gimple_call_fntype (stmt)
786 && lookup_attribute ("cold",
787 TYPE_ATTRIBUTES (gimple_call_fntype (stmt)))
788 && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl)))
789 return true;
790 tree decl = gimple_call_fndecl (stmt);
791 if (!decl)
792 return false;
793 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl))
794 && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl)))
795 return true;
797 cgraph_node *n = cgraph_node::get (decl);
798 if (!n)
799 return false;
801 availability avail;
802 n = n->ultimate_alias_target (&avail);
803 if (avail < AVAIL_AVAILABLE)
804 return false;
805 if (!n->analyzed
806 || n->decl == current_function_decl)
807 return false;
808 return n->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED;
811 /* Return true if BB is unlikely executed. */
813 static bool
814 unlikely_executed_bb_p (basic_block bb)
816 if (bb->count == profile_count::zero ())
817 return true;
818 if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) || bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
819 return false;
820 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
821 !gsi_end_p (gsi); gsi_next (&gsi))
823 if (unlikely_executed_stmt_p (gsi_stmt (gsi)))
824 return true;
825 if (stmt_can_terminate_bb_p (gsi_stmt (gsi)))
826 return false;
828 return false;
831 /* We can not predict the probabilities of outgoing edges of bb. Set them
832 evenly and hope for the best. If UNLIKELY_EDGES is not null, distribute
833 even probability for all edges not mentioned in the set. These edges
834 are given PROB_VERY_UNLIKELY probability. */
836 static void
837 set_even_probabilities (basic_block bb,
838 hash_set<edge> *unlikely_edges = NULL)
840 unsigned nedges = 0;
841 edge e = NULL;
842 edge_iterator ei;
844 FOR_EACH_EDGE (e, ei, bb->succs)
845 if (!unlikely_executed_edge_p (e))
846 nedges ++;
848 /* Make the distribution even if all edges are unlikely. */
849 unsigned unlikely_count = unlikely_edges ? unlikely_edges->elements () : 0;
850 if (unlikely_count == nedges)
852 unlikely_edges = NULL;
853 unlikely_count = 0;
856 unsigned c = nedges - unlikely_count;
858 FOR_EACH_EDGE (e, ei, bb->succs)
859 if (!unlikely_executed_edge_p (e))
861 if (unlikely_edges != NULL && unlikely_edges->contains (e))
862 e->probability = PROB_VERY_UNLIKELY;
863 else
864 e->probability = (REG_BR_PROB_BASE + c / 2) / c;
866 else
867 e->probability = 0;
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. */
873 static void
874 combine_predictions_for_insn (rtx_insn *insn, basic_block bb)
876 rtx prob_note;
877 rtx *pnote;
878 rtx note;
879 int best_probability = PROB_EVEN;
880 enum br_predictor best_predictor = END_PREDICTORS;
881 int combined_probability = REG_BR_PROB_BASE / 2;
882 int d;
883 bool first_match = false;
884 bool found = false;
886 if (!can_predict_insn_p (insn))
888 set_even_probabilities (bb);
889 return;
892 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
893 pnote = &REG_NOTES (insn);
894 if (dump_file)
895 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
896 bb->index);
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));
907 found = true;
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. */
917 if (d == 0)
918 /* If one probability is 0% and one 100%, avoid division by zero. */
919 combined_probability = REG_BR_PROB_BASE / 2;
920 else
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)
930 first_match = true;
932 if (!found)
933 dump_prediction (dump_file, PRED_NO_PREDICTION,
934 combined_probability, bb);
935 else
937 if (!first_match)
938 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
939 bb, !first_match ? REASON_NONE : REASON_IGNORED);
940 else
941 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
942 bb, first_match ? REASON_NONE : REASON_IGNORED);
945 if (first_match)
946 combined_probability = best_probability;
947 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb);
949 while (*pnote)
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);
962 else
963 pnote = &XEXP (*pnote, 1);
966 if (!prob_note)
968 add_int_reg_note (insn, REG_BR_PROB, combined_probability);
970 /* Save the prediction into CFG in case we are seeing non-degenerated
971 conditional jump. */
972 if (!single_succ_p (bb))
974 BRANCH_EDGE (bb)->probability = combined_probability;
975 FALLTHRU_EDGE (bb)->probability
976 = REG_BR_PROB_BASE - combined_probability;
979 else if (!single_succ_p (bb))
981 int prob = XINT (prob_note, 0);
983 BRANCH_EDGE (bb)->probability = prob;
984 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
986 else
987 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
990 /* Edge prediction hash traits. */
992 struct predictor_hash: pointer_hash <edge_prediction>
995 static inline hashval_t hash (const edge_prediction *);
996 static inline bool equal (const edge_prediction *, const edge_prediction *);
999 /* Calculate hash value of an edge prediction P based on predictor and
1000 normalized probability. */
1002 inline hashval_t
1003 predictor_hash::hash (const edge_prediction *p)
1005 inchash::hash hstate;
1006 hstate.add_int (p->ep_predictor);
1008 int prob = p->ep_probability;
1009 if (prob > REG_BR_PROB_BASE / 2)
1010 prob = REG_BR_PROB_BASE - prob;
1012 hstate.add_int (prob);
1014 return hstate.end ();
1017 /* Return true whether edge predictions P1 and P2 use the same predictor and
1018 have equal (or opposed probability). */
1020 inline bool
1021 predictor_hash::equal (const edge_prediction *p1, const edge_prediction *p2)
1023 return (p1->ep_predictor == p2->ep_predictor
1024 && (p1->ep_probability == p2->ep_probability
1025 || p1->ep_probability == REG_BR_PROB_BASE - p2->ep_probability));
1028 struct predictor_hash_traits: predictor_hash,
1029 typed_noop_remove <edge_prediction *> {};
1031 /* Return true if edge prediction P is not in DATA hash set. */
1033 static bool
1034 not_removed_prediction_p (edge_prediction *p, void *data)
1036 hash_set<edge_prediction *> *remove = (hash_set<edge_prediction *> *) data;
1037 return !remove->contains (p);
1040 /* Prune predictions for a basic block BB. Currently we do following
1041 clean-up steps:
1043 1) remove duplicate prediction that is guessed with the same probability
1044 (different than 1/2) to both edge
1045 2) remove duplicates for a prediction that belongs with the same probability
1046 to a single edge
1050 static void
1051 prune_predictions_for_bb (basic_block bb)
1053 edge_prediction **preds = bb_predictions->get (bb);
1055 if (preds)
1057 hash_table <predictor_hash_traits> s (13);
1058 hash_set <edge_prediction *> remove;
1060 /* Step 1: identify predictors that should be removed. */
1061 for (edge_prediction *pred = *preds; pred; pred = pred->ep_next)
1063 edge_prediction *existing = s.find (pred);
1064 if (existing)
1066 if (pred->ep_edge == existing->ep_edge
1067 && pred->ep_probability == existing->ep_probability)
1069 /* Remove a duplicate predictor. */
1070 dump_prediction (dump_file, pred->ep_predictor,
1071 pred->ep_probability, bb,
1072 REASON_SINGLE_EDGE_DUPLICATE, pred->ep_edge);
1074 remove.add (pred);
1076 else if (pred->ep_edge != existing->ep_edge
1077 && pred->ep_probability == existing->ep_probability
1078 && pred->ep_probability != REG_BR_PROB_BASE / 2)
1080 /* Remove both predictors as they predict the same
1081 for both edges. */
1082 dump_prediction (dump_file, existing->ep_predictor,
1083 pred->ep_probability, bb,
1084 REASON_EDGE_PAIR_DUPLICATE,
1085 existing->ep_edge);
1086 dump_prediction (dump_file, pred->ep_predictor,
1087 pred->ep_probability, bb,
1088 REASON_EDGE_PAIR_DUPLICATE,
1089 pred->ep_edge);
1091 remove.add (existing);
1092 remove.add (pred);
1096 edge_prediction **slot2 = s.find_slot (pred, INSERT);
1097 *slot2 = pred;
1100 /* Step 2: Remove predictors. */
1101 filter_predictions (preds, not_removed_prediction_p, &remove);
1105 /* Combine predictions into single probability and store them into CFG.
1106 Remove now useless prediction entries.
1107 If DRY_RUN is set, only produce dumps and do not modify profile. */
1109 static void
1110 combine_predictions_for_bb (basic_block bb, bool dry_run)
1112 int best_probability = PROB_EVEN;
1113 enum br_predictor best_predictor = END_PREDICTORS;
1114 int combined_probability = REG_BR_PROB_BASE / 2;
1115 int d;
1116 bool first_match = false;
1117 bool found = false;
1118 struct edge_prediction *pred;
1119 int nedges = 0;
1120 edge e, first = NULL, second = NULL;
1121 edge_iterator ei;
1123 FOR_EACH_EDGE (e, ei, bb->succs)
1124 if (!unlikely_executed_edge_p (e))
1126 nedges ++;
1127 if (first && !second)
1128 second = e;
1129 if (!first)
1130 first = e;
1133 /* When there is no successor or only one choice, prediction is easy.
1135 When we have a basic block with more than 2 successors, the situation
1136 is more complicated as DS theory cannot be used literally.
1137 More precisely, let's assume we predicted edge e1 with probability p1,
1138 thus: m1({b1}) = p1. As we're going to combine more than 2 edges, we
1139 need to find probability of e.g. m1({b2}), which we don't know.
1140 The only approximation is to equally distribute 1-p1 to all edges
1141 different from b1.
1143 According to numbers we've got from SPEC2006 benchark, there's only
1144 one interesting reliable predictor (noreturn call), which can be
1145 handled with a bit easier approach. */
1146 if (nedges != 2)
1148 hash_set<edge> unlikely_edges (4);
1150 /* Identify all edges that have a probability close to very unlikely.
1151 Doing the approach for very unlikely doesn't worth for doing as
1152 there's no such probability in SPEC2006 benchmark. */
1153 edge_prediction **preds = bb_predictions->get (bb);
1154 if (preds)
1155 for (pred = *preds; pred; pred = pred->ep_next)
1156 if (pred->ep_probability <= PROB_VERY_UNLIKELY)
1157 unlikely_edges.add (pred->ep_edge);
1159 if (!bb->count.initialized_p () && !dry_run)
1160 set_even_probabilities (bb, &unlikely_edges);
1161 clear_bb_predictions (bb);
1162 if (dump_file)
1164 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
1165 if (unlikely_edges.elements () == 0)
1166 fprintf (dump_file,
1167 "%i edges in bb %i predicted to even probabilities\n",
1168 nedges, bb->index);
1169 else
1171 fprintf (dump_file,
1172 "%i edges in bb %i predicted with some unlikely edges\n",
1173 nedges, bb->index);
1174 FOR_EACH_EDGE (e, ei, bb->succs)
1175 if (!unlikely_executed_edge_p (e))
1176 dump_prediction (dump_file, PRED_COMBINED, e->probability,
1177 bb, REASON_NONE, e);
1180 return;
1183 if (dump_file)
1184 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
1186 prune_predictions_for_bb (bb);
1188 edge_prediction **preds = bb_predictions->get (bb);
1190 if (preds)
1192 /* We implement "first match" heuristics and use probability guessed
1193 by predictor with smallest index. */
1194 for (pred = *preds; pred; pred = pred->ep_next)
1196 enum br_predictor predictor = pred->ep_predictor;
1197 int probability = pred->ep_probability;
1199 if (pred->ep_edge != first)
1200 probability = REG_BR_PROB_BASE - probability;
1202 found = true;
1203 /* First match heuristics would be widly confused if we predicted
1204 both directions. */
1205 if (best_predictor > predictor
1206 && predictor_info[predictor].flags & PRED_FLAG_FIRST_MATCH)
1208 struct edge_prediction *pred2;
1209 int prob = probability;
1211 for (pred2 = (struct edge_prediction *) *preds;
1212 pred2; pred2 = pred2->ep_next)
1213 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
1215 int probability2 = pred2->ep_probability;
1217 if (pred2->ep_edge != first)
1218 probability2 = REG_BR_PROB_BASE - probability2;
1220 if ((probability < REG_BR_PROB_BASE / 2) !=
1221 (probability2 < REG_BR_PROB_BASE / 2))
1222 break;
1224 /* If the same predictor later gave better result, go for it! */
1225 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
1226 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
1227 prob = probability2;
1229 if (!pred2)
1230 best_probability = prob, best_predictor = predictor;
1233 d = (combined_probability * probability
1234 + (REG_BR_PROB_BASE - combined_probability)
1235 * (REG_BR_PROB_BASE - probability));
1237 /* Use FP math to avoid overflows of 32bit integers. */
1238 if (d == 0)
1239 /* If one probability is 0% and one 100%, avoid division by zero. */
1240 combined_probability = REG_BR_PROB_BASE / 2;
1241 else
1242 combined_probability = (((double) combined_probability)
1243 * probability
1244 * REG_BR_PROB_BASE / d + 0.5);
1248 /* Decide which heuristic to use. In case we didn't match anything,
1249 use no_prediction heuristic, in case we did match, use either
1250 first match or Dempster-Shaffer theory depending on the flags. */
1252 if (best_predictor != END_PREDICTORS)
1253 first_match = true;
1255 if (!found)
1256 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb);
1257 else
1259 if (!first_match)
1260 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
1261 !first_match ? REASON_NONE : REASON_IGNORED);
1262 else
1263 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
1264 first_match ? REASON_NONE : REASON_IGNORED);
1267 if (first_match)
1268 combined_probability = best_probability;
1269 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb);
1271 if (preds)
1273 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
1275 enum br_predictor predictor = pred->ep_predictor;
1276 int probability = pred->ep_probability;
1278 dump_prediction (dump_file, predictor, probability, bb,
1279 (!first_match || best_predictor == predictor)
1280 ? REASON_NONE : REASON_IGNORED, pred->ep_edge);
1283 clear_bb_predictions (bb);
1285 if (!bb->count.initialized_p () && !dry_run)
1287 first->probability = combined_probability;
1288 second->probability = REG_BR_PROB_BASE - combined_probability;
1292 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
1293 Return the SSA_NAME if the condition satisfies, NULL otherwise.
1295 T1 and T2 should be one of the following cases:
1296 1. T1 is SSA_NAME, T2 is NULL
1297 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
1298 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
1300 static tree
1301 strips_small_constant (tree t1, tree t2)
1303 tree ret = NULL;
1304 int value = 0;
1306 if (!t1)
1307 return NULL;
1308 else if (TREE_CODE (t1) == SSA_NAME)
1309 ret = t1;
1310 else if (tree_fits_shwi_p (t1))
1311 value = tree_to_shwi (t1);
1312 else
1313 return NULL;
1315 if (!t2)
1316 return ret;
1317 else if (tree_fits_shwi_p (t2))
1318 value = tree_to_shwi (t2);
1319 else if (TREE_CODE (t2) == SSA_NAME)
1321 if (ret)
1322 return NULL;
1323 else
1324 ret = t2;
1327 if (value <= 4 && value >= -4)
1328 return ret;
1329 else
1330 return NULL;
1333 /* Return the SSA_NAME in T or T's operands.
1334 Return NULL if SSA_NAME cannot be found. */
1336 static tree
1337 get_base_value (tree t)
1339 if (TREE_CODE (t) == SSA_NAME)
1340 return t;
1342 if (!BINARY_CLASS_P (t))
1343 return NULL;
1345 switch (TREE_OPERAND_LENGTH (t))
1347 case 1:
1348 return strips_small_constant (TREE_OPERAND (t, 0), NULL);
1349 case 2:
1350 return strips_small_constant (TREE_OPERAND (t, 0),
1351 TREE_OPERAND (t, 1));
1352 default:
1353 return NULL;
1357 /* Check the compare STMT in LOOP. If it compares an induction
1358 variable to a loop invariant, return true, and save
1359 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1360 Otherwise return false and set LOOP_INVAIANT to NULL. */
1362 static bool
1363 is_comparison_with_loop_invariant_p (gcond *stmt, struct loop *loop,
1364 tree *loop_invariant,
1365 enum tree_code *compare_code,
1366 tree *loop_step,
1367 tree *loop_iv_base)
1369 tree op0, op1, bound, base;
1370 affine_iv iv0, iv1;
1371 enum tree_code code;
1372 tree step;
1374 code = gimple_cond_code (stmt);
1375 *loop_invariant = NULL;
1377 switch (code)
1379 case GT_EXPR:
1380 case GE_EXPR:
1381 case NE_EXPR:
1382 case LT_EXPR:
1383 case LE_EXPR:
1384 case EQ_EXPR:
1385 break;
1387 default:
1388 return false;
1391 op0 = gimple_cond_lhs (stmt);
1392 op1 = gimple_cond_rhs (stmt);
1394 if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1395 || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1396 return false;
1397 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1398 return false;
1399 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1400 return false;
1401 if (TREE_CODE (iv0.step) != INTEGER_CST
1402 || TREE_CODE (iv1.step) != INTEGER_CST)
1403 return false;
1404 if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1405 || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1406 return false;
1408 if (integer_zerop (iv0.step))
1410 if (code != NE_EXPR && code != EQ_EXPR)
1411 code = invert_tree_comparison (code, false);
1412 bound = iv0.base;
1413 base = iv1.base;
1414 if (tree_fits_shwi_p (iv1.step))
1415 step = iv1.step;
1416 else
1417 return false;
1419 else
1421 bound = iv1.base;
1422 base = iv0.base;
1423 if (tree_fits_shwi_p (iv0.step))
1424 step = iv0.step;
1425 else
1426 return false;
1429 if (TREE_CODE (bound) != INTEGER_CST)
1430 bound = get_base_value (bound);
1431 if (!bound)
1432 return false;
1433 if (TREE_CODE (base) != INTEGER_CST)
1434 base = get_base_value (base);
1435 if (!base)
1436 return false;
1438 *loop_invariant = bound;
1439 *compare_code = code;
1440 *loop_step = step;
1441 *loop_iv_base = base;
1442 return true;
1445 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1447 static bool
1448 expr_coherent_p (tree t1, tree t2)
1450 gimple *stmt;
1451 tree ssa_name_1 = NULL;
1452 tree ssa_name_2 = NULL;
1454 gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1455 gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1457 if (t1 == t2)
1458 return true;
1460 if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1461 return true;
1462 if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1463 return false;
1465 /* Check to see if t1 is expressed/defined with t2. */
1466 stmt = SSA_NAME_DEF_STMT (t1);
1467 gcc_assert (stmt != NULL);
1468 if (is_gimple_assign (stmt))
1470 ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1471 if (ssa_name_1 && ssa_name_1 == t2)
1472 return true;
1475 /* Check to see if t2 is expressed/defined with t1. */
1476 stmt = SSA_NAME_DEF_STMT (t2);
1477 gcc_assert (stmt != NULL);
1478 if (is_gimple_assign (stmt))
1480 ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1481 if (ssa_name_2 && ssa_name_2 == t1)
1482 return true;
1485 /* Compare if t1 and t2's def_stmts are identical. */
1486 if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1487 return true;
1488 else
1489 return false;
1492 /* Return true if E is predicted by one of loop heuristics. */
1494 static bool
1495 predicted_by_loop_heuristics_p (basic_block bb)
1497 struct edge_prediction *i;
1498 edge_prediction **preds = bb_predictions->get (bb);
1500 if (!preds)
1501 return false;
1503 for (i = *preds; i; i = i->ep_next)
1504 if (i->ep_predictor == PRED_LOOP_ITERATIONS_GUESSED
1505 || i->ep_predictor == PRED_LOOP_ITERATIONS_MAX
1506 || i->ep_predictor == PRED_LOOP_ITERATIONS
1507 || i->ep_predictor == PRED_LOOP_EXIT
1508 || i->ep_predictor == PRED_LOOP_EXIT_WITH_RECURSION
1509 || i->ep_predictor == PRED_LOOP_EXTRA_EXIT)
1510 return true;
1511 return false;
1514 /* Predict branch probability of BB when BB contains a branch that compares
1515 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1516 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1518 E.g.
1519 for (int i = 0; i < bound; i++) {
1520 if (i < bound - 2)
1521 computation_1();
1522 else
1523 computation_2();
1526 In this loop, we will predict the branch inside the loop to be taken. */
1528 static void
1529 predict_iv_comparison (struct loop *loop, basic_block bb,
1530 tree loop_bound_var,
1531 tree loop_iv_base_var,
1532 enum tree_code loop_bound_code,
1533 int loop_bound_step)
1535 gimple *stmt;
1536 tree compare_var, compare_base;
1537 enum tree_code compare_code;
1538 tree compare_step_var;
1539 edge then_edge;
1540 edge_iterator ei;
1542 if (predicted_by_loop_heuristics_p (bb))
1543 return;
1545 stmt = last_stmt (bb);
1546 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1547 return;
1548 if (!is_comparison_with_loop_invariant_p (as_a <gcond *> (stmt),
1549 loop, &compare_var,
1550 &compare_code,
1551 &compare_step_var,
1552 &compare_base))
1553 return;
1555 /* Find the taken edge. */
1556 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1557 if (then_edge->flags & EDGE_TRUE_VALUE)
1558 break;
1560 /* When comparing an IV to a loop invariant, NE is more likely to be
1561 taken while EQ is more likely to be not-taken. */
1562 if (compare_code == NE_EXPR)
1564 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1565 return;
1567 else if (compare_code == EQ_EXPR)
1569 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1570 return;
1573 if (!expr_coherent_p (loop_iv_base_var, compare_base))
1574 return;
1576 /* If loop bound, base and compare bound are all constants, we can
1577 calculate the probability directly. */
1578 if (tree_fits_shwi_p (loop_bound_var)
1579 && tree_fits_shwi_p (compare_var)
1580 && tree_fits_shwi_p (compare_base))
1582 int probability;
1583 bool overflow, overall_overflow = false;
1584 widest_int compare_count, tem;
1586 /* (loop_bound - base) / compare_step */
1587 tem = wi::sub (wi::to_widest (loop_bound_var),
1588 wi::to_widest (compare_base), SIGNED, &overflow);
1589 overall_overflow |= overflow;
1590 widest_int loop_count = wi::div_trunc (tem,
1591 wi::to_widest (compare_step_var),
1592 SIGNED, &overflow);
1593 overall_overflow |= overflow;
1595 if (!wi::neg_p (wi::to_widest (compare_step_var))
1596 ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1598 /* (loop_bound - compare_bound) / compare_step */
1599 tem = wi::sub (wi::to_widest (loop_bound_var),
1600 wi::to_widest (compare_var), SIGNED, &overflow);
1601 overall_overflow |= overflow;
1602 compare_count = wi::div_trunc (tem, wi::to_widest (compare_step_var),
1603 SIGNED, &overflow);
1604 overall_overflow |= overflow;
1606 else
1608 /* (compare_bound - base) / compare_step */
1609 tem = wi::sub (wi::to_widest (compare_var),
1610 wi::to_widest (compare_base), SIGNED, &overflow);
1611 overall_overflow |= overflow;
1612 compare_count = wi::div_trunc (tem, wi::to_widest (compare_step_var),
1613 SIGNED, &overflow);
1614 overall_overflow |= overflow;
1616 if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1617 ++compare_count;
1618 if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1619 ++loop_count;
1620 if (wi::neg_p (compare_count))
1621 compare_count = 0;
1622 if (wi::neg_p (loop_count))
1623 loop_count = 0;
1624 if (loop_count == 0)
1625 probability = 0;
1626 else if (wi::cmps (compare_count, loop_count) == 1)
1627 probability = REG_BR_PROB_BASE;
1628 else
1630 tem = compare_count * REG_BR_PROB_BASE;
1631 tem = wi::udiv_trunc (tem, loop_count);
1632 probability = tem.to_uhwi ();
1635 /* FIXME: The branch prediction seems broken. It has only 20% hitrate. */
1636 if (!overall_overflow)
1637 predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1639 return;
1642 if (expr_coherent_p (loop_bound_var, compare_var))
1644 if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1645 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1646 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1647 else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1648 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1649 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1650 else if (loop_bound_code == NE_EXPR)
1652 /* If the loop backedge condition is "(i != bound)", we do
1653 the comparison based on the step of IV:
1654 * step < 0 : backedge condition is like (i > bound)
1655 * step > 0 : backedge condition is like (i < bound) */
1656 gcc_assert (loop_bound_step != 0);
1657 if (loop_bound_step > 0
1658 && (compare_code == LT_EXPR
1659 || compare_code == LE_EXPR))
1660 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1661 else if (loop_bound_step < 0
1662 && (compare_code == GT_EXPR
1663 || compare_code == GE_EXPR))
1664 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1665 else
1666 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1668 else
1669 /* The branch is predicted not-taken if loop_bound_code is
1670 opposite with compare_code. */
1671 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1673 else if (expr_coherent_p (loop_iv_base_var, compare_var))
1675 /* For cases like:
1676 for (i = s; i < h; i++)
1677 if (i > s + 2) ....
1678 The branch should be predicted taken. */
1679 if (loop_bound_step > 0
1680 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1681 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1682 else if (loop_bound_step < 0
1683 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1684 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1685 else
1686 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1690 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1691 exits are resulted from short-circuit conditions that will generate an
1692 if_tmp. E.g.:
1694 if (foo() || global > 10)
1695 break;
1697 This will be translated into:
1699 BB3:
1700 loop header...
1701 BB4:
1702 if foo() goto BB6 else goto BB5
1703 BB5:
1704 if global > 10 goto BB6 else goto BB7
1705 BB6:
1706 goto BB7
1707 BB7:
1708 iftmp = (PHI 0(BB5), 1(BB6))
1709 if iftmp == 1 goto BB8 else goto BB3
1710 BB8:
1711 outside of the loop...
1713 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1714 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1715 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1716 exits to predict them using PRED_LOOP_EXTRA_EXIT. */
1718 static void
1719 predict_extra_loop_exits (edge exit_edge)
1721 unsigned i;
1722 bool check_value_one;
1723 gimple *lhs_def_stmt;
1724 gphi *phi_stmt;
1725 tree cmp_rhs, cmp_lhs;
1726 gimple *last;
1727 gcond *cmp_stmt;
1729 last = last_stmt (exit_edge->src);
1730 if (!last)
1731 return;
1732 cmp_stmt = dyn_cast <gcond *> (last);
1733 if (!cmp_stmt)
1734 return;
1736 cmp_rhs = gimple_cond_rhs (cmp_stmt);
1737 cmp_lhs = gimple_cond_lhs (cmp_stmt);
1738 if (!TREE_CONSTANT (cmp_rhs)
1739 || !(integer_zerop (cmp_rhs) || integer_onep (cmp_rhs)))
1740 return;
1741 if (TREE_CODE (cmp_lhs) != SSA_NAME)
1742 return;
1744 /* If check_value_one is true, only the phi_args with value '1' will lead
1745 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1746 loop exit. */
1747 check_value_one = (((integer_onep (cmp_rhs))
1748 ^ (gimple_cond_code (cmp_stmt) == EQ_EXPR))
1749 ^ ((exit_edge->flags & EDGE_TRUE_VALUE) != 0));
1751 lhs_def_stmt = SSA_NAME_DEF_STMT (cmp_lhs);
1752 if (!lhs_def_stmt)
1753 return;
1755 phi_stmt = dyn_cast <gphi *> (lhs_def_stmt);
1756 if (!phi_stmt)
1757 return;
1759 for (i = 0; i < gimple_phi_num_args (phi_stmt); i++)
1761 edge e1;
1762 edge_iterator ei;
1763 tree val = gimple_phi_arg_def (phi_stmt, i);
1764 edge e = gimple_phi_arg_edge (phi_stmt, i);
1766 if (!TREE_CONSTANT (val) || !(integer_zerop (val) || integer_onep (val)))
1767 continue;
1768 if ((check_value_one ^ integer_onep (val)) == 1)
1769 continue;
1770 if (EDGE_COUNT (e->src->succs) != 1)
1772 predict_paths_leading_to_edge (e, PRED_LOOP_EXTRA_EXIT, NOT_TAKEN);
1773 continue;
1776 FOR_EACH_EDGE (e1, ei, e->src->preds)
1777 predict_paths_leading_to_edge (e1, PRED_LOOP_EXTRA_EXIT, NOT_TAKEN);
1782 /* Predict edge probabilities by exploiting loop structure. */
1784 static void
1785 predict_loops (void)
1787 struct loop *loop;
1788 basic_block bb;
1789 hash_set <struct loop *> with_recursion(10);
1791 FOR_EACH_BB_FN (bb, cfun)
1793 gimple_stmt_iterator gsi;
1794 tree decl;
1796 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1797 if (is_gimple_call (gsi_stmt (gsi))
1798 && (decl = gimple_call_fndecl (gsi_stmt (gsi))) != NULL
1799 && recursive_call_p (current_function_decl, decl))
1801 loop = bb->loop_father;
1802 while (loop && !with_recursion.add (loop))
1803 loop = loop_outer (loop);
1807 /* Try to predict out blocks in a loop that are not part of a
1808 natural loop. */
1809 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
1811 basic_block bb, *bbs;
1812 unsigned j, n_exits = 0;
1813 vec<edge> exits;
1814 struct tree_niter_desc niter_desc;
1815 edge ex;
1816 struct nb_iter_bound *nb_iter;
1817 enum tree_code loop_bound_code = ERROR_MARK;
1818 tree loop_bound_step = NULL;
1819 tree loop_bound_var = NULL;
1820 tree loop_iv_base = NULL;
1821 gcond *stmt = NULL;
1822 bool recursion = with_recursion.contains (loop);
1824 exits = get_loop_exit_edges (loop);
1825 FOR_EACH_VEC_ELT (exits, j, ex)
1826 if (!unlikely_executed_edge_p (ex) && !(ex->flags & EDGE_ABNORMAL_CALL))
1827 n_exits ++;
1828 if (!n_exits)
1830 exits.release ();
1831 continue;
1834 if (dump_file && (dump_flags & TDF_DETAILS))
1835 fprintf (dump_file, "Predicting loop %i%s with %i exits.\n",
1836 loop->num, recursion ? " (with recursion)":"", n_exits);
1837 if (dump_file && (dump_flags & TDF_DETAILS)
1838 && max_loop_iterations_int (loop) >= 0)
1840 fprintf (dump_file,
1841 "Loop %d iterates at most %i times.\n", loop->num,
1842 (int)max_loop_iterations_int (loop));
1844 if (dump_file && (dump_flags & TDF_DETAILS)
1845 && likely_max_loop_iterations_int (loop) >= 0)
1847 fprintf (dump_file, "Loop %d likely iterates at most %i times.\n",
1848 loop->num, (int)likely_max_loop_iterations_int (loop));
1851 FOR_EACH_VEC_ELT (exits, j, ex)
1853 tree niter = NULL;
1854 HOST_WIDE_INT nitercst;
1855 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
1856 int probability;
1857 enum br_predictor predictor;
1858 widest_int nit;
1860 if (unlikely_executed_edge_p (ex)
1861 || (ex->flags & EDGE_ABNORMAL_CALL))
1862 continue;
1863 /* Loop heuristics do not expect exit conditional to be inside
1864 inner loop. We predict from innermost to outermost loop. */
1865 if (predicted_by_loop_heuristics_p (ex->src))
1867 if (dump_file && (dump_flags & TDF_DETAILS))
1868 fprintf (dump_file, "Skipping exit %i->%i because "
1869 "it is already predicted.\n",
1870 ex->src->index, ex->dest->index);
1871 continue;
1873 predict_extra_loop_exits (ex);
1875 if (number_of_iterations_exit (loop, ex, &niter_desc, false, false))
1876 niter = niter_desc.niter;
1877 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
1878 niter = loop_niter_by_eval (loop, ex);
1879 if (dump_file && (dump_flags & TDF_DETAILS)
1880 && TREE_CODE (niter) == INTEGER_CST)
1882 fprintf (dump_file, "Exit %i->%i %d iterates ",
1883 ex->src->index, ex->dest->index,
1884 loop->num);
1885 print_generic_expr (dump_file, niter, TDF_SLIM);
1886 fprintf (dump_file, " times.\n");
1889 if (TREE_CODE (niter) == INTEGER_CST)
1891 if (tree_fits_uhwi_p (niter)
1892 && max
1893 && compare_tree_int (niter, max - 1) == -1)
1894 nitercst = tree_to_uhwi (niter) + 1;
1895 else
1896 nitercst = max;
1897 predictor = PRED_LOOP_ITERATIONS;
1899 /* If we have just one exit and we can derive some information about
1900 the number of iterations of the loop from the statements inside
1901 the loop, use it to predict this exit. */
1902 else if (n_exits == 1
1903 && estimated_stmt_executions (loop, &nit))
1905 if (wi::gtu_p (nit, max))
1906 nitercst = max;
1907 else
1908 nitercst = nit.to_shwi ();
1909 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1911 /* If we have likely upper bound, trust it for very small iteration
1912 counts. Such loops would otherwise get mispredicted by standard
1913 LOOP_EXIT heuristics. */
1914 else if (n_exits == 1
1915 && likely_max_stmt_executions (loop, &nit)
1916 && wi::ltu_p (nit,
1917 RDIV (REG_BR_PROB_BASE,
1918 REG_BR_PROB_BASE
1919 - predictor_info
1920 [recursion
1921 ? PRED_LOOP_EXIT_WITH_RECURSION
1922 : PRED_LOOP_EXIT].hitrate)))
1924 nitercst = nit.to_shwi ();
1925 predictor = PRED_LOOP_ITERATIONS_MAX;
1927 else
1929 if (dump_file && (dump_flags & TDF_DETAILS))
1930 fprintf (dump_file, "Nothing known about exit %i->%i.\n",
1931 ex->src->index, ex->dest->index);
1932 continue;
1935 if (dump_file && (dump_flags & TDF_DETAILS))
1936 fprintf (dump_file, "Recording prediction to %i iterations by %s.\n",
1937 (int)nitercst, predictor_info[predictor].name);
1938 /* If the prediction for number of iterations is zero, do not
1939 predict the exit edges. */
1940 if (nitercst == 0)
1941 continue;
1943 probability = RDIV (REG_BR_PROB_BASE, nitercst);
1944 predict_edge (ex, predictor, probability);
1946 exits.release ();
1948 /* Find information about loop bound variables. */
1949 for (nb_iter = loop->bounds; nb_iter;
1950 nb_iter = nb_iter->next)
1951 if (nb_iter->stmt
1952 && gimple_code (nb_iter->stmt) == GIMPLE_COND)
1954 stmt = as_a <gcond *> (nb_iter->stmt);
1955 break;
1957 if (!stmt && last_stmt (loop->header)
1958 && gimple_code (last_stmt (loop->header)) == GIMPLE_COND)
1959 stmt = as_a <gcond *> (last_stmt (loop->header));
1960 if (stmt)
1961 is_comparison_with_loop_invariant_p (stmt, loop,
1962 &loop_bound_var,
1963 &loop_bound_code,
1964 &loop_bound_step,
1965 &loop_iv_base);
1967 bbs = get_loop_body (loop);
1969 for (j = 0; j < loop->num_nodes; j++)
1971 edge e;
1972 edge_iterator ei;
1974 bb = bbs[j];
1976 /* Bypass loop heuristics on continue statement. These
1977 statements construct loops via "non-loop" constructs
1978 in the source language and are better to be handled
1979 separately. */
1980 if (predicted_by_p (bb, PRED_CONTINUE))
1982 if (dump_file && (dump_flags & TDF_DETAILS))
1983 fprintf (dump_file, "BB %i predicted by continue.\n",
1984 bb->index);
1985 continue;
1988 /* If we already used more reliable loop exit predictors, do not
1989 bother with PRED_LOOP_EXIT. */
1990 if (!predicted_by_loop_heuristics_p (bb))
1992 /* For loop with many exits we don't want to predict all exits
1993 with the pretty large probability, because if all exits are
1994 considered in row, the loop would be predicted to iterate
1995 almost never. The code to divide probability by number of
1996 exits is very rough. It should compute the number of exits
1997 taken in each patch through function (not the overall number
1998 of exits that might be a lot higher for loops with wide switch
1999 statements in them) and compute n-th square root.
2001 We limit the minimal probability by 2% to avoid
2002 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
2003 as this was causing regression in perl benchmark containing such
2004 a wide loop. */
2006 int probability = ((REG_BR_PROB_BASE
2007 - predictor_info
2008 [recursion
2009 ? PRED_LOOP_EXIT_WITH_RECURSION
2010 : PRED_LOOP_EXIT].hitrate)
2011 / n_exits);
2012 if (probability < HITRATE (2))
2013 probability = HITRATE (2);
2014 FOR_EACH_EDGE (e, ei, bb->succs)
2015 if (e->dest->index < NUM_FIXED_BLOCKS
2016 || !flow_bb_inside_loop_p (loop, e->dest))
2018 if (dump_file && (dump_flags & TDF_DETAILS))
2019 fprintf (dump_file,
2020 "Predicting exit %i->%i with prob %i.\n",
2021 e->src->index, e->dest->index, probability);
2022 predict_edge (e,
2023 recursion ? PRED_LOOP_EXIT_WITH_RECURSION
2024 : PRED_LOOP_EXIT, probability);
2027 if (loop_bound_var)
2028 predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
2029 loop_bound_code,
2030 tree_to_shwi (loop_bound_step));
2033 /* In the following code
2034 for (loop1)
2035 if (cond)
2036 for (loop2)
2037 body;
2038 guess that cond is unlikely. */
2039 if (loop_outer (loop)->num)
2041 basic_block bb = NULL;
2042 edge preheader_edge = loop_preheader_edge (loop);
2044 if (single_pred_p (preheader_edge->src)
2045 && single_succ_p (preheader_edge->src))
2046 preheader_edge = single_pred_edge (preheader_edge->src);
2048 gimple *stmt = last_stmt (preheader_edge->src);
2049 /* Pattern match fortran loop preheader:
2050 _16 = BUILTIN_EXPECT (_15, 1, PRED_FORTRAN_LOOP_PREHEADER);
2051 _17 = (logical(kind=4)) _16;
2052 if (_17 != 0)
2053 goto <bb 11>;
2054 else
2055 goto <bb 13>;
2057 Loop guard branch prediction says nothing about duplicated loop
2058 headers produced by fortran frontend and in this case we want
2059 to predict paths leading to this preheader. */
2061 if (stmt
2062 && gimple_code (stmt) == GIMPLE_COND
2063 && gimple_cond_code (stmt) == NE_EXPR
2064 && TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME
2065 && integer_zerop (gimple_cond_rhs (stmt)))
2067 gimple *call_stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
2068 if (gimple_code (call_stmt) == GIMPLE_ASSIGN
2069 && gimple_expr_code (call_stmt) == NOP_EXPR
2070 && TREE_CODE (gimple_assign_rhs1 (call_stmt)) == SSA_NAME)
2071 call_stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (call_stmt));
2072 if (gimple_call_internal_p (call_stmt, IFN_BUILTIN_EXPECT)
2073 && TREE_CODE (gimple_call_arg (call_stmt, 2)) == INTEGER_CST
2074 && tree_fits_uhwi_p (gimple_call_arg (call_stmt, 2))
2075 && tree_to_uhwi (gimple_call_arg (call_stmt, 2))
2076 == PRED_FORTRAN_LOOP_PREHEADER)
2077 bb = preheader_edge->src;
2079 if (!bb)
2081 if (!dominated_by_p (CDI_DOMINATORS,
2082 loop_outer (loop)->latch, loop->header))
2083 predict_paths_leading_to_edge (loop_preheader_edge (loop),
2084 recursion
2085 ? PRED_LOOP_GUARD_WITH_RECURSION
2086 : PRED_LOOP_GUARD,
2087 NOT_TAKEN,
2088 loop_outer (loop));
2090 else
2092 if (!dominated_by_p (CDI_DOMINATORS,
2093 loop_outer (loop)->latch, bb))
2094 predict_paths_leading_to (bb,
2095 recursion
2096 ? PRED_LOOP_GUARD_WITH_RECURSION
2097 : PRED_LOOP_GUARD,
2098 NOT_TAKEN,
2099 loop_outer (loop));
2103 /* Free basic blocks from get_loop_body. */
2104 free (bbs);
2108 /* Attempt to predict probabilities of BB outgoing edges using local
2109 properties. */
2110 static void
2111 bb_estimate_probability_locally (basic_block bb)
2113 rtx_insn *last_insn = BB_END (bb);
2114 rtx cond;
2116 if (! can_predict_insn_p (last_insn))
2117 return;
2118 cond = get_condition (last_insn, NULL, false, false);
2119 if (! cond)
2120 return;
2122 /* Try "pointer heuristic."
2123 A comparison ptr == 0 is predicted as false.
2124 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2125 if (COMPARISON_P (cond)
2126 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
2127 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
2129 if (GET_CODE (cond) == EQ)
2130 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
2131 else if (GET_CODE (cond) == NE)
2132 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
2134 else
2136 /* Try "opcode heuristic."
2137 EQ tests are usually false and NE tests are usually true. Also,
2138 most quantities are positive, so we can make the appropriate guesses
2139 about signed comparisons against zero. */
2140 switch (GET_CODE (cond))
2142 case CONST_INT:
2143 /* Unconditional branch. */
2144 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
2145 cond == const0_rtx ? NOT_TAKEN : TAKEN);
2146 break;
2148 case EQ:
2149 case UNEQ:
2150 /* Floating point comparisons appears to behave in a very
2151 unpredictable way because of special role of = tests in
2152 FP code. */
2153 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
2155 /* Comparisons with 0 are often used for booleans and there is
2156 nothing useful to predict about them. */
2157 else if (XEXP (cond, 1) == const0_rtx
2158 || XEXP (cond, 0) == const0_rtx)
2160 else
2161 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
2162 break;
2164 case NE:
2165 case LTGT:
2166 /* Floating point comparisons appears to behave in a very
2167 unpredictable way because of special role of = tests in
2168 FP code. */
2169 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
2171 /* Comparisons with 0 are often used for booleans and there is
2172 nothing useful to predict about them. */
2173 else if (XEXP (cond, 1) == const0_rtx
2174 || XEXP (cond, 0) == const0_rtx)
2176 else
2177 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
2178 break;
2180 case ORDERED:
2181 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
2182 break;
2184 case UNORDERED:
2185 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
2186 break;
2188 case LE:
2189 case LT:
2190 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
2191 || XEXP (cond, 1) == constm1_rtx)
2192 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
2193 break;
2195 case GE:
2196 case GT:
2197 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
2198 || XEXP (cond, 1) == constm1_rtx)
2199 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
2200 break;
2202 default:
2203 break;
2207 /* Set edge->probability for each successor edge of BB. */
2208 void
2209 guess_outgoing_edge_probabilities (basic_block bb)
2211 bb_estimate_probability_locally (bb);
2212 combine_predictions_for_insn (BB_END (bb), bb);
2215 static tree expr_expected_value (tree, bitmap, enum br_predictor *predictor);
2217 /* Helper function for expr_expected_value. */
2219 static tree
2220 expr_expected_value_1 (tree type, tree op0, enum tree_code code,
2221 tree op1, bitmap visited, enum br_predictor *predictor)
2223 gimple *def;
2225 if (predictor)
2226 *predictor = PRED_UNCONDITIONAL;
2228 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
2230 if (TREE_CONSTANT (op0))
2231 return op0;
2233 if (code == IMAGPART_EXPR)
2235 if (TREE_CODE (TREE_OPERAND (op0, 0)) == SSA_NAME)
2237 def = SSA_NAME_DEF_STMT (TREE_OPERAND (op0, 0));
2238 if (is_gimple_call (def)
2239 && gimple_call_internal_p (def)
2240 && (gimple_call_internal_fn (def)
2241 == IFN_ATOMIC_COMPARE_EXCHANGE))
2243 /* Assume that any given atomic operation has low contention,
2244 and thus the compare-and-swap operation succeeds. */
2245 if (predictor)
2246 *predictor = PRED_COMPARE_AND_SWAP;
2247 return build_one_cst (TREE_TYPE (op0));
2252 if (code != SSA_NAME)
2253 return NULL_TREE;
2255 def = SSA_NAME_DEF_STMT (op0);
2257 /* If we were already here, break the infinite cycle. */
2258 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
2259 return NULL;
2261 if (gimple_code (def) == GIMPLE_PHI)
2263 /* All the arguments of the PHI node must have the same constant
2264 length. */
2265 int i, n = gimple_phi_num_args (def);
2266 tree val = NULL, new_val;
2268 for (i = 0; i < n; i++)
2270 tree arg = PHI_ARG_DEF (def, i);
2271 enum br_predictor predictor2;
2273 /* If this PHI has itself as an argument, we cannot
2274 determine the string length of this argument. However,
2275 if we can find an expected constant value for the other
2276 PHI args then we can still be sure that this is
2277 likely a constant. So be optimistic and just
2278 continue with the next argument. */
2279 if (arg == PHI_RESULT (def))
2280 continue;
2282 new_val = expr_expected_value (arg, visited, &predictor2);
2284 /* It is difficult to combine value predictors. Simply assume
2285 that later predictor is weaker and take its prediction. */
2286 if (predictor && *predictor < predictor2)
2287 *predictor = predictor2;
2288 if (!new_val)
2289 return NULL;
2290 if (!val)
2291 val = new_val;
2292 else if (!operand_equal_p (val, new_val, false))
2293 return NULL;
2295 return val;
2297 if (is_gimple_assign (def))
2299 if (gimple_assign_lhs (def) != op0)
2300 return NULL;
2302 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
2303 gimple_assign_rhs1 (def),
2304 gimple_assign_rhs_code (def),
2305 gimple_assign_rhs2 (def),
2306 visited, predictor);
2309 if (is_gimple_call (def))
2311 tree decl = gimple_call_fndecl (def);
2312 if (!decl)
2314 if (gimple_call_internal_p (def)
2315 && gimple_call_internal_fn (def) == IFN_BUILTIN_EXPECT)
2317 gcc_assert (gimple_call_num_args (def) == 3);
2318 tree val = gimple_call_arg (def, 0);
2319 if (TREE_CONSTANT (val))
2320 return val;
2321 if (predictor)
2323 tree val2 = gimple_call_arg (def, 2);
2324 gcc_assert (TREE_CODE (val2) == INTEGER_CST
2325 && tree_fits_uhwi_p (val2)
2326 && tree_to_uhwi (val2) < END_PREDICTORS);
2327 *predictor = (enum br_predictor) tree_to_uhwi (val2);
2329 return gimple_call_arg (def, 1);
2331 return NULL;
2333 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
2334 switch (DECL_FUNCTION_CODE (decl))
2336 case BUILT_IN_EXPECT:
2338 tree val;
2339 if (gimple_call_num_args (def) != 2)
2340 return NULL;
2341 val = gimple_call_arg (def, 0);
2342 if (TREE_CONSTANT (val))
2343 return val;
2344 if (predictor)
2345 *predictor = PRED_BUILTIN_EXPECT;
2346 return gimple_call_arg (def, 1);
2349 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
2350 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
2351 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
2352 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
2353 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
2354 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
2355 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
2356 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
2357 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
2358 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
2359 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
2360 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
2361 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
2362 /* Assume that any given atomic operation has low contention,
2363 and thus the compare-and-swap operation succeeds. */
2364 if (predictor)
2365 *predictor = PRED_COMPARE_AND_SWAP;
2366 return boolean_true_node;
2367 default:
2368 break;
2372 return NULL;
2375 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
2377 tree res;
2378 enum br_predictor predictor2;
2379 op0 = expr_expected_value (op0, visited, predictor);
2380 if (!op0)
2381 return NULL;
2382 op1 = expr_expected_value (op1, visited, &predictor2);
2383 if (predictor && *predictor < predictor2)
2384 *predictor = predictor2;
2385 if (!op1)
2386 return NULL;
2387 res = fold_build2 (code, type, op0, op1);
2388 if (TREE_CONSTANT (res))
2389 return res;
2390 return NULL;
2392 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
2394 tree res;
2395 op0 = expr_expected_value (op0, visited, predictor);
2396 if (!op0)
2397 return NULL;
2398 res = fold_build1 (code, type, op0);
2399 if (TREE_CONSTANT (res))
2400 return res;
2401 return NULL;
2403 return NULL;
2406 /* Return constant EXPR will likely have at execution time, NULL if unknown.
2407 The function is used by builtin_expect branch predictor so the evidence
2408 must come from this construct and additional possible constant folding.
2410 We may want to implement more involved value guess (such as value range
2411 propagation based prediction), but such tricks shall go to new
2412 implementation. */
2414 static tree
2415 expr_expected_value (tree expr, bitmap visited,
2416 enum br_predictor *predictor)
2418 enum tree_code code;
2419 tree op0, op1;
2421 if (TREE_CONSTANT (expr))
2423 if (predictor)
2424 *predictor = PRED_UNCONDITIONAL;
2425 return expr;
2428 extract_ops_from_tree (expr, &code, &op0, &op1);
2429 return expr_expected_value_1 (TREE_TYPE (expr),
2430 op0, code, op1, visited, predictor);
2433 /* Predict using opcode of the last statement in basic block. */
2434 static void
2435 tree_predict_by_opcode (basic_block bb)
2437 gimple *stmt = last_stmt (bb);
2438 edge then_edge;
2439 tree op0, op1;
2440 tree type;
2441 tree val;
2442 enum tree_code cmp;
2443 edge_iterator ei;
2444 enum br_predictor predictor;
2446 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
2447 return;
2448 FOR_EACH_EDGE (then_edge, ei, bb->succs)
2449 if (then_edge->flags & EDGE_TRUE_VALUE)
2450 break;
2451 op0 = gimple_cond_lhs (stmt);
2452 op1 = gimple_cond_rhs (stmt);
2453 cmp = gimple_cond_code (stmt);
2454 type = TREE_TYPE (op0);
2455 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, auto_bitmap (),
2456 &predictor);
2457 if (val && TREE_CODE (val) == INTEGER_CST)
2459 if (predictor == PRED_BUILTIN_EXPECT)
2461 int percent = PARAM_VALUE (BUILTIN_EXPECT_PROBABILITY);
2463 gcc_assert (percent >= 0 && percent <= 100);
2464 if (integer_zerop (val))
2465 percent = 100 - percent;
2466 predict_edge (then_edge, PRED_BUILTIN_EXPECT, HITRATE (percent));
2468 else
2469 predict_edge_def (then_edge, predictor,
2470 integer_zerop (val) ? NOT_TAKEN : TAKEN);
2472 /* Try "pointer heuristic."
2473 A comparison ptr == 0 is predicted as false.
2474 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2475 if (POINTER_TYPE_P (type))
2477 if (cmp == EQ_EXPR)
2478 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
2479 else if (cmp == NE_EXPR)
2480 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
2482 else
2484 /* Try "opcode heuristic."
2485 EQ tests are usually false and NE tests are usually true. Also,
2486 most quantities are positive, so we can make the appropriate guesses
2487 about signed comparisons against zero. */
2488 switch (cmp)
2490 case EQ_EXPR:
2491 case UNEQ_EXPR:
2492 /* Floating point comparisons appears to behave in a very
2493 unpredictable way because of special role of = tests in
2494 FP code. */
2495 if (FLOAT_TYPE_P (type))
2497 /* Comparisons with 0 are often used for booleans and there is
2498 nothing useful to predict about them. */
2499 else if (integer_zerop (op0) || integer_zerop (op1))
2501 else
2502 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
2503 break;
2505 case NE_EXPR:
2506 case LTGT_EXPR:
2507 /* Floating point comparisons appears to behave in a very
2508 unpredictable way because of special role of = tests in
2509 FP code. */
2510 if (FLOAT_TYPE_P (type))
2512 /* Comparisons with 0 are often used for booleans and there is
2513 nothing useful to predict about them. */
2514 else if (integer_zerop (op0)
2515 || integer_zerop (op1))
2517 else
2518 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
2519 break;
2521 case ORDERED_EXPR:
2522 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
2523 break;
2525 case UNORDERED_EXPR:
2526 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
2527 break;
2529 case LE_EXPR:
2530 case LT_EXPR:
2531 if (integer_zerop (op1)
2532 || integer_onep (op1)
2533 || integer_all_onesp (op1)
2534 || real_zerop (op1)
2535 || real_onep (op1)
2536 || real_minus_onep (op1))
2537 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
2538 break;
2540 case GE_EXPR:
2541 case GT_EXPR:
2542 if (integer_zerop (op1)
2543 || integer_onep (op1)
2544 || integer_all_onesp (op1)
2545 || real_zerop (op1)
2546 || real_onep (op1)
2547 || real_minus_onep (op1))
2548 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
2549 break;
2551 default:
2552 break;
2556 /* Returns TRUE if the STMT is exit(0) like statement. */
2558 static bool
2559 is_exit_with_zero_arg (const gimple *stmt)
2561 /* This is not exit, _exit or _Exit. */
2562 if (!gimple_call_builtin_p (stmt, BUILT_IN_EXIT)
2563 && !gimple_call_builtin_p (stmt, BUILT_IN__EXIT)
2564 && !gimple_call_builtin_p (stmt, BUILT_IN__EXIT2))
2565 return false;
2567 /* Argument is an interger zero. */
2568 return integer_zerop (gimple_call_arg (stmt, 0));
2571 /* Try to guess whether the value of return means error code. */
2573 static enum br_predictor
2574 return_prediction (tree val, enum prediction *prediction)
2576 /* VOID. */
2577 if (!val)
2578 return PRED_NO_PREDICTION;
2579 /* Different heuristics for pointers and scalars. */
2580 if (POINTER_TYPE_P (TREE_TYPE (val)))
2582 /* NULL is usually not returned. */
2583 if (integer_zerop (val))
2585 *prediction = NOT_TAKEN;
2586 return PRED_NULL_RETURN;
2589 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
2591 /* Negative return values are often used to indicate
2592 errors. */
2593 if (TREE_CODE (val) == INTEGER_CST
2594 && tree_int_cst_sgn (val) < 0)
2596 *prediction = NOT_TAKEN;
2597 return PRED_NEGATIVE_RETURN;
2599 /* Constant return values seems to be commonly taken.
2600 Zero/one often represent booleans so exclude them from the
2601 heuristics. */
2602 if (TREE_CONSTANT (val)
2603 && (!integer_zerop (val) && !integer_onep (val)))
2605 *prediction = NOT_TAKEN;
2606 return PRED_CONST_RETURN;
2609 return PRED_NO_PREDICTION;
2612 /* Find the basic block with return expression and look up for possible
2613 return value trying to apply RETURN_PREDICTION heuristics. */
2614 static void
2615 apply_return_prediction (void)
2617 greturn *return_stmt = NULL;
2618 tree return_val;
2619 edge e;
2620 gphi *phi;
2621 int phi_num_args, i;
2622 enum br_predictor pred;
2623 enum prediction direction;
2624 edge_iterator ei;
2626 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2628 gimple *last = last_stmt (e->src);
2629 if (last
2630 && gimple_code (last) == GIMPLE_RETURN)
2632 return_stmt = as_a <greturn *> (last);
2633 break;
2636 if (!e)
2637 return;
2638 return_val = gimple_return_retval (return_stmt);
2639 if (!return_val)
2640 return;
2641 if (TREE_CODE (return_val) != SSA_NAME
2642 || !SSA_NAME_DEF_STMT (return_val)
2643 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
2644 return;
2645 phi = as_a <gphi *> (SSA_NAME_DEF_STMT (return_val));
2646 phi_num_args = gimple_phi_num_args (phi);
2647 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
2649 /* Avoid the degenerate case where all return values form the function
2650 belongs to same category (ie they are all positive constants)
2651 so we can hardly say something about them. */
2652 for (i = 1; i < phi_num_args; i++)
2653 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
2654 break;
2655 if (i != phi_num_args)
2656 for (i = 0; i < phi_num_args; i++)
2658 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
2659 if (pred != PRED_NO_PREDICTION)
2660 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
2661 direction);
2665 /* Look for basic block that contains unlikely to happen events
2666 (such as noreturn calls) and mark all paths leading to execution
2667 of this basic blocks as unlikely. */
2669 static void
2670 tree_bb_level_predictions (void)
2672 basic_block bb;
2673 bool has_return_edges = false;
2674 edge e;
2675 edge_iterator ei;
2677 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2678 if (!unlikely_executed_edge_p (e) && !(e->flags & EDGE_ABNORMAL_CALL))
2680 has_return_edges = true;
2681 break;
2684 apply_return_prediction ();
2686 FOR_EACH_BB_FN (bb, cfun)
2688 gimple_stmt_iterator gsi;
2690 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2692 gimple *stmt = gsi_stmt (gsi);
2693 tree decl;
2695 if (is_gimple_call (stmt))
2697 if (gimple_call_noreturn_p (stmt)
2698 && has_return_edges
2699 && !is_exit_with_zero_arg (stmt))
2700 predict_paths_leading_to (bb, PRED_NORETURN,
2701 NOT_TAKEN);
2702 decl = gimple_call_fndecl (stmt);
2703 if (decl
2704 && lookup_attribute ("cold",
2705 DECL_ATTRIBUTES (decl)))
2706 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
2707 NOT_TAKEN);
2708 if (decl && recursive_call_p (current_function_decl, decl))
2709 predict_paths_leading_to (bb, PRED_RECURSIVE_CALL,
2710 NOT_TAKEN);
2712 else if (gimple_code (stmt) == GIMPLE_PREDICT)
2714 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
2715 gimple_predict_outcome (stmt));
2716 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2717 hints to callers. */
2723 /* Callback for hash_map::traverse, asserts that the pointer map is
2724 empty. */
2726 bool
2727 assert_is_empty (const_basic_block const &, edge_prediction *const &value,
2728 void *)
2730 gcc_assert (!value);
2731 return false;
2734 /* Predict branch probabilities and estimate profile for basic block BB.
2735 When LOCAL_ONLY is set do not use any global properties of CFG. */
2737 static void
2738 tree_estimate_probability_bb (basic_block bb, bool local_only)
2740 edge e;
2741 edge_iterator ei;
2742 gimple *last;
2744 FOR_EACH_EDGE (e, ei, bb->succs)
2746 /* Predict edges to user labels with attributes. */
2747 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
2749 gimple_stmt_iterator gi;
2750 for (gi = gsi_start_bb (e->dest); !gsi_end_p (gi); gsi_next (&gi))
2752 glabel *label_stmt = dyn_cast <glabel *> (gsi_stmt (gi));
2753 tree decl;
2755 if (!label_stmt)
2756 break;
2757 decl = gimple_label_label (label_stmt);
2758 if (DECL_ARTIFICIAL (decl))
2759 continue;
2761 /* Finally, we have a user-defined label. */
2762 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl)))
2763 predict_edge_def (e, PRED_COLD_LABEL, NOT_TAKEN);
2764 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl)))
2765 predict_edge_def (e, PRED_HOT_LABEL, TAKEN);
2769 /* Predict early returns to be probable, as we've already taken
2770 care for error returns and other cases are often used for
2771 fast paths through function.
2773 Since we've already removed the return statements, we are
2774 looking for CFG like:
2776 if (conditional)
2779 goto return_block
2781 some other blocks
2782 return_block:
2783 return_stmt. */
2784 if (e->dest != bb->next_bb
2785 && e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
2786 && single_succ_p (e->dest)
2787 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR_FOR_FN (cfun)
2788 && (last = last_stmt (e->dest)) != NULL
2789 && gimple_code (last) == GIMPLE_RETURN)
2791 edge e1;
2792 edge_iterator ei1;
2794 if (single_succ_p (bb))
2796 FOR_EACH_EDGE (e1, ei1, bb->preds)
2797 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
2798 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
2799 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
2800 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2802 else
2803 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
2804 && !predicted_by_p (e->src, PRED_CONST_RETURN)
2805 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
2806 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2809 /* Look for block we are guarding (ie we dominate it,
2810 but it doesn't postdominate us). */
2811 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun) && e->dest != bb
2812 && !local_only
2813 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
2814 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
2816 gimple_stmt_iterator bi;
2818 /* The call heuristic claims that a guarded function call
2819 is improbable. This is because such calls are often used
2820 to signal exceptional situations such as printing error
2821 messages. */
2822 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
2823 gsi_next (&bi))
2825 gimple *stmt = gsi_stmt (bi);
2826 if (is_gimple_call (stmt)
2827 && !gimple_inexpensive_call_p (as_a <gcall *> (stmt))
2828 /* Constant and pure calls are hardly used to signalize
2829 something exceptional. */
2830 && gimple_has_side_effects (stmt))
2832 if (gimple_call_fndecl (stmt))
2833 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
2834 else if (virtual_method_call_p (gimple_call_fn (stmt)))
2835 predict_edge_def (e, PRED_POLYMORPHIC_CALL, NOT_TAKEN);
2836 else
2837 predict_edge_def (e, PRED_INDIR_CALL, TAKEN);
2838 break;
2843 tree_predict_by_opcode (bb);
2846 /* Predict branch probabilities and estimate profile of the tree CFG.
2847 This function can be called from the loop optimizers to recompute
2848 the profile information.
2849 If DRY_RUN is set, do not modify CFG and only produce dump files. */
2851 void
2852 tree_estimate_probability (bool dry_run)
2854 basic_block bb;
2856 add_noreturn_fake_exit_edges ();
2857 connect_infinite_loops_to_exit ();
2858 /* We use loop_niter_by_eval, which requires that the loops have
2859 preheaders. */
2860 create_preheaders (CP_SIMPLE_PREHEADERS);
2861 calculate_dominance_info (CDI_POST_DOMINATORS);
2863 bb_predictions = new hash_map<const_basic_block, edge_prediction *>;
2864 tree_bb_level_predictions ();
2865 record_loop_exits ();
2867 if (number_of_loops (cfun) > 1)
2868 predict_loops ();
2870 FOR_EACH_BB_FN (bb, cfun)
2871 tree_estimate_probability_bb (bb, false);
2873 FOR_EACH_BB_FN (bb, cfun)
2874 combine_predictions_for_bb (bb, dry_run);
2876 if (flag_checking)
2877 bb_predictions->traverse<void *, assert_is_empty> (NULL);
2879 delete bb_predictions;
2880 bb_predictions = NULL;
2882 if (!dry_run)
2883 estimate_bb_frequencies (false);
2884 free_dominance_info (CDI_POST_DOMINATORS);
2885 remove_fake_exit_edges ();
2888 /* Set edge->probability for each successor edge of BB. */
2889 void
2890 tree_guess_outgoing_edge_probabilities (basic_block bb)
2892 bb_predictions = new hash_map<const_basic_block, edge_prediction *>;
2893 tree_estimate_probability_bb (bb, true);
2894 combine_predictions_for_bb (bb, false);
2895 if (flag_checking)
2896 bb_predictions->traverse<void *, assert_is_empty> (NULL);
2897 delete bb_predictions;
2898 bb_predictions = NULL;
2901 /* Predict edges to successors of CUR whose sources are not postdominated by
2902 BB by PRED and recurse to all postdominators. */
2904 static void
2905 predict_paths_for_bb (basic_block cur, basic_block bb,
2906 enum br_predictor pred,
2907 enum prediction taken,
2908 bitmap visited, struct loop *in_loop = NULL)
2910 edge e;
2911 edge_iterator ei;
2912 basic_block son;
2914 /* If we exited the loop or CUR is unconditional in the loop, there is
2915 nothing to do. */
2916 if (in_loop
2917 && (!flow_bb_inside_loop_p (in_loop, cur)
2918 || dominated_by_p (CDI_DOMINATORS, in_loop->latch, cur)))
2919 return;
2921 /* We are looking for all edges forming edge cut induced by
2922 set of all blocks postdominated by BB. */
2923 FOR_EACH_EDGE (e, ei, cur->preds)
2924 if (e->src->index >= NUM_FIXED_BLOCKS
2925 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
2927 edge e2;
2928 edge_iterator ei2;
2929 bool found = false;
2931 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2932 if (unlikely_executed_edge_p (e))
2933 continue;
2934 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
2936 /* See if there is an edge from e->src that is not abnormal
2937 and does not lead to BB and does not exit the loop. */
2938 FOR_EACH_EDGE (e2, ei2, e->src->succs)
2939 if (e2 != e
2940 && !unlikely_executed_edge_p (e2)
2941 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb)
2942 && (!in_loop || !loop_exit_edge_p (in_loop, e2)))
2944 found = true;
2945 break;
2948 /* If there is non-abnormal path leaving e->src, predict edge
2949 using predictor. Otherwise we need to look for paths
2950 leading to e->src.
2952 The second may lead to infinite loop in the case we are predicitng
2953 regions that are only reachable by abnormal edges. We simply
2954 prevent visiting given BB twice. */
2955 if (found)
2957 if (!edge_predicted_by_p (e, pred, taken))
2958 predict_edge_def (e, pred, taken);
2960 else if (bitmap_set_bit (visited, e->src->index))
2961 predict_paths_for_bb (e->src, e->src, pred, taken, visited, in_loop);
2963 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
2964 son;
2965 son = next_dom_son (CDI_POST_DOMINATORS, son))
2966 predict_paths_for_bb (son, bb, pred, taken, visited, in_loop);
2969 /* Sets branch probabilities according to PREDiction and
2970 FLAGS. */
2972 static void
2973 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
2974 enum prediction taken, struct loop *in_loop)
2976 predict_paths_for_bb (bb, bb, pred, taken, auto_bitmap (), in_loop);
2979 /* Like predict_paths_leading_to but take edge instead of basic block. */
2981 static void
2982 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
2983 enum prediction taken, struct loop *in_loop)
2985 bool has_nonloop_edge = false;
2986 edge_iterator ei;
2987 edge e2;
2989 basic_block bb = e->src;
2990 FOR_EACH_EDGE (e2, ei, bb->succs)
2991 if (e2->dest != e->src && e2->dest != e->dest
2992 && !unlikely_executed_edge_p (e)
2993 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
2995 has_nonloop_edge = true;
2996 break;
2998 if (!has_nonloop_edge)
3000 predict_paths_for_bb (bb, bb, pred, taken, auto_bitmap (), in_loop);
3002 else
3003 predict_edge_def (e, pred, taken);
3006 /* This is used to carry information about basic blocks. It is
3007 attached to the AUX field of the standard CFG block. */
3009 struct block_info
3011 /* Estimated frequency of execution of basic_block. */
3012 sreal frequency;
3014 /* To keep queue of basic blocks to process. */
3015 basic_block next;
3017 /* Number of predecessors we need to visit first. */
3018 int npredecessors;
3021 /* Similar information for edges. */
3022 struct edge_prob_info
3024 /* In case edge is a loopback edge, the probability edge will be reached
3025 in case header is. Estimated number of iterations of the loop can be
3026 then computed as 1 / (1 - back_edge_prob). */
3027 sreal back_edge_prob;
3028 /* True if the edge is a loopback edge in the natural loop. */
3029 unsigned int back_edge:1;
3032 #define BLOCK_INFO(B) ((block_info *) (B)->aux)
3033 #undef EDGE_INFO
3034 #define EDGE_INFO(E) ((edge_prob_info *) (E)->aux)
3036 /* Helper function for estimate_bb_frequencies.
3037 Propagate the frequencies in blocks marked in
3038 TOVISIT, starting in HEAD. */
3040 static void
3041 propagate_freq (basic_block head, bitmap tovisit)
3043 basic_block bb;
3044 basic_block last;
3045 unsigned i;
3046 edge e;
3047 basic_block nextbb;
3048 bitmap_iterator bi;
3050 /* For each basic block we need to visit count number of his predecessors
3051 we need to visit first. */
3052 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
3054 edge_iterator ei;
3055 int count = 0;
3057 bb = BASIC_BLOCK_FOR_FN (cfun, i);
3059 FOR_EACH_EDGE (e, ei, bb->preds)
3061 bool visit = bitmap_bit_p (tovisit, e->src->index);
3063 if (visit && !(e->flags & EDGE_DFS_BACK))
3064 count++;
3065 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
3066 fprintf (dump_file,
3067 "Irreducible region hit, ignoring edge to %i->%i\n",
3068 e->src->index, bb->index);
3070 BLOCK_INFO (bb)->npredecessors = count;
3071 /* When function never returns, we will never process exit block. */
3072 if (!count && bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
3074 bb->count = profile_count::zero ();
3075 bb->frequency = 0;
3079 BLOCK_INFO (head)->frequency = 1;
3080 last = head;
3081 for (bb = head; bb; bb = nextbb)
3083 edge_iterator ei;
3084 sreal cyclic_probability = 0;
3085 sreal frequency = 0;
3087 nextbb = BLOCK_INFO (bb)->next;
3088 BLOCK_INFO (bb)->next = NULL;
3090 /* Compute frequency of basic block. */
3091 if (bb != head)
3093 if (flag_checking)
3094 FOR_EACH_EDGE (e, ei, bb->preds)
3095 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
3096 || (e->flags & EDGE_DFS_BACK));
3098 FOR_EACH_EDGE (e, ei, bb->preds)
3099 if (EDGE_INFO (e)->back_edge)
3101 cyclic_probability += EDGE_INFO (e)->back_edge_prob;
3103 else if (!(e->flags & EDGE_DFS_BACK))
3105 /* frequency += (e->probability
3106 * BLOCK_INFO (e->src)->frequency /
3107 REG_BR_PROB_BASE); */
3109 sreal tmp = e->probability;
3110 tmp *= BLOCK_INFO (e->src)->frequency;
3111 tmp *= real_inv_br_prob_base;
3112 frequency += tmp;
3115 if (cyclic_probability == 0)
3117 BLOCK_INFO (bb)->frequency = frequency;
3119 else
3121 if (cyclic_probability > real_almost_one)
3122 cyclic_probability = real_almost_one;
3124 /* BLOCK_INFO (bb)->frequency = frequency
3125 / (1 - cyclic_probability) */
3127 cyclic_probability = sreal (1) - cyclic_probability;
3128 BLOCK_INFO (bb)->frequency = frequency / cyclic_probability;
3132 bitmap_clear_bit (tovisit, bb->index);
3134 e = find_edge (bb, head);
3135 if (e)
3137 /* EDGE_INFO (e)->back_edge_prob
3138 = ((e->probability * BLOCK_INFO (bb)->frequency)
3139 / REG_BR_PROB_BASE); */
3141 sreal tmp = e->probability;
3142 tmp *= BLOCK_INFO (bb)->frequency;
3143 EDGE_INFO (e)->back_edge_prob = tmp * real_inv_br_prob_base;
3146 /* Propagate to successor blocks. */
3147 FOR_EACH_EDGE (e, ei, bb->succs)
3148 if (!(e->flags & EDGE_DFS_BACK)
3149 && BLOCK_INFO (e->dest)->npredecessors)
3151 BLOCK_INFO (e->dest)->npredecessors--;
3152 if (!BLOCK_INFO (e->dest)->npredecessors)
3154 if (!nextbb)
3155 nextbb = e->dest;
3156 else
3157 BLOCK_INFO (last)->next = e->dest;
3159 last = e->dest;
3165 /* Estimate frequencies in loops at same nest level. */
3167 static void
3168 estimate_loops_at_level (struct loop *first_loop)
3170 struct loop *loop;
3172 for (loop = first_loop; loop; loop = loop->next)
3174 edge e;
3175 basic_block *bbs;
3176 unsigned i;
3177 auto_bitmap tovisit;
3179 estimate_loops_at_level (loop->inner);
3181 /* Find current loop back edge and mark it. */
3182 e = loop_latch_edge (loop);
3183 EDGE_INFO (e)->back_edge = 1;
3185 bbs = get_loop_body (loop);
3186 for (i = 0; i < loop->num_nodes; i++)
3187 bitmap_set_bit (tovisit, bbs[i]->index);
3188 free (bbs);
3189 propagate_freq (loop->header, tovisit);
3193 /* Propagates frequencies through structure of loops. */
3195 static void
3196 estimate_loops (void)
3198 auto_bitmap tovisit;
3199 basic_block bb;
3201 /* Start by estimating the frequencies in the loops. */
3202 if (number_of_loops (cfun) > 1)
3203 estimate_loops_at_level (current_loops->tree_root->inner);
3205 /* Now propagate the frequencies through all the blocks. */
3206 FOR_ALL_BB_FN (bb, cfun)
3208 bitmap_set_bit (tovisit, bb->index);
3210 propagate_freq (ENTRY_BLOCK_PTR_FOR_FN (cfun), tovisit);
3213 /* Drop the profile for NODE to guessed, and update its frequency based on
3214 whether it is expected to be hot given the CALL_COUNT. */
3216 static void
3217 drop_profile (struct cgraph_node *node, profile_count call_count)
3219 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3220 /* In the case where this was called by another function with a
3221 dropped profile, call_count will be 0. Since there are no
3222 non-zero call counts to this function, we don't know for sure
3223 whether it is hot, and therefore it will be marked normal below. */
3224 bool hot = maybe_hot_count_p (NULL, call_count);
3226 if (dump_file)
3227 fprintf (dump_file,
3228 "Dropping 0 profile for %s. %s based on calls.\n",
3229 node->dump_name (),
3230 hot ? "Function is hot" : "Function is normal");
3231 /* We only expect to miss profiles for functions that are reached
3232 via non-zero call edges in cases where the function may have
3233 been linked from another module or library (COMDATs and extern
3234 templates). See the comments below for handle_missing_profiles.
3235 Also, only warn in cases where the missing counts exceed the
3236 number of training runs. In certain cases with an execv followed
3237 by a no-return call the profile for the no-return call is not
3238 dumped and there can be a mismatch. */
3239 if (!DECL_COMDAT (node->decl) && !DECL_EXTERNAL (node->decl)
3240 && call_count > profile_info->runs)
3242 if (flag_profile_correction)
3244 if (dump_file)
3245 fprintf (dump_file,
3246 "Missing counts for called function %s\n",
3247 node->dump_name ());
3249 else
3250 warning (0, "Missing counts for called function %s",
3251 node->dump_name ());
3254 basic_block bb;
3255 FOR_ALL_BB_FN (bb, fn)
3257 bb->count = profile_count::uninitialized ();
3259 edge_iterator ei;
3260 edge e;
3261 FOR_EACH_EDGE (e, ei, bb->preds)
3262 e->count = profile_count::uninitialized ();
3265 struct cgraph_edge *e;
3266 for (e = node->callees; e; e = e->next_caller)
3268 e->count = profile_count::uninitialized ();
3269 e->frequency = compute_call_stmt_bb_frequency (e->caller->decl,
3270 gimple_bb (e->call_stmt));
3272 node->count = profile_count::uninitialized ();
3274 profile_status_for_fn (fn)
3275 = (flag_guess_branch_prob ? PROFILE_GUESSED : PROFILE_ABSENT);
3276 node->frequency
3277 = hot ? NODE_FREQUENCY_HOT : NODE_FREQUENCY_NORMAL;
3280 /* In the case of COMDAT routines, multiple object files will contain the same
3281 function and the linker will select one for the binary. In that case
3282 all the other copies from the profile instrument binary will be missing
3283 profile counts. Look for cases where this happened, due to non-zero
3284 call counts going to 0-count functions, and drop the profile to guessed
3285 so that we can use the estimated probabilities and avoid optimizing only
3286 for size.
3288 The other case where the profile may be missing is when the routine
3289 is not going to be emitted to the object file, e.g. for "extern template"
3290 class methods. Those will be marked DECL_EXTERNAL. Emit a warning in
3291 all other cases of non-zero calls to 0-count functions. */
3293 void
3294 handle_missing_profiles (void)
3296 struct cgraph_node *node;
3297 int unlikely_count_fraction = PARAM_VALUE (UNLIKELY_BB_COUNT_FRACTION);
3298 auto_vec<struct cgraph_node *, 64> worklist;
3300 /* See if 0 count function has non-0 count callers. In this case we
3301 lost some profile. Drop its function profile to PROFILE_GUESSED. */
3302 FOR_EACH_DEFINED_FUNCTION (node)
3304 struct cgraph_edge *e;
3305 profile_count call_count = profile_count::zero ();
3306 gcov_type max_tp_first_run = 0;
3307 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3309 if (!(node->count == profile_count::zero ()))
3310 continue;
3311 for (e = node->callers; e; e = e->next_caller)
3312 if (e->count.initialized_p () && e->count > 0)
3314 call_count = call_count + e->count;
3316 if (e->caller->tp_first_run > max_tp_first_run)
3317 max_tp_first_run = e->caller->tp_first_run;
3320 /* If time profile is missing, let assign the maximum that comes from
3321 caller functions. */
3322 if (!node->tp_first_run && max_tp_first_run)
3323 node->tp_first_run = max_tp_first_run + 1;
3325 if (call_count > 0
3326 && fn && fn->cfg
3327 && (call_count.apply_scale (unlikely_count_fraction, 1)
3328 >= profile_info->runs))
3330 drop_profile (node, call_count);
3331 worklist.safe_push (node);
3335 /* Propagate the profile dropping to other 0-count COMDATs that are
3336 potentially called by COMDATs we already dropped the profile on. */
3337 while (worklist.length () > 0)
3339 struct cgraph_edge *e;
3341 node = worklist.pop ();
3342 for (e = node->callees; e; e = e->next_caller)
3344 struct cgraph_node *callee = e->callee;
3345 struct function *fn = DECL_STRUCT_FUNCTION (callee->decl);
3347 if (callee->count > 0)
3348 continue;
3349 if ((DECL_COMDAT (callee->decl) || DECL_EXTERNAL (callee->decl))
3350 && fn && fn->cfg
3351 && profile_status_for_fn (fn) == PROFILE_READ)
3353 drop_profile (node, profile_count::zero ());
3354 worklist.safe_push (callee);
3360 /* Convert counts measured by profile driven feedback to frequencies.
3361 Return nonzero iff there was any nonzero execution count. */
3363 bool
3364 counts_to_freqs (void)
3366 gcov_type count_max;
3367 profile_count true_count_max = profile_count::zero ();
3368 basic_block bb;
3370 /* Don't overwrite the estimated frequencies when the profile for
3371 the function is missing. We may drop this function PROFILE_GUESSED
3372 later in drop_profile (). */
3373 if (!ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.initialized_p ()
3374 || ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ())
3375 return false;
3377 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3378 if (bb->count > true_count_max)
3379 true_count_max = bb->count;
3381 /* If we have no counts to base frequencies on, keep those that are
3382 already there. */
3383 if (!(true_count_max > 0))
3384 return false;
3386 count_max = true_count_max.to_gcov_type ();
3388 FOR_ALL_BB_FN (bb, cfun)
3389 if (bb->count.initialized_p ())
3390 bb->frequency = RDIV (bb->count.to_gcov_type () * BB_FREQ_MAX, count_max);
3392 return true;
3395 /* Return true if function is likely to be expensive, so there is no point to
3396 optimize performance of prologue, epilogue or do inlining at the expense
3397 of code size growth. THRESHOLD is the limit of number of instructions
3398 function can execute at average to be still considered not expensive. */
3400 bool
3401 expensive_function_p (int threshold)
3403 unsigned int sum = 0;
3404 basic_block bb;
3405 unsigned int limit;
3407 /* We can not compute accurately for large thresholds due to scaled
3408 frequencies. */
3409 gcc_assert (threshold <= BB_FREQ_MAX);
3411 /* Frequencies are out of range. This either means that function contains
3412 internal loop executing more than BB_FREQ_MAX times or profile feedback
3413 is available and function has not been executed at all. */
3414 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency == 0)
3415 return true;
3417 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
3418 limit = ENTRY_BLOCK_PTR_FOR_FN (cfun)->frequency * threshold;
3419 FOR_EACH_BB_FN (bb, cfun)
3421 rtx_insn *insn;
3423 FOR_BB_INSNS (bb, insn)
3424 if (active_insn_p (insn))
3426 sum += bb->frequency;
3427 if (sum > limit)
3428 return true;
3432 return false;
3435 /* Determine basic blocks/edges that are known to be unlikely executed and set
3436 their counters to zero.
3437 This is done with first identifying obviously unlikely BBs/edges and then
3438 propagating in both directions. */
3440 static void
3441 determine_unlikely_bbs ()
3443 basic_block bb;
3444 auto_vec<basic_block, 64> worklist;
3445 edge_iterator ei;
3446 edge e;
3448 FOR_EACH_BB_FN (bb, cfun)
3450 if (!(bb->count == profile_count::zero ())
3451 && unlikely_executed_bb_p (bb))
3453 if (dump_file && (dump_flags & TDF_DETAILS))
3454 fprintf (dump_file, "Basic block %i is locally unlikely\n",
3455 bb->index);
3456 bb->count = profile_count::zero ();
3459 if (bb->count == profile_count::zero ())
3461 bb->frequency = 0;
3462 FOR_EACH_EDGE (e, ei, bb->preds)
3463 e->count = profile_count::zero ();
3466 FOR_EACH_EDGE (e, ei, bb->succs)
3467 if (!(e->count == profile_count::zero ())
3468 && unlikely_executed_edge_p (e))
3470 if (dump_file && (dump_flags & TDF_DETAILS))
3471 fprintf (dump_file, "Edge %i->%i is locally unlikely\n",
3472 bb->index, e->dest->index);
3473 e->count = profile_count::zero ();
3476 gcc_checking_assert (!bb->aux);
3479 if (!(ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ()))
3481 ENTRY_BLOCK_PTR_FOR_FN (cfun)->aux = (void *)(size_t) 1;
3482 worklist.safe_push (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3484 while (worklist.length () > 0)
3486 bb = worklist.pop ();
3487 FOR_EACH_EDGE (e, ei, bb->succs)
3488 if (!(e->count == profile_count::zero ())
3489 && !(e->dest->count == profile_count::zero ())
3490 && !e->dest->aux)
3492 e->dest->aux = (void *)(size_t) 1;
3493 worklist.safe_push (e->dest);
3498 FOR_ALL_BB_FN (bb, cfun)
3500 if (!bb->aux)
3502 if (!(bb->count == profile_count::zero ())
3503 && (dump_file && (dump_flags & TDF_DETAILS)))
3504 fprintf (dump_file,
3505 "Basic block %i is marked unlikely by forward prop\n",
3506 bb->index);
3507 bb->count = profile_count::zero ();
3508 bb->frequency = 0;
3509 FOR_EACH_EDGE (e, ei, bb->succs)
3510 e->count = profile_count::zero ();
3512 else
3513 bb->aux = NULL;
3516 auto_vec<int, 64> nsuccs;
3517 nsuccs.safe_grow_cleared (last_basic_block_for_fn (cfun));
3518 FOR_ALL_BB_FN (bb, cfun)
3519 if (!(bb->count == profile_count::zero ())
3520 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
3522 nsuccs[bb->index] = 0;
3523 FOR_EACH_EDGE (e, ei, bb->succs)
3524 if (!(e->count == profile_count::zero ()))
3525 nsuccs[bb->index]++;
3526 if (!nsuccs[bb->index])
3527 worklist.safe_push (bb);
3529 while (worklist.length () > 0)
3531 bb = worklist.pop ();
3532 if (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun))
3534 bool found = false;
3535 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
3536 !gsi_end_p (gsi); gsi_next (&gsi))
3537 if (stmt_can_terminate_bb_p (gsi_stmt (gsi))
3538 /* stmt_can_terminate_bb_p special cases noreturns because it
3539 assumes that fake edges are created. We want to know that
3540 noreturn alone does not imply BB to be unlikely. */
3541 || (is_gimple_call (gsi_stmt (gsi))
3542 && (gimple_call_flags (gsi_stmt (gsi)) & ECF_NORETURN)))
3544 found = true;
3545 break;
3547 if (found)
3548 continue;
3550 if (!(bb->count == profile_count::zero ())
3551 && (dump_file && (dump_flags & TDF_DETAILS)))
3552 fprintf (dump_file,
3553 "Basic block %i is marked unlikely by backward prop\n",
3554 bb->index);
3555 bb->count = profile_count::zero ();
3556 bb->frequency = 0;
3557 FOR_EACH_EDGE (e, ei, bb->preds)
3558 if (!(e->count == profile_count::zero ()))
3560 e->count = profile_count::zero ();
3561 if (!(e->src->count == profile_count::zero ()))
3563 nsuccs[e->src->index]--;
3564 if (!nsuccs[e->src->index])
3565 worklist.safe_push (e->src);
3571 /* Estimate and propagate basic block frequencies using the given branch
3572 probabilities. If FORCE is true, the frequencies are used to estimate
3573 the counts even when there are already non-zero profile counts. */
3575 void
3576 estimate_bb_frequencies (bool force)
3578 basic_block bb;
3579 sreal freq_max;
3581 determine_unlikely_bbs ();
3583 if (force || profile_status_for_fn (cfun) != PROFILE_READ
3584 || !counts_to_freqs ())
3586 static int real_values_initialized = 0;
3588 if (!real_values_initialized)
3590 real_values_initialized = 1;
3591 real_br_prob_base = REG_BR_PROB_BASE;
3592 real_bb_freq_max = BB_FREQ_MAX;
3593 real_one_half = sreal (1, -1);
3594 real_inv_br_prob_base = sreal (1) / real_br_prob_base;
3595 real_almost_one = sreal (1) - real_inv_br_prob_base;
3598 mark_dfs_back_edges ();
3600 single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->probability =
3601 REG_BR_PROB_BASE;
3603 /* Set up block info for each basic block. */
3604 alloc_aux_for_blocks (sizeof (block_info));
3605 alloc_aux_for_edges (sizeof (edge_prob_info));
3606 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3608 edge e;
3609 edge_iterator ei;
3611 FOR_EACH_EDGE (e, ei, bb->succs)
3613 EDGE_INFO (e)->back_edge_prob = e->probability;
3614 EDGE_INFO (e)->back_edge_prob *= real_inv_br_prob_base;
3618 /* First compute frequencies locally for each loop from innermost
3619 to outermost to examine frequencies for back edges. */
3620 estimate_loops ();
3622 freq_max = 0;
3623 FOR_EACH_BB_FN (bb, cfun)
3624 if (freq_max < BLOCK_INFO (bb)->frequency)
3625 freq_max = BLOCK_INFO (bb)->frequency;
3627 freq_max = real_bb_freq_max / freq_max;
3628 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3630 sreal tmp = BLOCK_INFO (bb)->frequency * freq_max + real_one_half;
3631 bb->frequency = tmp.to_int ();
3634 free_aux_for_blocks ();
3635 free_aux_for_edges ();
3637 compute_function_frequency ();
3640 /* Decide whether function is hot, cold or unlikely executed. */
3641 void
3642 compute_function_frequency (void)
3644 basic_block bb;
3645 struct cgraph_node *node = cgraph_node::get (current_function_decl);
3647 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
3648 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
3649 node->only_called_at_startup = true;
3650 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
3651 node->only_called_at_exit = true;
3653 if (profile_status_for_fn (cfun) != PROFILE_READ)
3655 int flags = flags_from_decl_or_type (current_function_decl);
3656 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ()
3657 || lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
3658 != NULL)
3659 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
3660 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
3661 != NULL)
3662 node->frequency = NODE_FREQUENCY_HOT;
3663 else if (flags & ECF_NORETURN)
3664 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
3665 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
3666 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
3667 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
3668 || DECL_STATIC_DESTRUCTOR (current_function_decl))
3669 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
3670 return;
3673 /* Only first time try to drop function into unlikely executed.
3674 After inlining the roundoff errors may confuse us.
3675 Ipa-profile pass will drop functions only called from unlikely
3676 functions to unlikely and that is most of what we care about. */
3677 if (!cfun->after_inlining)
3678 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
3679 FOR_EACH_BB_FN (bb, cfun)
3681 if (maybe_hot_bb_p (cfun, bb))
3683 node->frequency = NODE_FREQUENCY_HOT;
3684 return;
3686 if (!probably_never_executed_bb_p (cfun, bb))
3687 node->frequency = NODE_FREQUENCY_NORMAL;
3691 /* Build PREDICT_EXPR. */
3692 tree
3693 build_predict_expr (enum br_predictor predictor, enum prediction taken)
3695 tree t = build1 (PREDICT_EXPR, void_type_node,
3696 build_int_cst (integer_type_node, predictor));
3697 SET_PREDICT_EXPR_OUTCOME (t, taken);
3698 return t;
3701 const char *
3702 predictor_name (enum br_predictor predictor)
3704 return predictor_info[predictor].name;
3707 /* Predict branch probabilities and estimate profile of the tree CFG. */
3709 namespace {
3711 const pass_data pass_data_profile =
3713 GIMPLE_PASS, /* type */
3714 "profile_estimate", /* name */
3715 OPTGROUP_NONE, /* optinfo_flags */
3716 TV_BRANCH_PROB, /* tv_id */
3717 PROP_cfg, /* properties_required */
3718 0, /* properties_provided */
3719 0, /* properties_destroyed */
3720 0, /* todo_flags_start */
3721 0, /* todo_flags_finish */
3724 class pass_profile : public gimple_opt_pass
3726 public:
3727 pass_profile (gcc::context *ctxt)
3728 : gimple_opt_pass (pass_data_profile, ctxt)
3731 /* opt_pass methods: */
3732 virtual bool gate (function *) { return flag_guess_branch_prob; }
3733 virtual unsigned int execute (function *);
3735 }; // class pass_profile
3737 unsigned int
3738 pass_profile::execute (function *fun)
3740 unsigned nb_loops;
3742 if (profile_status_for_fn (cfun) == PROFILE_GUESSED)
3743 return 0;
3745 loop_optimizer_init (LOOPS_NORMAL);
3746 if (dump_file && (dump_flags & TDF_DETAILS))
3747 flow_loops_dump (dump_file, NULL, 0);
3749 mark_irreducible_loops ();
3751 nb_loops = number_of_loops (fun);
3752 if (nb_loops > 1)
3753 scev_initialize ();
3755 tree_estimate_probability (false);
3757 if (nb_loops > 1)
3758 scev_finalize ();
3760 loop_optimizer_finalize ();
3761 if (dump_file && (dump_flags & TDF_DETAILS))
3762 gimple_dump_cfg (dump_file, dump_flags);
3763 if (profile_status_for_fn (fun) == PROFILE_ABSENT)
3764 profile_status_for_fn (fun) = PROFILE_GUESSED;
3765 if (dump_file && (dump_flags & TDF_DETAILS))
3767 struct loop *loop;
3768 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3769 if (loop->header->frequency)
3770 fprintf (dump_file, "Loop got predicted %d to iterate %i times.\n",
3771 loop->num,
3772 (int)expected_loop_iterations_unbounded (loop));
3774 return 0;
3777 } // anon namespace
3779 gimple_opt_pass *
3780 make_pass_profile (gcc::context *ctxt)
3782 return new pass_profile (ctxt);
3785 namespace {
3787 const pass_data pass_data_strip_predict_hints =
3789 GIMPLE_PASS, /* type */
3790 "*strip_predict_hints", /* name */
3791 OPTGROUP_NONE, /* optinfo_flags */
3792 TV_BRANCH_PROB, /* tv_id */
3793 PROP_cfg, /* properties_required */
3794 0, /* properties_provided */
3795 0, /* properties_destroyed */
3796 0, /* todo_flags_start */
3797 0, /* todo_flags_finish */
3800 class pass_strip_predict_hints : public gimple_opt_pass
3802 public:
3803 pass_strip_predict_hints (gcc::context *ctxt)
3804 : gimple_opt_pass (pass_data_strip_predict_hints, ctxt)
3807 /* opt_pass methods: */
3808 opt_pass * clone () { return new pass_strip_predict_hints (m_ctxt); }
3809 virtual unsigned int execute (function *);
3811 }; // class pass_strip_predict_hints
3813 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
3814 we no longer need. */
3815 unsigned int
3816 pass_strip_predict_hints::execute (function *fun)
3818 basic_block bb;
3819 gimple *ass_stmt;
3820 tree var;
3821 bool changed = false;
3823 FOR_EACH_BB_FN (bb, fun)
3825 gimple_stmt_iterator bi;
3826 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
3828 gimple *stmt = gsi_stmt (bi);
3830 if (gimple_code (stmt) == GIMPLE_PREDICT)
3832 gsi_remove (&bi, true);
3833 changed = true;
3834 continue;
3836 else if (is_gimple_call (stmt))
3838 tree fndecl = gimple_call_fndecl (stmt);
3840 if ((fndecl
3841 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
3842 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
3843 && gimple_call_num_args (stmt) == 2)
3844 || (gimple_call_internal_p (stmt)
3845 && gimple_call_internal_fn (stmt) == IFN_BUILTIN_EXPECT))
3847 var = gimple_call_lhs (stmt);
3848 changed = true;
3849 if (var)
3851 ass_stmt
3852 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
3853 gsi_replace (&bi, ass_stmt, true);
3855 else
3857 gsi_remove (&bi, true);
3858 continue;
3862 gsi_next (&bi);
3865 return changed ? TODO_cleanup_cfg : 0;
3868 } // anon namespace
3870 gimple_opt_pass *
3871 make_pass_strip_predict_hints (gcc::context *ctxt)
3873 return new pass_strip_predict_hints (ctxt);
3876 /* Rebuild function frequencies. Passes are in general expected to
3877 maintain profile by hand, however in some cases this is not possible:
3878 for example when inlining several functions with loops freuqencies might run
3879 out of scale and thus needs to be recomputed. */
3881 void
3882 rebuild_frequencies (void)
3884 timevar_push (TV_REBUILD_FREQUENCIES);
3886 /* When the max bb count in the function is small, there is a higher
3887 chance that there were truncation errors in the integer scaling
3888 of counts by inlining and other optimizations. This could lead
3889 to incorrect classification of code as being cold when it isn't.
3890 In that case, force the estimation of bb counts/frequencies from the
3891 branch probabilities, rather than computing frequencies from counts,
3892 which may also lead to frequencies incorrectly reduced to 0. There
3893 is less precision in the probabilities, so we only do this for small
3894 max counts. */
3895 profile_count count_max = profile_count::zero ();
3896 basic_block bb;
3897 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3898 if (bb->count > count_max)
3899 count_max = bb->count;
3901 if (profile_status_for_fn (cfun) == PROFILE_GUESSED
3902 || (!flag_auto_profile && profile_status_for_fn (cfun) == PROFILE_READ
3903 && count_max < REG_BR_PROB_BASE / 10))
3905 loop_optimizer_init (0);
3906 add_noreturn_fake_exit_edges ();
3907 mark_irreducible_loops ();
3908 connect_infinite_loops_to_exit ();
3909 estimate_bb_frequencies (true);
3910 remove_fake_exit_edges ();
3911 loop_optimizer_finalize ();
3913 else if (profile_status_for_fn (cfun) == PROFILE_READ)
3914 counts_to_freqs ();
3915 else
3916 gcc_unreachable ();
3917 timevar_pop (TV_REBUILD_FREQUENCIES);
3920 /* Perform a dry run of the branch prediction pass and report comparsion of
3921 the predicted and real profile into the dump file. */
3923 void
3924 report_predictor_hitrates (void)
3926 unsigned nb_loops;
3928 loop_optimizer_init (LOOPS_NORMAL);
3929 if (dump_file && (dump_flags & TDF_DETAILS))
3930 flow_loops_dump (dump_file, NULL, 0);
3932 mark_irreducible_loops ();
3934 nb_loops = number_of_loops (cfun);
3935 if (nb_loops > 1)
3936 scev_initialize ();
3938 tree_estimate_probability (true);
3940 if (nb_loops > 1)
3941 scev_finalize ();
3943 loop_optimizer_finalize ();
3946 /* Force edge E to be cold.
3947 If IMPOSSIBLE is true, for edge to have count and probability 0 otherwise
3948 keep low probability to represent possible error in a guess. This is used
3949 i.e. in case we predict loop to likely iterate given number of times but
3950 we are not 100% sure.
3952 This function locally updates profile without attempt to keep global
3953 consistency which can not be reached in full generality without full profile
3954 rebuild from probabilities alone. Doing so is not necessarily a good idea
3955 because frequencies and counts may be more realistic then probabilities.
3957 In some cases (such as for elimination of early exits during full loop
3958 unrolling) the caller can ensure that profile will get consistent
3959 afterwards. */
3961 void
3962 force_edge_cold (edge e, bool impossible)
3964 profile_count count_sum = profile_count::zero ();
3965 int prob_sum = 0;
3966 edge_iterator ei;
3967 edge e2;
3968 profile_count old_count = e->count;
3969 int old_probability = e->probability;
3970 int prob_scale = REG_BR_PROB_BASE;
3971 bool uninitialized_exit = false;
3973 /* If edge is already improbably or cold, just return. */
3974 if (e->probability <= (impossible ? PROB_VERY_UNLIKELY : 0)
3975 && (!impossible || e->count == profile_count::zero ()))
3976 return;
3977 FOR_EACH_EDGE (e2, ei, e->src->succs)
3978 if (e2 != e)
3980 if (e2->count.initialized_p ())
3981 count_sum += e2->count;
3982 else
3983 uninitialized_exit = true;
3984 prob_sum += e2->probability;
3987 /* If there are other edges out of e->src, redistribute probabilitity
3988 there. */
3989 if (prob_sum)
3991 e->probability
3992 = MIN (e->probability, impossible ? 0 : PROB_VERY_UNLIKELY);
3993 if (impossible)
3994 e->count = profile_count::zero ();
3995 else if (old_probability)
3996 e->count = e->count.apply_scale (e->probability, old_probability);
3997 else
3998 e->count = e->count.apply_scale (1, REG_BR_PROB_BASE);
4000 prob_scale = RDIV ((REG_BR_PROB_BASE - e->probability) * REG_BR_PROB_BASE,
4001 prob_sum);
4002 if (dump_file && (dump_flags & TDF_DETAILS))
4003 fprintf (dump_file, "Making edge %i->%i %s by redistributing "
4004 "probability to other edges.\n",
4005 e->src->index, e->dest->index,
4006 impossible ? "impossible" : "cold");
4007 profile_count count_sum2 = count_sum + old_count - e->count;
4008 FOR_EACH_EDGE (e2, ei, e->src->succs)
4009 if (e2 != e)
4011 if (count_sum > 0)
4012 e2->count.apply_scale (count_sum2, count_sum);
4013 e2->probability = RDIV (e2->probability * prob_scale,
4014 REG_BR_PROB_BASE);
4017 /* If all edges out of e->src are unlikely, the basic block itself
4018 is unlikely. */
4019 else
4021 e->probability = REG_BR_PROB_BASE;
4022 if (e->src->count == profile_count::zero ())
4023 return;
4024 if (count_sum == profile_count::zero () && !uninitialized_exit
4025 && impossible)
4027 bool found = false;
4028 for (gimple_stmt_iterator gsi = gsi_start_bb (e->src);
4029 !gsi_end_p (gsi); gsi_next (&gsi))
4031 if (stmt_can_terminate_bb_p (gsi_stmt (gsi)))
4033 found = true;
4034 break;
4037 if (!found)
4039 if (dump_file && (dump_flags & TDF_DETAILS))
4040 fprintf (dump_file,
4041 "Making bb %i impossible and dropping count to 0.\n",
4042 e->src->index);
4043 e->count = profile_count::zero ();
4044 e->src->count = profile_count::zero ();
4045 FOR_EACH_EDGE (e2, ei, e->src->preds)
4046 force_edge_cold (e2, impossible);
4047 return;
4051 /* If we did not adjusting, the source basic block has no likely edeges
4052 leaving other direction. In that case force that bb cold, too.
4053 This in general is difficult task to do, but handle special case when
4054 BB has only one predecestor. This is common case when we are updating
4055 after loop transforms. */
4056 if (!prob_sum && count_sum == profile_count::zero ()
4057 && single_pred_p (e->src) && e->src->frequency > (impossible ? 0 : 1))
4059 int old_frequency = e->src->frequency;
4060 if (dump_file && (dump_flags & TDF_DETAILS))
4061 fprintf (dump_file, "Making bb %i %s.\n", e->src->index,
4062 impossible ? "impossible" : "cold");
4063 e->src->frequency = MIN (e->src->frequency, impossible ? 0 : 1);
4064 if (impossible)
4065 e->src->count = e->count = profile_count::zero ();
4066 else
4067 e->src->count = e->count = e->count.apply_scale (e->src->frequency,
4068 old_frequency);
4069 force_edge_cold (single_pred_edge (e->src), impossible);
4071 else if (dump_file && (dump_flags & TDF_DETAILS)
4072 && maybe_hot_bb_p (cfun, e->src))
4073 fprintf (dump_file, "Giving up on making bb %i %s.\n", e->src->index,
4074 impossible ? "impossible" : "cold");
4078 #if CHECKING_P
4080 namespace selftest {
4082 /* Test that value range of predictor values defined in predict.def is
4083 within range (50, 100]. */
4085 struct branch_predictor
4087 const char *name;
4088 unsigned probability;
4091 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) { NAME, HITRATE },
4093 static void
4094 test_prediction_value_range ()
4096 branch_predictor predictors[] = {
4097 #include "predict.def"
4098 {NULL, -1}
4101 for (unsigned i = 0; predictors[i].name != NULL; i++)
4103 unsigned p = 100 * predictors[i].probability / REG_BR_PROB_BASE;
4104 ASSERT_TRUE (p > 50 && p <= 100);
4108 #undef DEF_PREDICTOR
4110 /* Run all of the selfests within this file. */
4112 void
4113 predict_c_tests ()
4115 test_prediction_value_range ();
4118 } // namespace selftest
4119 #endif /* CHECKING_P. */