i386: move alignment defaults to processor_costs.
[official-gcc.git] / gcc / predict.c
blob51145526d2a168fe242eeceb303a5f1204c496d4
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000-2018 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"
61 #include "cfgrtl.h"
62 #include "stringpool.h"
63 #include "attribs.h"
65 /* Enum with reasons why a predictor is ignored. */
67 enum predictor_reason
69 REASON_NONE,
70 REASON_IGNORED,
71 REASON_SINGLE_EDGE_DUPLICATE,
72 REASON_EDGE_PAIR_DUPLICATE
75 /* String messages for the aforementioned enum. */
77 static const char *reason_messages[] = {"", " (ignored)",
78 " (single edge duplicate)", " (edge pair duplicate)"};
80 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
81 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
82 static sreal real_almost_one, real_br_prob_base,
83 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
85 static void combine_predictions_for_insn (rtx_insn *, basic_block);
86 static void dump_prediction (FILE *, enum br_predictor, int, basic_block,
87 enum predictor_reason, edge);
88 static void predict_paths_leading_to (basic_block, enum br_predictor,
89 enum prediction,
90 struct loop *in_loop = NULL);
91 static void predict_paths_leading_to_edge (edge, enum br_predictor,
92 enum prediction,
93 struct loop *in_loop = NULL);
94 static bool can_predict_insn_p (const rtx_insn *);
95 static HOST_WIDE_INT get_predictor_value (br_predictor, HOST_WIDE_INT);
97 /* Information we hold about each branch predictor.
98 Filled using information from predict.def. */
100 struct predictor_info
102 const char *const name; /* Name used in the debugging dumps. */
103 const int hitrate; /* Expected hitrate used by
104 predict_insn_def call. */
105 const int flags;
108 /* Use given predictor without Dempster-Shaffer theory if it matches
109 using first_match heuristics. */
110 #define PRED_FLAG_FIRST_MATCH 1
112 /* Recompute hitrate in percent to our representation. */
114 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
116 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
117 static const struct predictor_info predictor_info[]= {
118 #include "predict.def"
120 /* Upper bound on predictors. */
121 {NULL, 0, 0}
123 #undef DEF_PREDICTOR
125 static gcov_type min_count = -1;
127 /* Determine the threshold for hot BB counts. */
129 gcov_type
130 get_hot_bb_threshold ()
132 gcov_working_set_t *ws;
133 if (min_count == -1)
135 ws = find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE));
136 gcc_assert (ws);
137 min_count = ws->min_counter;
139 return min_count;
142 /* Set the threshold for hot BB counts. */
144 void
145 set_hot_bb_threshold (gcov_type min)
147 min_count = min;
150 /* Return TRUE if frequency FREQ is considered to be hot. */
152 bool
153 maybe_hot_count_p (struct function *fun, profile_count count)
155 if (!count.initialized_p ())
156 return true;
157 if (count.ipa () == profile_count::zero ())
158 return false;
159 if (!count.ipa_p ())
161 struct cgraph_node *node = cgraph_node::get (fun->decl);
162 if (!profile_info || profile_status_for_fn (fun) != PROFILE_READ)
164 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
165 return false;
166 if (node->frequency == NODE_FREQUENCY_HOT)
167 return true;
169 if (profile_status_for_fn (fun) == PROFILE_ABSENT)
170 return true;
171 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
172 && count < (ENTRY_BLOCK_PTR_FOR_FN (fun)->count.apply_scale (2, 3)))
173 return false;
174 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION) == 0)
175 return false;
176 if (count.apply_scale (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION), 1)
177 < ENTRY_BLOCK_PTR_FOR_FN (fun)->count)
178 return false;
179 return true;
181 /* Code executed at most once is not hot. */
182 if (count <= MAX (profile_info ? profile_info->runs : 1, 1))
183 return false;
184 return (count.to_gcov_type () >= get_hot_bb_threshold ());
187 /* Return true in case BB can be CPU intensive and should be optimized
188 for maximal performance. */
190 bool
191 maybe_hot_bb_p (struct function *fun, const_basic_block bb)
193 gcc_checking_assert (fun);
194 return maybe_hot_count_p (fun, bb->count);
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 return maybe_hot_count_p (cfun, e->count ());
206 /* Return true if profile COUNT and FREQUENCY, or function FUN static
207 node frequency reflects never being executed. */
209 static bool
210 probably_never_executed (struct function *fun,
211 profile_count count)
213 gcc_checking_assert (fun);
214 if (count.ipa () == profile_count::zero ())
215 return true;
216 /* Do not trust adjusted counts. This will make us to drop int cold section
217 code with low execution count as a result of inlining. These low counts
218 are not safe even with read profile and may lead us to dropping
219 code which actually gets executed into cold section of binary that is not
220 desirable. */
221 if (count.precise_p () && profile_status_for_fn (fun) == PROFILE_READ)
223 int unlikely_count_fraction = PARAM_VALUE (UNLIKELY_BB_COUNT_FRACTION);
224 if (count.apply_scale (unlikely_count_fraction, 1) >= profile_info->runs)
225 return false;
226 return true;
228 if ((!profile_info || profile_status_for_fn (fun) != PROFILE_READ)
229 && (cgraph_node::get (fun->decl)->frequency
230 == NODE_FREQUENCY_UNLIKELY_EXECUTED))
231 return true;
232 return false;
236 /* Return true in case BB is probably never executed. */
238 bool
239 probably_never_executed_bb_p (struct function *fun, const_basic_block bb)
241 return probably_never_executed (fun, bb->count);
245 /* Return true if E is unlikely executed for obvious reasons. */
247 static bool
248 unlikely_executed_edge_p (edge e)
250 return (e->count () == profile_count::zero ()
251 || e->probability == profile_probability::never ())
252 || (e->flags & (EDGE_EH | EDGE_FAKE));
255 /* Return true in case edge E is probably never executed. */
257 bool
258 probably_never_executed_edge_p (struct function *fun, edge e)
260 if (unlikely_executed_edge_p (e))
261 return true;
262 return probably_never_executed (fun, e->count ());
265 /* Return true when current function should always be optimized for size. */
267 bool
268 optimize_function_for_size_p (struct function *fun)
270 if (!fun || !fun->decl)
271 return optimize_size;
272 cgraph_node *n = cgraph_node::get (fun->decl);
273 return n && n->optimize_for_size_p ();
276 /* Return true when current function should always be optimized for speed. */
278 bool
279 optimize_function_for_speed_p (struct function *fun)
281 return !optimize_function_for_size_p (fun);
284 /* Return the optimization type that should be used for the function FUN. */
286 optimization_type
287 function_optimization_type (struct function *fun)
289 return (optimize_function_for_speed_p (fun)
290 ? OPTIMIZE_FOR_SPEED
291 : OPTIMIZE_FOR_SIZE);
294 /* Return TRUE when BB should be optimized for size. */
296 bool
297 optimize_bb_for_size_p (const_basic_block bb)
299 return (optimize_function_for_size_p (cfun)
300 || (bb && !maybe_hot_bb_p (cfun, bb)));
303 /* Return TRUE when BB should be optimized for speed. */
305 bool
306 optimize_bb_for_speed_p (const_basic_block bb)
308 return !optimize_bb_for_size_p (bb);
311 /* Return the optimization type that should be used for block BB. */
313 optimization_type
314 bb_optimization_type (const_basic_block bb)
316 return (optimize_bb_for_speed_p (bb)
317 ? OPTIMIZE_FOR_SPEED
318 : OPTIMIZE_FOR_SIZE);
321 /* Return TRUE when BB should be optimized for size. */
323 bool
324 optimize_edge_for_size_p (edge e)
326 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
329 /* Return TRUE when BB should be optimized for speed. */
331 bool
332 optimize_edge_for_speed_p (edge e)
334 return !optimize_edge_for_size_p (e);
337 /* Return TRUE when BB should be optimized for size. */
339 bool
340 optimize_insn_for_size_p (void)
342 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
345 /* Return TRUE when BB should be optimized for speed. */
347 bool
348 optimize_insn_for_speed_p (void)
350 return !optimize_insn_for_size_p ();
353 /* Return TRUE when LOOP should be optimized for size. */
355 bool
356 optimize_loop_for_size_p (struct loop *loop)
358 return optimize_bb_for_size_p (loop->header);
361 /* Return TRUE when LOOP should be optimized for speed. */
363 bool
364 optimize_loop_for_speed_p (struct loop *loop)
366 return optimize_bb_for_speed_p (loop->header);
369 /* Return TRUE when LOOP nest should be optimized for speed. */
371 bool
372 optimize_loop_nest_for_speed_p (struct loop *loop)
374 struct loop *l = loop;
375 if (optimize_loop_for_speed_p (loop))
376 return true;
377 l = loop->inner;
378 while (l && l != loop)
380 if (optimize_loop_for_speed_p (l))
381 return true;
382 if (l->inner)
383 l = l->inner;
384 else if (l->next)
385 l = l->next;
386 else
388 while (l != loop && !l->next)
389 l = loop_outer (l);
390 if (l != loop)
391 l = l->next;
394 return false;
397 /* Return TRUE when LOOP nest should be optimized for size. */
399 bool
400 optimize_loop_nest_for_size_p (struct loop *loop)
402 return !optimize_loop_nest_for_speed_p (loop);
405 /* Return true when edge E is likely to be well predictable by branch
406 predictor. */
408 bool
409 predictable_edge_p (edge e)
411 if (!e->probability.initialized_p ())
412 return false;
413 if ((e->probability.to_reg_br_prob_base ()
414 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
415 || (REG_BR_PROB_BASE - e->probability.to_reg_br_prob_base ()
416 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
417 return true;
418 return false;
422 /* Set RTL expansion for BB profile. */
424 void
425 rtl_profile_for_bb (basic_block bb)
427 crtl->maybe_hot_insn_p = maybe_hot_bb_p (cfun, bb);
430 /* Set RTL expansion for edge profile. */
432 void
433 rtl_profile_for_edge (edge e)
435 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
438 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
439 void
440 default_rtl_profile (void)
442 crtl->maybe_hot_insn_p = true;
445 /* Return true if the one of outgoing edges is already predicted by
446 PREDICTOR. */
448 bool
449 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
451 rtx note;
452 if (!INSN_P (BB_END (bb)))
453 return false;
454 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
455 if (REG_NOTE_KIND (note) == REG_BR_PRED
456 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
457 return true;
458 return false;
461 /* Structure representing predictions in tree level. */
463 struct edge_prediction {
464 struct edge_prediction *ep_next;
465 edge ep_edge;
466 enum br_predictor ep_predictor;
467 int ep_probability;
470 /* This map contains for a basic block the list of predictions for the
471 outgoing edges. */
473 static hash_map<const_basic_block, edge_prediction *> *bb_predictions;
475 /* Return true if the one of outgoing edges is already predicted by
476 PREDICTOR. */
478 bool
479 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
481 struct edge_prediction *i;
482 edge_prediction **preds = bb_predictions->get (bb);
484 if (!preds)
485 return false;
487 for (i = *preds; i; i = i->ep_next)
488 if (i->ep_predictor == predictor)
489 return true;
490 return false;
493 /* Return true if the one of outgoing edges is already predicted by
494 PREDICTOR for edge E predicted as TAKEN. */
496 bool
497 edge_predicted_by_p (edge e, enum br_predictor predictor, bool taken)
499 struct edge_prediction *i;
500 basic_block bb = e->src;
501 edge_prediction **preds = bb_predictions->get (bb);
502 if (!preds)
503 return false;
505 int probability = predictor_info[(int) predictor].hitrate;
507 if (taken != TAKEN)
508 probability = REG_BR_PROB_BASE - probability;
510 for (i = *preds; i; i = i->ep_next)
511 if (i->ep_predictor == predictor
512 && i->ep_edge == e
513 && i->ep_probability == probability)
514 return true;
515 return false;
518 /* Same predicate as above, working on edges. */
519 bool
520 edge_probability_reliable_p (const_edge e)
522 return e->probability.probably_reliable_p ();
525 /* Same predicate as edge_probability_reliable_p, working on notes. */
526 bool
527 br_prob_note_reliable_p (const_rtx note)
529 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
530 return profile_probability::from_reg_br_prob_note
531 (XINT (note, 0)).probably_reliable_p ();
534 static void
535 predict_insn (rtx_insn *insn, enum br_predictor predictor, int probability)
537 gcc_assert (any_condjump_p (insn));
538 if (!flag_guess_branch_prob)
539 return;
541 add_reg_note (insn, REG_BR_PRED,
542 gen_rtx_CONCAT (VOIDmode,
543 GEN_INT ((int) predictor),
544 GEN_INT ((int) probability)));
547 /* Predict insn by given predictor. */
549 void
550 predict_insn_def (rtx_insn *insn, enum br_predictor predictor,
551 enum prediction taken)
553 int probability = predictor_info[(int) predictor].hitrate;
554 gcc_assert (probability != PROB_UNINITIALIZED);
556 if (taken != TAKEN)
557 probability = REG_BR_PROB_BASE - probability;
559 predict_insn (insn, predictor, probability);
562 /* Predict edge E with given probability if possible. */
564 void
565 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
567 rtx_insn *last_insn;
568 last_insn = BB_END (e->src);
570 /* We can store the branch prediction information only about
571 conditional jumps. */
572 if (!any_condjump_p (last_insn))
573 return;
575 /* We always store probability of branching. */
576 if (e->flags & EDGE_FALLTHRU)
577 probability = REG_BR_PROB_BASE - probability;
579 predict_insn (last_insn, predictor, probability);
582 /* Predict edge E with the given PROBABILITY. */
583 void
584 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
586 if (e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun)
587 && EDGE_COUNT (e->src->succs) > 1
588 && flag_guess_branch_prob
589 && optimize)
591 struct edge_prediction *i = XNEW (struct edge_prediction);
592 edge_prediction *&preds = bb_predictions->get_or_insert (e->src);
594 i->ep_next = preds;
595 preds = i;
596 i->ep_probability = probability;
597 i->ep_predictor = predictor;
598 i->ep_edge = e;
602 /* Filter edge predictions PREDS by a function FILTER. DATA are passed
603 to the filter function. */
605 void
606 filter_predictions (edge_prediction **preds,
607 bool (*filter) (edge_prediction *, void *), void *data)
609 if (!bb_predictions)
610 return;
612 if (preds)
614 struct edge_prediction **prediction = preds;
615 struct edge_prediction *next;
617 while (*prediction)
619 if ((*filter) (*prediction, data))
620 prediction = &((*prediction)->ep_next);
621 else
623 next = (*prediction)->ep_next;
624 free (*prediction);
625 *prediction = next;
631 /* Filter function predicate that returns true for a edge predicate P
632 if its edge is equal to DATA. */
634 bool
635 equal_edge_p (edge_prediction *p, void *data)
637 return p->ep_edge == (edge)data;
640 /* Remove all predictions on given basic block that are attached
641 to edge E. */
642 void
643 remove_predictions_associated_with_edge (edge e)
645 if (!bb_predictions)
646 return;
648 edge_prediction **preds = bb_predictions->get (e->src);
649 filter_predictions (preds, equal_edge_p, e);
652 /* Clears the list of predictions stored for BB. */
654 static void
655 clear_bb_predictions (basic_block bb)
657 edge_prediction **preds = bb_predictions->get (bb);
658 struct edge_prediction *pred, *next;
660 if (!preds)
661 return;
663 for (pred = *preds; pred; pred = next)
665 next = pred->ep_next;
666 free (pred);
668 *preds = NULL;
671 /* Return true when we can store prediction on insn INSN.
672 At the moment we represent predictions only on conditional
673 jumps, not at computed jump or other complicated cases. */
674 static bool
675 can_predict_insn_p (const rtx_insn *insn)
677 return (JUMP_P (insn)
678 && any_condjump_p (insn)
679 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
682 /* Predict edge E by given predictor if possible. */
684 void
685 predict_edge_def (edge e, enum br_predictor predictor,
686 enum prediction taken)
688 int probability = predictor_info[(int) predictor].hitrate;
690 if (taken != TAKEN)
691 probability = REG_BR_PROB_BASE - probability;
693 predict_edge (e, predictor, probability);
696 /* Invert all branch predictions or probability notes in the INSN. This needs
697 to be done each time we invert the condition used by the jump. */
699 void
700 invert_br_probabilities (rtx insn)
702 rtx note;
704 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
705 if (REG_NOTE_KIND (note) == REG_BR_PROB)
706 XINT (note, 0) = profile_probability::from_reg_br_prob_note
707 (XINT (note, 0)).invert ().to_reg_br_prob_note ();
708 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
709 XEXP (XEXP (note, 0), 1)
710 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
713 /* Dump information about the branch prediction to the output file. */
715 static void
716 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
717 basic_block bb, enum predictor_reason reason = REASON_NONE,
718 edge ep_edge = NULL)
720 edge e = ep_edge;
721 edge_iterator ei;
723 if (!file)
724 return;
726 if (e == NULL)
727 FOR_EACH_EDGE (e, ei, bb->succs)
728 if (! (e->flags & EDGE_FALLTHRU))
729 break;
731 char edge_info_str[128];
732 if (ep_edge)
733 sprintf (edge_info_str, " of edge %d->%d", ep_edge->src->index,
734 ep_edge->dest->index);
735 else
736 edge_info_str[0] = '\0';
738 fprintf (file, " %s heuristics%s%s: %.2f%%",
739 predictor_info[predictor].name,
740 edge_info_str, reason_messages[reason],
741 probability * 100.0 / REG_BR_PROB_BASE);
743 if (bb->count.initialized_p ())
745 fprintf (file, " exec ");
746 bb->count.dump (file);
747 if (e)
749 fprintf (file, " hit ");
750 e->count ().dump (file);
751 fprintf (file, " (%.1f%%)", e->count ().to_gcov_type() * 100.0
752 / bb->count.to_gcov_type ());
756 fprintf (file, "\n");
758 /* Print output that be easily read by analyze_brprob.py script. We are
759 interested only in counts that are read from GCDA files. */
760 if (dump_file && (dump_flags & TDF_DETAILS)
761 && bb->count.precise_p ()
762 && reason == REASON_NONE)
764 gcc_assert (e->count ().precise_p ());
765 fprintf (file, ";;heuristics;%s;%" PRId64 ";%" PRId64 ";%.1f;\n",
766 predictor_info[predictor].name,
767 bb->count.to_gcov_type (), e->count ().to_gcov_type (),
768 probability * 100.0 / REG_BR_PROB_BASE);
772 /* Return true if STMT is known to be unlikely executed. */
774 static bool
775 unlikely_executed_stmt_p (gimple *stmt)
777 if (!is_gimple_call (stmt))
778 return false;
779 /* NORETURN attribute alone is not strong enough: exit() may be quite
780 likely executed once during program run. */
781 if (gimple_call_fntype (stmt)
782 && lookup_attribute ("cold",
783 TYPE_ATTRIBUTES (gimple_call_fntype (stmt)))
784 && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl)))
785 return true;
786 tree decl = gimple_call_fndecl (stmt);
787 if (!decl)
788 return false;
789 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl))
790 && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl)))
791 return true;
793 cgraph_node *n = cgraph_node::get (decl);
794 if (!n)
795 return false;
797 availability avail;
798 n = n->ultimate_alias_target (&avail);
799 if (avail < AVAIL_AVAILABLE)
800 return false;
801 if (!n->analyzed
802 || n->decl == current_function_decl)
803 return false;
804 return n->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED;
807 /* Return true if BB is unlikely executed. */
809 static bool
810 unlikely_executed_bb_p (basic_block bb)
812 if (bb->count == profile_count::zero ())
813 return true;
814 if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) || bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
815 return false;
816 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
817 !gsi_end_p (gsi); gsi_next (&gsi))
819 if (unlikely_executed_stmt_p (gsi_stmt (gsi)))
820 return true;
821 if (stmt_can_terminate_bb_p (gsi_stmt (gsi)))
822 return false;
824 return false;
827 /* We can not predict the probabilities of outgoing edges of bb. Set them
828 evenly and hope for the best. If UNLIKELY_EDGES is not null, distribute
829 even probability for all edges not mentioned in the set. These edges
830 are given PROB_VERY_UNLIKELY probability. Similarly for LIKELY_EDGES,
831 if we have exactly one likely edge, make the other edges predicted
832 as not probable. */
834 static void
835 set_even_probabilities (basic_block bb,
836 hash_set<edge> *unlikely_edges = NULL,
837 hash_set<edge_prediction *> *likely_edges = NULL)
839 unsigned nedges = 0, unlikely_count = 0;
840 edge e = NULL;
841 edge_iterator ei;
842 profile_probability all = profile_probability::always ();
844 FOR_EACH_EDGE (e, ei, bb->succs)
845 if (e->probability.initialized_p ())
846 all -= e->probability;
847 else if (!unlikely_executed_edge_p (e))
849 nedges++;
850 if (unlikely_edges != NULL && unlikely_edges->contains (e))
852 all -= profile_probability::very_unlikely ();
853 unlikely_count++;
857 /* Make the distribution even if all edges are unlikely. */
858 unsigned likely_count = likely_edges ? likely_edges->elements () : 0;
859 if (unlikely_count == nedges)
861 unlikely_edges = NULL;
862 unlikely_count = 0;
865 /* If we have one likely edge, then use its probability and distribute
866 remaining probabilities as even. */
867 if (likely_count == 1)
869 FOR_EACH_EDGE (e, ei, bb->succs)
870 if (e->probability.initialized_p ())
872 else if (!unlikely_executed_edge_p (e))
874 edge_prediction *prediction = *likely_edges->begin ();
875 int p = prediction->ep_probability;
876 profile_probability prob
877 = profile_probability::from_reg_br_prob_base (p);
878 profile_probability remainder = prob.invert ();
880 if (prediction->ep_edge == e)
881 e->probability = prob;
882 else
883 e->probability = remainder.apply_scale (1, nedges - 1);
885 else
886 e->probability = profile_probability::never ();
888 else
890 /* Make all unlikely edges unlikely and the rest will have even
891 probability. */
892 unsigned scale = nedges - unlikely_count;
893 FOR_EACH_EDGE (e, ei, bb->succs)
894 if (e->probability.initialized_p ())
896 else if (!unlikely_executed_edge_p (e))
898 if (unlikely_edges != NULL && unlikely_edges->contains (e))
899 e->probability = profile_probability::very_unlikely ();
900 else
901 e->probability = all.apply_scale (1, scale);
903 else
904 e->probability = profile_probability::never ();
908 /* Add REG_BR_PROB note to JUMP with PROB. */
910 void
911 add_reg_br_prob_note (rtx_insn *jump, profile_probability prob)
913 gcc_checking_assert (JUMP_P (jump) && !find_reg_note (jump, REG_BR_PROB, 0));
914 add_int_reg_note (jump, REG_BR_PROB, prob.to_reg_br_prob_note ());
917 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
918 note if not already present. Remove now useless REG_BR_PRED notes. */
920 static void
921 combine_predictions_for_insn (rtx_insn *insn, basic_block bb)
923 rtx prob_note;
924 rtx *pnote;
925 rtx note;
926 int best_probability = PROB_EVEN;
927 enum br_predictor best_predictor = END_PREDICTORS;
928 int combined_probability = REG_BR_PROB_BASE / 2;
929 int d;
930 bool first_match = false;
931 bool found = false;
933 if (!can_predict_insn_p (insn))
935 set_even_probabilities (bb);
936 return;
939 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
940 pnote = &REG_NOTES (insn);
941 if (dump_file)
942 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
943 bb->index);
945 /* We implement "first match" heuristics and use probability guessed
946 by predictor with smallest index. */
947 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
948 if (REG_NOTE_KIND (note) == REG_BR_PRED)
950 enum br_predictor predictor = ((enum br_predictor)
951 INTVAL (XEXP (XEXP (note, 0), 0)));
952 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
954 found = true;
955 if (best_predictor > predictor
956 && predictor_info[predictor].flags & PRED_FLAG_FIRST_MATCH)
957 best_probability = probability, best_predictor = predictor;
959 d = (combined_probability * probability
960 + (REG_BR_PROB_BASE - combined_probability)
961 * (REG_BR_PROB_BASE - probability));
963 /* Use FP math to avoid overflows of 32bit integers. */
964 if (d == 0)
965 /* If one probability is 0% and one 100%, avoid division by zero. */
966 combined_probability = REG_BR_PROB_BASE / 2;
967 else
968 combined_probability = (((double) combined_probability) * probability
969 * REG_BR_PROB_BASE / d + 0.5);
972 /* Decide which heuristic to use. In case we didn't match anything,
973 use no_prediction heuristic, in case we did match, use either
974 first match or Dempster-Shaffer theory depending on the flags. */
976 if (best_predictor != END_PREDICTORS)
977 first_match = true;
979 if (!found)
980 dump_prediction (dump_file, PRED_NO_PREDICTION,
981 combined_probability, bb);
982 else
984 if (!first_match)
985 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
986 bb, !first_match ? REASON_NONE : REASON_IGNORED);
987 else
988 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
989 bb, first_match ? REASON_NONE : REASON_IGNORED);
992 if (first_match)
993 combined_probability = best_probability;
994 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb);
996 while (*pnote)
998 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
1000 enum br_predictor predictor = ((enum br_predictor)
1001 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
1002 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
1004 dump_prediction (dump_file, predictor, probability, bb,
1005 (!first_match || best_predictor == predictor)
1006 ? REASON_NONE : REASON_IGNORED);
1007 *pnote = XEXP (*pnote, 1);
1009 else
1010 pnote = &XEXP (*pnote, 1);
1013 if (!prob_note)
1015 profile_probability p
1016 = profile_probability::from_reg_br_prob_base (combined_probability);
1017 add_reg_br_prob_note (insn, p);
1019 /* Save the prediction into CFG in case we are seeing non-degenerated
1020 conditional jump. */
1021 if (!single_succ_p (bb))
1023 BRANCH_EDGE (bb)->probability = p;
1024 FALLTHRU_EDGE (bb)->probability
1025 = BRANCH_EDGE (bb)->probability.invert ();
1028 else if (!single_succ_p (bb))
1030 profile_probability prob = profile_probability::from_reg_br_prob_note
1031 (XINT (prob_note, 0));
1033 BRANCH_EDGE (bb)->probability = prob;
1034 FALLTHRU_EDGE (bb)->probability = prob.invert ();
1036 else
1037 single_succ_edge (bb)->probability = profile_probability::always ();
1040 /* Edge prediction hash traits. */
1042 struct predictor_hash: pointer_hash <edge_prediction>
1045 static inline hashval_t hash (const edge_prediction *);
1046 static inline bool equal (const edge_prediction *, const edge_prediction *);
1049 /* Calculate hash value of an edge prediction P based on predictor and
1050 normalized probability. */
1052 inline hashval_t
1053 predictor_hash::hash (const edge_prediction *p)
1055 inchash::hash hstate;
1056 hstate.add_int (p->ep_predictor);
1058 int prob = p->ep_probability;
1059 if (prob > REG_BR_PROB_BASE / 2)
1060 prob = REG_BR_PROB_BASE - prob;
1062 hstate.add_int (prob);
1064 return hstate.end ();
1067 /* Return true whether edge predictions P1 and P2 use the same predictor and
1068 have equal (or opposed probability). */
1070 inline bool
1071 predictor_hash::equal (const edge_prediction *p1, const edge_prediction *p2)
1073 return (p1->ep_predictor == p2->ep_predictor
1074 && (p1->ep_probability == p2->ep_probability
1075 || p1->ep_probability == REG_BR_PROB_BASE - p2->ep_probability));
1078 struct predictor_hash_traits: predictor_hash,
1079 typed_noop_remove <edge_prediction *> {};
1081 /* Return true if edge prediction P is not in DATA hash set. */
1083 static bool
1084 not_removed_prediction_p (edge_prediction *p, void *data)
1086 hash_set<edge_prediction *> *remove = (hash_set<edge_prediction *> *) data;
1087 return !remove->contains (p);
1090 /* Prune predictions for a basic block BB. Currently we do following
1091 clean-up steps:
1093 1) remove duplicate prediction that is guessed with the same probability
1094 (different than 1/2) to both edge
1095 2) remove duplicates for a prediction that belongs with the same probability
1096 to a single edge
1100 static void
1101 prune_predictions_for_bb (basic_block bb)
1103 edge_prediction **preds = bb_predictions->get (bb);
1105 if (preds)
1107 hash_table <predictor_hash_traits> s (13);
1108 hash_set <edge_prediction *> remove;
1110 /* Step 1: identify predictors that should be removed. */
1111 for (edge_prediction *pred = *preds; pred; pred = pred->ep_next)
1113 edge_prediction *existing = s.find (pred);
1114 if (existing)
1116 if (pred->ep_edge == existing->ep_edge
1117 && pred->ep_probability == existing->ep_probability)
1119 /* Remove a duplicate predictor. */
1120 dump_prediction (dump_file, pred->ep_predictor,
1121 pred->ep_probability, bb,
1122 REASON_SINGLE_EDGE_DUPLICATE, pred->ep_edge);
1124 remove.add (pred);
1126 else if (pred->ep_edge != existing->ep_edge
1127 && pred->ep_probability == existing->ep_probability
1128 && pred->ep_probability != REG_BR_PROB_BASE / 2)
1130 /* Remove both predictors as they predict the same
1131 for both edges. */
1132 dump_prediction (dump_file, existing->ep_predictor,
1133 pred->ep_probability, bb,
1134 REASON_EDGE_PAIR_DUPLICATE,
1135 existing->ep_edge);
1136 dump_prediction (dump_file, pred->ep_predictor,
1137 pred->ep_probability, bb,
1138 REASON_EDGE_PAIR_DUPLICATE,
1139 pred->ep_edge);
1141 remove.add (existing);
1142 remove.add (pred);
1146 edge_prediction **slot2 = s.find_slot (pred, INSERT);
1147 *slot2 = pred;
1150 /* Step 2: Remove predictors. */
1151 filter_predictions (preds, not_removed_prediction_p, &remove);
1155 /* Combine predictions into single probability and store them into CFG.
1156 Remove now useless prediction entries.
1157 If DRY_RUN is set, only produce dumps and do not modify profile. */
1159 static void
1160 combine_predictions_for_bb (basic_block bb, bool dry_run)
1162 int best_probability = PROB_EVEN;
1163 enum br_predictor best_predictor = END_PREDICTORS;
1164 int combined_probability = REG_BR_PROB_BASE / 2;
1165 int d;
1166 bool first_match = false;
1167 bool found = false;
1168 struct edge_prediction *pred;
1169 int nedges = 0;
1170 edge e, first = NULL, second = NULL;
1171 edge_iterator ei;
1172 int nzero = 0;
1173 int nunknown = 0;
1175 FOR_EACH_EDGE (e, ei, bb->succs)
1177 if (!unlikely_executed_edge_p (e))
1179 nedges ++;
1180 if (first && !second)
1181 second = e;
1182 if (!first)
1183 first = e;
1185 else if (!e->probability.initialized_p ())
1186 e->probability = profile_probability::never ();
1187 if (!e->probability.initialized_p ())
1188 nunknown++;
1189 else if (e->probability == profile_probability::never ())
1190 nzero++;
1193 /* When there is no successor or only one choice, prediction is easy.
1195 When we have a basic block with more than 2 successors, the situation
1196 is more complicated as DS theory cannot be used literally.
1197 More precisely, let's assume we predicted edge e1 with probability p1,
1198 thus: m1({b1}) = p1. As we're going to combine more than 2 edges, we
1199 need to find probability of e.g. m1({b2}), which we don't know.
1200 The only approximation is to equally distribute 1-p1 to all edges
1201 different from b1.
1203 According to numbers we've got from SPEC2006 benchark, there's only
1204 one interesting reliable predictor (noreturn call), which can be
1205 handled with a bit easier approach. */
1206 if (nedges != 2)
1208 hash_set<edge> unlikely_edges (4);
1209 hash_set<edge_prediction *> likely_edges (4);
1211 /* Identify all edges that have a probability close to very unlikely.
1212 Doing the approach for very unlikely doesn't worth for doing as
1213 there's no such probability in SPEC2006 benchmark. */
1214 edge_prediction **preds = bb_predictions->get (bb);
1215 if (preds)
1216 for (pred = *preds; pred; pred = pred->ep_next)
1218 if (pred->ep_probability <= PROB_VERY_UNLIKELY)
1219 unlikely_edges.add (pred->ep_edge);
1220 if (pred->ep_probability >= PROB_VERY_LIKELY
1221 || pred->ep_predictor == PRED_BUILTIN_EXPECT)
1222 likely_edges.add (pred);
1225 if (!dry_run)
1226 set_even_probabilities (bb, &unlikely_edges, &likely_edges);
1227 clear_bb_predictions (bb);
1228 if (dump_file)
1230 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
1231 if (unlikely_edges.elements () == 0)
1232 fprintf (dump_file,
1233 "%i edges in bb %i predicted to even probabilities\n",
1234 nedges, bb->index);
1235 else
1237 fprintf (dump_file,
1238 "%i edges in bb %i predicted with some unlikely edges\n",
1239 nedges, bb->index);
1240 FOR_EACH_EDGE (e, ei, bb->succs)
1241 if (!unlikely_executed_edge_p (e))
1242 dump_prediction (dump_file, PRED_COMBINED,
1243 e->probability.to_reg_br_prob_base (), bb, REASON_NONE, e);
1246 return;
1249 if (dump_file)
1250 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
1252 prune_predictions_for_bb (bb);
1254 edge_prediction **preds = bb_predictions->get (bb);
1256 if (preds)
1258 /* We implement "first match" heuristics and use probability guessed
1259 by predictor with smallest index. */
1260 for (pred = *preds; pred; pred = pred->ep_next)
1262 enum br_predictor predictor = pred->ep_predictor;
1263 int probability = pred->ep_probability;
1265 if (pred->ep_edge != first)
1266 probability = REG_BR_PROB_BASE - probability;
1268 found = true;
1269 /* First match heuristics would be widly confused if we predicted
1270 both directions. */
1271 if (best_predictor > predictor
1272 && predictor_info[predictor].flags & PRED_FLAG_FIRST_MATCH)
1274 struct edge_prediction *pred2;
1275 int prob = probability;
1277 for (pred2 = (struct edge_prediction *) *preds;
1278 pred2; pred2 = pred2->ep_next)
1279 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
1281 int probability2 = pred2->ep_probability;
1283 if (pred2->ep_edge != first)
1284 probability2 = REG_BR_PROB_BASE - probability2;
1286 if ((probability < REG_BR_PROB_BASE / 2) !=
1287 (probability2 < REG_BR_PROB_BASE / 2))
1288 break;
1290 /* If the same predictor later gave better result, go for it! */
1291 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
1292 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
1293 prob = probability2;
1295 if (!pred2)
1296 best_probability = prob, best_predictor = predictor;
1299 d = (combined_probability * probability
1300 + (REG_BR_PROB_BASE - combined_probability)
1301 * (REG_BR_PROB_BASE - probability));
1303 /* Use FP math to avoid overflows of 32bit integers. */
1304 if (d == 0)
1305 /* If one probability is 0% and one 100%, avoid division by zero. */
1306 combined_probability = REG_BR_PROB_BASE / 2;
1307 else
1308 combined_probability = (((double) combined_probability)
1309 * probability
1310 * REG_BR_PROB_BASE / d + 0.5);
1314 /* Decide which heuristic to use. In case we didn't match anything,
1315 use no_prediction heuristic, in case we did match, use either
1316 first match or Dempster-Shaffer theory depending on the flags. */
1318 if (best_predictor != END_PREDICTORS)
1319 first_match = true;
1321 if (!found)
1322 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb);
1323 else
1325 if (!first_match)
1326 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
1327 !first_match ? REASON_NONE : REASON_IGNORED);
1328 else
1329 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
1330 first_match ? REASON_NONE : REASON_IGNORED);
1333 if (first_match)
1334 combined_probability = best_probability;
1335 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb);
1337 if (preds)
1339 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
1341 enum br_predictor predictor = pred->ep_predictor;
1342 int probability = pred->ep_probability;
1344 dump_prediction (dump_file, predictor, probability, bb,
1345 (!first_match || best_predictor == predictor)
1346 ? REASON_NONE : REASON_IGNORED, pred->ep_edge);
1349 clear_bb_predictions (bb);
1352 /* If we have only one successor which is unknown, we can compute missing
1353 probablity. */
1354 if (nunknown == 1)
1356 profile_probability prob = profile_probability::always ();
1357 edge missing = NULL;
1359 FOR_EACH_EDGE (e, ei, bb->succs)
1360 if (e->probability.initialized_p ())
1361 prob -= e->probability;
1362 else if (missing == NULL)
1363 missing = e;
1364 else
1365 gcc_unreachable ();
1366 missing->probability = prob;
1368 /* If nothing is unknown, we have nothing to update. */
1369 else if (!nunknown && nzero != (int)EDGE_COUNT (bb->succs))
1371 else if (!dry_run)
1373 first->probability
1374 = profile_probability::from_reg_br_prob_base (combined_probability);
1375 second->probability = first->probability.invert ();
1379 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
1380 Return the SSA_NAME if the condition satisfies, NULL otherwise.
1382 T1 and T2 should be one of the following cases:
1383 1. T1 is SSA_NAME, T2 is NULL
1384 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
1385 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
1387 static tree
1388 strips_small_constant (tree t1, tree t2)
1390 tree ret = NULL;
1391 int value = 0;
1393 if (!t1)
1394 return NULL;
1395 else if (TREE_CODE (t1) == SSA_NAME)
1396 ret = t1;
1397 else if (tree_fits_shwi_p (t1))
1398 value = tree_to_shwi (t1);
1399 else
1400 return NULL;
1402 if (!t2)
1403 return ret;
1404 else if (tree_fits_shwi_p (t2))
1405 value = tree_to_shwi (t2);
1406 else if (TREE_CODE (t2) == SSA_NAME)
1408 if (ret)
1409 return NULL;
1410 else
1411 ret = t2;
1414 if (value <= 4 && value >= -4)
1415 return ret;
1416 else
1417 return NULL;
1420 /* Return the SSA_NAME in T or T's operands.
1421 Return NULL if SSA_NAME cannot be found. */
1423 static tree
1424 get_base_value (tree t)
1426 if (TREE_CODE (t) == SSA_NAME)
1427 return t;
1429 if (!BINARY_CLASS_P (t))
1430 return NULL;
1432 switch (TREE_OPERAND_LENGTH (t))
1434 case 1:
1435 return strips_small_constant (TREE_OPERAND (t, 0), NULL);
1436 case 2:
1437 return strips_small_constant (TREE_OPERAND (t, 0),
1438 TREE_OPERAND (t, 1));
1439 default:
1440 return NULL;
1444 /* Check the compare STMT in LOOP. If it compares an induction
1445 variable to a loop invariant, return true, and save
1446 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1447 Otherwise return false and set LOOP_INVAIANT to NULL. */
1449 static bool
1450 is_comparison_with_loop_invariant_p (gcond *stmt, struct loop *loop,
1451 tree *loop_invariant,
1452 enum tree_code *compare_code,
1453 tree *loop_step,
1454 tree *loop_iv_base)
1456 tree op0, op1, bound, base;
1457 affine_iv iv0, iv1;
1458 enum tree_code code;
1459 tree step;
1461 code = gimple_cond_code (stmt);
1462 *loop_invariant = NULL;
1464 switch (code)
1466 case GT_EXPR:
1467 case GE_EXPR:
1468 case NE_EXPR:
1469 case LT_EXPR:
1470 case LE_EXPR:
1471 case EQ_EXPR:
1472 break;
1474 default:
1475 return false;
1478 op0 = gimple_cond_lhs (stmt);
1479 op1 = gimple_cond_rhs (stmt);
1481 if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1482 || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1483 return false;
1484 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1485 return false;
1486 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1487 return false;
1488 if (TREE_CODE (iv0.step) != INTEGER_CST
1489 || TREE_CODE (iv1.step) != INTEGER_CST)
1490 return false;
1491 if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1492 || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1493 return false;
1495 if (integer_zerop (iv0.step))
1497 if (code != NE_EXPR && code != EQ_EXPR)
1498 code = invert_tree_comparison (code, false);
1499 bound = iv0.base;
1500 base = iv1.base;
1501 if (tree_fits_shwi_p (iv1.step))
1502 step = iv1.step;
1503 else
1504 return false;
1506 else
1508 bound = iv1.base;
1509 base = iv0.base;
1510 if (tree_fits_shwi_p (iv0.step))
1511 step = iv0.step;
1512 else
1513 return false;
1516 if (TREE_CODE (bound) != INTEGER_CST)
1517 bound = get_base_value (bound);
1518 if (!bound)
1519 return false;
1520 if (TREE_CODE (base) != INTEGER_CST)
1521 base = get_base_value (base);
1522 if (!base)
1523 return false;
1525 *loop_invariant = bound;
1526 *compare_code = code;
1527 *loop_step = step;
1528 *loop_iv_base = base;
1529 return true;
1532 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1534 static bool
1535 expr_coherent_p (tree t1, tree t2)
1537 gimple *stmt;
1538 tree ssa_name_1 = NULL;
1539 tree ssa_name_2 = NULL;
1541 gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1542 gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1544 if (t1 == t2)
1545 return true;
1547 if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1548 return true;
1549 if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1550 return false;
1552 /* Check to see if t1 is expressed/defined with t2. */
1553 stmt = SSA_NAME_DEF_STMT (t1);
1554 gcc_assert (stmt != NULL);
1555 if (is_gimple_assign (stmt))
1557 ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1558 if (ssa_name_1 && ssa_name_1 == t2)
1559 return true;
1562 /* Check to see if t2 is expressed/defined with t1. */
1563 stmt = SSA_NAME_DEF_STMT (t2);
1564 gcc_assert (stmt != NULL);
1565 if (is_gimple_assign (stmt))
1567 ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1568 if (ssa_name_2 && ssa_name_2 == t1)
1569 return true;
1572 /* Compare if t1 and t2's def_stmts are identical. */
1573 if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1574 return true;
1575 else
1576 return false;
1579 /* Return true if E is predicted by one of loop heuristics. */
1581 static bool
1582 predicted_by_loop_heuristics_p (basic_block bb)
1584 struct edge_prediction *i;
1585 edge_prediction **preds = bb_predictions->get (bb);
1587 if (!preds)
1588 return false;
1590 for (i = *preds; i; i = i->ep_next)
1591 if (i->ep_predictor == PRED_LOOP_ITERATIONS_GUESSED
1592 || i->ep_predictor == PRED_LOOP_ITERATIONS_MAX
1593 || i->ep_predictor == PRED_LOOP_ITERATIONS
1594 || i->ep_predictor == PRED_LOOP_EXIT
1595 || i->ep_predictor == PRED_LOOP_EXIT_WITH_RECURSION
1596 || i->ep_predictor == PRED_LOOP_EXTRA_EXIT)
1597 return true;
1598 return false;
1601 /* Predict branch probability of BB when BB contains a branch that compares
1602 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1603 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1605 E.g.
1606 for (int i = 0; i < bound; i++) {
1607 if (i < bound - 2)
1608 computation_1();
1609 else
1610 computation_2();
1613 In this loop, we will predict the branch inside the loop to be taken. */
1615 static void
1616 predict_iv_comparison (struct loop *loop, basic_block bb,
1617 tree loop_bound_var,
1618 tree loop_iv_base_var,
1619 enum tree_code loop_bound_code,
1620 int loop_bound_step)
1622 gimple *stmt;
1623 tree compare_var, compare_base;
1624 enum tree_code compare_code;
1625 tree compare_step_var;
1626 edge then_edge;
1627 edge_iterator ei;
1629 if (predicted_by_loop_heuristics_p (bb))
1630 return;
1632 stmt = last_stmt (bb);
1633 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1634 return;
1635 if (!is_comparison_with_loop_invariant_p (as_a <gcond *> (stmt),
1636 loop, &compare_var,
1637 &compare_code,
1638 &compare_step_var,
1639 &compare_base))
1640 return;
1642 /* Find the taken edge. */
1643 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1644 if (then_edge->flags & EDGE_TRUE_VALUE)
1645 break;
1647 /* When comparing an IV to a loop invariant, NE is more likely to be
1648 taken while EQ is more likely to be not-taken. */
1649 if (compare_code == NE_EXPR)
1651 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1652 return;
1654 else if (compare_code == EQ_EXPR)
1656 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1657 return;
1660 if (!expr_coherent_p (loop_iv_base_var, compare_base))
1661 return;
1663 /* If loop bound, base and compare bound are all constants, we can
1664 calculate the probability directly. */
1665 if (tree_fits_shwi_p (loop_bound_var)
1666 && tree_fits_shwi_p (compare_var)
1667 && tree_fits_shwi_p (compare_base))
1669 int probability;
1670 wi::overflow_type overflow;
1671 bool overall_overflow = false;
1672 widest_int compare_count, tem;
1674 /* (loop_bound - base) / compare_step */
1675 tem = wi::sub (wi::to_widest (loop_bound_var),
1676 wi::to_widest (compare_base), SIGNED, &overflow);
1677 overall_overflow |= overflow;
1678 widest_int loop_count = wi::div_trunc (tem,
1679 wi::to_widest (compare_step_var),
1680 SIGNED, &overflow);
1681 overall_overflow |= overflow;
1683 if (!wi::neg_p (wi::to_widest (compare_step_var))
1684 ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1686 /* (loop_bound - compare_bound) / compare_step */
1687 tem = wi::sub (wi::to_widest (loop_bound_var),
1688 wi::to_widest (compare_var), SIGNED, &overflow);
1689 overall_overflow |= overflow;
1690 compare_count = wi::div_trunc (tem, wi::to_widest (compare_step_var),
1691 SIGNED, &overflow);
1692 overall_overflow |= overflow;
1694 else
1696 /* (compare_bound - base) / compare_step */
1697 tem = wi::sub (wi::to_widest (compare_var),
1698 wi::to_widest (compare_base), SIGNED, &overflow);
1699 overall_overflow |= overflow;
1700 compare_count = wi::div_trunc (tem, wi::to_widest (compare_step_var),
1701 SIGNED, &overflow);
1702 overall_overflow |= overflow;
1704 if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1705 ++compare_count;
1706 if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1707 ++loop_count;
1708 if (wi::neg_p (compare_count))
1709 compare_count = 0;
1710 if (wi::neg_p (loop_count))
1711 loop_count = 0;
1712 if (loop_count == 0)
1713 probability = 0;
1714 else if (wi::cmps (compare_count, loop_count) == 1)
1715 probability = REG_BR_PROB_BASE;
1716 else
1718 tem = compare_count * REG_BR_PROB_BASE;
1719 tem = wi::udiv_trunc (tem, loop_count);
1720 probability = tem.to_uhwi ();
1723 /* FIXME: The branch prediction seems broken. It has only 20% hitrate. */
1724 if (!overall_overflow)
1725 predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1727 return;
1730 if (expr_coherent_p (loop_bound_var, compare_var))
1732 if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1733 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1734 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1735 else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1736 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1737 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1738 else if (loop_bound_code == NE_EXPR)
1740 /* If the loop backedge condition is "(i != bound)", we do
1741 the comparison based on the step of IV:
1742 * step < 0 : backedge condition is like (i > bound)
1743 * step > 0 : backedge condition is like (i < bound) */
1744 gcc_assert (loop_bound_step != 0);
1745 if (loop_bound_step > 0
1746 && (compare_code == LT_EXPR
1747 || compare_code == LE_EXPR))
1748 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1749 else if (loop_bound_step < 0
1750 && (compare_code == GT_EXPR
1751 || compare_code == GE_EXPR))
1752 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1753 else
1754 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1756 else
1757 /* The branch is predicted not-taken if loop_bound_code is
1758 opposite with compare_code. */
1759 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1761 else if (expr_coherent_p (loop_iv_base_var, compare_var))
1763 /* For cases like:
1764 for (i = s; i < h; i++)
1765 if (i > s + 2) ....
1766 The branch should be predicted taken. */
1767 if (loop_bound_step > 0
1768 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1769 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1770 else if (loop_bound_step < 0
1771 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1772 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1773 else
1774 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1778 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1779 exits are resulted from short-circuit conditions that will generate an
1780 if_tmp. E.g.:
1782 if (foo() || global > 10)
1783 break;
1785 This will be translated into:
1787 BB3:
1788 loop header...
1789 BB4:
1790 if foo() goto BB6 else goto BB5
1791 BB5:
1792 if global > 10 goto BB6 else goto BB7
1793 BB6:
1794 goto BB7
1795 BB7:
1796 iftmp = (PHI 0(BB5), 1(BB6))
1797 if iftmp == 1 goto BB8 else goto BB3
1798 BB8:
1799 outside of the loop...
1801 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1802 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1803 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1804 exits to predict them using PRED_LOOP_EXTRA_EXIT. */
1806 static void
1807 predict_extra_loop_exits (edge exit_edge)
1809 unsigned i;
1810 bool check_value_one;
1811 gimple *lhs_def_stmt;
1812 gphi *phi_stmt;
1813 tree cmp_rhs, cmp_lhs;
1814 gimple *last;
1815 gcond *cmp_stmt;
1817 last = last_stmt (exit_edge->src);
1818 if (!last)
1819 return;
1820 cmp_stmt = dyn_cast <gcond *> (last);
1821 if (!cmp_stmt)
1822 return;
1824 cmp_rhs = gimple_cond_rhs (cmp_stmt);
1825 cmp_lhs = gimple_cond_lhs (cmp_stmt);
1826 if (!TREE_CONSTANT (cmp_rhs)
1827 || !(integer_zerop (cmp_rhs) || integer_onep (cmp_rhs)))
1828 return;
1829 if (TREE_CODE (cmp_lhs) != SSA_NAME)
1830 return;
1832 /* If check_value_one is true, only the phi_args with value '1' will lead
1833 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1834 loop exit. */
1835 check_value_one = (((integer_onep (cmp_rhs))
1836 ^ (gimple_cond_code (cmp_stmt) == EQ_EXPR))
1837 ^ ((exit_edge->flags & EDGE_TRUE_VALUE) != 0));
1839 lhs_def_stmt = SSA_NAME_DEF_STMT (cmp_lhs);
1840 if (!lhs_def_stmt)
1841 return;
1843 phi_stmt = dyn_cast <gphi *> (lhs_def_stmt);
1844 if (!phi_stmt)
1845 return;
1847 for (i = 0; i < gimple_phi_num_args (phi_stmt); i++)
1849 edge e1;
1850 edge_iterator ei;
1851 tree val = gimple_phi_arg_def (phi_stmt, i);
1852 edge e = gimple_phi_arg_edge (phi_stmt, i);
1854 if (!TREE_CONSTANT (val) || !(integer_zerop (val) || integer_onep (val)))
1855 continue;
1856 if ((check_value_one ^ integer_onep (val)) == 1)
1857 continue;
1858 if (EDGE_COUNT (e->src->succs) != 1)
1860 predict_paths_leading_to_edge (e, PRED_LOOP_EXTRA_EXIT, NOT_TAKEN);
1861 continue;
1864 FOR_EACH_EDGE (e1, ei, e->src->preds)
1865 predict_paths_leading_to_edge (e1, PRED_LOOP_EXTRA_EXIT, NOT_TAKEN);
1870 /* Predict edge probabilities by exploiting loop structure. */
1872 static void
1873 predict_loops (void)
1875 struct loop *loop;
1876 basic_block bb;
1877 hash_set <struct loop *> with_recursion(10);
1879 FOR_EACH_BB_FN (bb, cfun)
1881 gimple_stmt_iterator gsi;
1882 tree decl;
1884 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1885 if (is_gimple_call (gsi_stmt (gsi))
1886 && (decl = gimple_call_fndecl (gsi_stmt (gsi))) != NULL
1887 && recursive_call_p (current_function_decl, decl))
1889 loop = bb->loop_father;
1890 while (loop && !with_recursion.add (loop))
1891 loop = loop_outer (loop);
1895 /* Try to predict out blocks in a loop that are not part of a
1896 natural loop. */
1897 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
1899 basic_block bb, *bbs;
1900 unsigned j, n_exits = 0;
1901 vec<edge> exits;
1902 struct tree_niter_desc niter_desc;
1903 edge ex;
1904 struct nb_iter_bound *nb_iter;
1905 enum tree_code loop_bound_code = ERROR_MARK;
1906 tree loop_bound_step = NULL;
1907 tree loop_bound_var = NULL;
1908 tree loop_iv_base = NULL;
1909 gcond *stmt = NULL;
1910 bool recursion = with_recursion.contains (loop);
1912 exits = get_loop_exit_edges (loop);
1913 FOR_EACH_VEC_ELT (exits, j, ex)
1914 if (!unlikely_executed_edge_p (ex) && !(ex->flags & EDGE_ABNORMAL_CALL))
1915 n_exits ++;
1916 if (!n_exits)
1918 exits.release ();
1919 continue;
1922 if (dump_file && (dump_flags & TDF_DETAILS))
1923 fprintf (dump_file, "Predicting loop %i%s with %i exits.\n",
1924 loop->num, recursion ? " (with recursion)":"", n_exits);
1925 if (dump_file && (dump_flags & TDF_DETAILS)
1926 && max_loop_iterations_int (loop) >= 0)
1928 fprintf (dump_file,
1929 "Loop %d iterates at most %i times.\n", loop->num,
1930 (int)max_loop_iterations_int (loop));
1932 if (dump_file && (dump_flags & TDF_DETAILS)
1933 && likely_max_loop_iterations_int (loop) >= 0)
1935 fprintf (dump_file, "Loop %d likely iterates at most %i times.\n",
1936 loop->num, (int)likely_max_loop_iterations_int (loop));
1939 FOR_EACH_VEC_ELT (exits, j, ex)
1941 tree niter = NULL;
1942 HOST_WIDE_INT nitercst;
1943 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
1944 int probability;
1945 enum br_predictor predictor;
1946 widest_int nit;
1948 if (unlikely_executed_edge_p (ex)
1949 || (ex->flags & EDGE_ABNORMAL_CALL))
1950 continue;
1951 /* Loop heuristics do not expect exit conditional to be inside
1952 inner loop. We predict from innermost to outermost loop. */
1953 if (predicted_by_loop_heuristics_p (ex->src))
1955 if (dump_file && (dump_flags & TDF_DETAILS))
1956 fprintf (dump_file, "Skipping exit %i->%i because "
1957 "it is already predicted.\n",
1958 ex->src->index, ex->dest->index);
1959 continue;
1961 predict_extra_loop_exits (ex);
1963 if (number_of_iterations_exit (loop, ex, &niter_desc, false, false))
1964 niter = niter_desc.niter;
1965 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
1966 niter = loop_niter_by_eval (loop, ex);
1967 if (dump_file && (dump_flags & TDF_DETAILS)
1968 && TREE_CODE (niter) == INTEGER_CST)
1970 fprintf (dump_file, "Exit %i->%i %d iterates ",
1971 ex->src->index, ex->dest->index,
1972 loop->num);
1973 print_generic_expr (dump_file, niter, TDF_SLIM);
1974 fprintf (dump_file, " times.\n");
1977 if (TREE_CODE (niter) == INTEGER_CST)
1979 if (tree_fits_uhwi_p (niter)
1980 && max
1981 && compare_tree_int (niter, max - 1) == -1)
1982 nitercst = tree_to_uhwi (niter) + 1;
1983 else
1984 nitercst = max;
1985 predictor = PRED_LOOP_ITERATIONS;
1987 /* If we have just one exit and we can derive some information about
1988 the number of iterations of the loop from the statements inside
1989 the loop, use it to predict this exit. */
1990 else if (n_exits == 1
1991 && estimated_stmt_executions (loop, &nit))
1993 if (wi::gtu_p (nit, max))
1994 nitercst = max;
1995 else
1996 nitercst = nit.to_shwi ();
1997 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1999 /* If we have likely upper bound, trust it for very small iteration
2000 counts. Such loops would otherwise get mispredicted by standard
2001 LOOP_EXIT heuristics. */
2002 else if (n_exits == 1
2003 && likely_max_stmt_executions (loop, &nit)
2004 && wi::ltu_p (nit,
2005 RDIV (REG_BR_PROB_BASE,
2006 REG_BR_PROB_BASE
2007 - predictor_info
2008 [recursion
2009 ? PRED_LOOP_EXIT_WITH_RECURSION
2010 : PRED_LOOP_EXIT].hitrate)))
2012 nitercst = nit.to_shwi ();
2013 predictor = PRED_LOOP_ITERATIONS_MAX;
2015 else
2017 if (dump_file && (dump_flags & TDF_DETAILS))
2018 fprintf (dump_file, "Nothing known about exit %i->%i.\n",
2019 ex->src->index, ex->dest->index);
2020 continue;
2023 if (dump_file && (dump_flags & TDF_DETAILS))
2024 fprintf (dump_file, "Recording prediction to %i iterations by %s.\n",
2025 (int)nitercst, predictor_info[predictor].name);
2026 /* If the prediction for number of iterations is zero, do not
2027 predict the exit edges. */
2028 if (nitercst == 0)
2029 continue;
2031 probability = RDIV (REG_BR_PROB_BASE, nitercst);
2032 predict_edge (ex, predictor, probability);
2034 exits.release ();
2036 /* Find information about loop bound variables. */
2037 for (nb_iter = loop->bounds; nb_iter;
2038 nb_iter = nb_iter->next)
2039 if (nb_iter->stmt
2040 && gimple_code (nb_iter->stmt) == GIMPLE_COND)
2042 stmt = as_a <gcond *> (nb_iter->stmt);
2043 break;
2045 if (!stmt && last_stmt (loop->header)
2046 && gimple_code (last_stmt (loop->header)) == GIMPLE_COND)
2047 stmt = as_a <gcond *> (last_stmt (loop->header));
2048 if (stmt)
2049 is_comparison_with_loop_invariant_p (stmt, loop,
2050 &loop_bound_var,
2051 &loop_bound_code,
2052 &loop_bound_step,
2053 &loop_iv_base);
2055 bbs = get_loop_body (loop);
2057 for (j = 0; j < loop->num_nodes; j++)
2059 edge e;
2060 edge_iterator ei;
2062 bb = bbs[j];
2064 /* Bypass loop heuristics on continue statement. These
2065 statements construct loops via "non-loop" constructs
2066 in the source language and are better to be handled
2067 separately. */
2068 if (predicted_by_p (bb, PRED_CONTINUE))
2070 if (dump_file && (dump_flags & TDF_DETAILS))
2071 fprintf (dump_file, "BB %i predicted by continue.\n",
2072 bb->index);
2073 continue;
2076 /* If we already used more reliable loop exit predictors, do not
2077 bother with PRED_LOOP_EXIT. */
2078 if (!predicted_by_loop_heuristics_p (bb))
2080 /* For loop with many exits we don't want to predict all exits
2081 with the pretty large probability, because if all exits are
2082 considered in row, the loop would be predicted to iterate
2083 almost never. The code to divide probability by number of
2084 exits is very rough. It should compute the number of exits
2085 taken in each patch through function (not the overall number
2086 of exits that might be a lot higher for loops with wide switch
2087 statements in them) and compute n-th square root.
2089 We limit the minimal probability by 2% to avoid
2090 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
2091 as this was causing regression in perl benchmark containing such
2092 a wide loop. */
2094 int probability = ((REG_BR_PROB_BASE
2095 - predictor_info
2096 [recursion
2097 ? PRED_LOOP_EXIT_WITH_RECURSION
2098 : PRED_LOOP_EXIT].hitrate)
2099 / n_exits);
2100 if (probability < HITRATE (2))
2101 probability = HITRATE (2);
2102 FOR_EACH_EDGE (e, ei, bb->succs)
2103 if (e->dest->index < NUM_FIXED_BLOCKS
2104 || !flow_bb_inside_loop_p (loop, e->dest))
2106 if (dump_file && (dump_flags & TDF_DETAILS))
2107 fprintf (dump_file,
2108 "Predicting exit %i->%i with prob %i.\n",
2109 e->src->index, e->dest->index, probability);
2110 predict_edge (e,
2111 recursion ? PRED_LOOP_EXIT_WITH_RECURSION
2112 : PRED_LOOP_EXIT, probability);
2115 if (loop_bound_var)
2116 predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
2117 loop_bound_code,
2118 tree_to_shwi (loop_bound_step));
2121 /* In the following code
2122 for (loop1)
2123 if (cond)
2124 for (loop2)
2125 body;
2126 guess that cond is unlikely. */
2127 if (loop_outer (loop)->num)
2129 basic_block bb = NULL;
2130 edge preheader_edge = loop_preheader_edge (loop);
2132 if (single_pred_p (preheader_edge->src)
2133 && single_succ_p (preheader_edge->src))
2134 preheader_edge = single_pred_edge (preheader_edge->src);
2136 gimple *stmt = last_stmt (preheader_edge->src);
2137 /* Pattern match fortran loop preheader:
2138 _16 = BUILTIN_EXPECT (_15, 1, PRED_FORTRAN_LOOP_PREHEADER);
2139 _17 = (logical(kind=4)) _16;
2140 if (_17 != 0)
2141 goto <bb 11>;
2142 else
2143 goto <bb 13>;
2145 Loop guard branch prediction says nothing about duplicated loop
2146 headers produced by fortran frontend and in this case we want
2147 to predict paths leading to this preheader. */
2149 if (stmt
2150 && gimple_code (stmt) == GIMPLE_COND
2151 && gimple_cond_code (stmt) == NE_EXPR
2152 && TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME
2153 && integer_zerop (gimple_cond_rhs (stmt)))
2155 gimple *call_stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
2156 if (gimple_code (call_stmt) == GIMPLE_ASSIGN
2157 && gimple_expr_code (call_stmt) == NOP_EXPR
2158 && TREE_CODE (gimple_assign_rhs1 (call_stmt)) == SSA_NAME)
2159 call_stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (call_stmt));
2160 if (gimple_call_internal_p (call_stmt, IFN_BUILTIN_EXPECT)
2161 && TREE_CODE (gimple_call_arg (call_stmt, 2)) == INTEGER_CST
2162 && tree_fits_uhwi_p (gimple_call_arg (call_stmt, 2))
2163 && tree_to_uhwi (gimple_call_arg (call_stmt, 2))
2164 == PRED_FORTRAN_LOOP_PREHEADER)
2165 bb = preheader_edge->src;
2167 if (!bb)
2169 if (!dominated_by_p (CDI_DOMINATORS,
2170 loop_outer (loop)->latch, loop->header))
2171 predict_paths_leading_to_edge (loop_preheader_edge (loop),
2172 recursion
2173 ? PRED_LOOP_GUARD_WITH_RECURSION
2174 : PRED_LOOP_GUARD,
2175 NOT_TAKEN,
2176 loop_outer (loop));
2178 else
2180 if (!dominated_by_p (CDI_DOMINATORS,
2181 loop_outer (loop)->latch, bb))
2182 predict_paths_leading_to (bb,
2183 recursion
2184 ? PRED_LOOP_GUARD_WITH_RECURSION
2185 : PRED_LOOP_GUARD,
2186 NOT_TAKEN,
2187 loop_outer (loop));
2191 /* Free basic blocks from get_loop_body. */
2192 free (bbs);
2196 /* Attempt to predict probabilities of BB outgoing edges using local
2197 properties. */
2198 static void
2199 bb_estimate_probability_locally (basic_block bb)
2201 rtx_insn *last_insn = BB_END (bb);
2202 rtx cond;
2204 if (! can_predict_insn_p (last_insn))
2205 return;
2206 cond = get_condition (last_insn, NULL, false, false);
2207 if (! cond)
2208 return;
2210 /* Try "pointer heuristic."
2211 A comparison ptr == 0 is predicted as false.
2212 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2213 if (COMPARISON_P (cond)
2214 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
2215 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
2217 if (GET_CODE (cond) == EQ)
2218 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
2219 else if (GET_CODE (cond) == NE)
2220 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
2222 else
2224 /* Try "opcode heuristic."
2225 EQ tests are usually false and NE tests are usually true. Also,
2226 most quantities are positive, so we can make the appropriate guesses
2227 about signed comparisons against zero. */
2228 switch (GET_CODE (cond))
2230 case CONST_INT:
2231 /* Unconditional branch. */
2232 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
2233 cond == const0_rtx ? NOT_TAKEN : TAKEN);
2234 break;
2236 case EQ:
2237 case UNEQ:
2238 /* Floating point comparisons appears to behave in a very
2239 unpredictable way because of special role of = tests in
2240 FP code. */
2241 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
2243 /* Comparisons with 0 are often used for booleans and there is
2244 nothing useful to predict about them. */
2245 else if (XEXP (cond, 1) == const0_rtx
2246 || XEXP (cond, 0) == const0_rtx)
2248 else
2249 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
2250 break;
2252 case NE:
2253 case LTGT:
2254 /* Floating point comparisons appears to behave in a very
2255 unpredictable way because of special role of = tests in
2256 FP code. */
2257 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
2259 /* Comparisons with 0 are often used for booleans and there is
2260 nothing useful to predict about them. */
2261 else if (XEXP (cond, 1) == const0_rtx
2262 || XEXP (cond, 0) == const0_rtx)
2264 else
2265 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
2266 break;
2268 case ORDERED:
2269 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
2270 break;
2272 case UNORDERED:
2273 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
2274 break;
2276 case LE:
2277 case LT:
2278 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
2279 || XEXP (cond, 1) == constm1_rtx)
2280 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
2281 break;
2283 case GE:
2284 case GT:
2285 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
2286 || XEXP (cond, 1) == constm1_rtx)
2287 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
2288 break;
2290 default:
2291 break;
2295 /* Set edge->probability for each successor edge of BB. */
2296 void
2297 guess_outgoing_edge_probabilities (basic_block bb)
2299 bb_estimate_probability_locally (bb);
2300 combine_predictions_for_insn (BB_END (bb), bb);
2303 static tree expr_expected_value (tree, bitmap, enum br_predictor *predictor,
2304 HOST_WIDE_INT *probability);
2306 /* Helper function for expr_expected_value. */
2308 static tree
2309 expr_expected_value_1 (tree type, tree op0, enum tree_code code,
2310 tree op1, bitmap visited, enum br_predictor *predictor,
2311 HOST_WIDE_INT *probability)
2313 gimple *def;
2315 /* Reset returned probability value. */
2316 *probability = -1;
2317 *predictor = PRED_UNCONDITIONAL;
2319 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
2321 if (TREE_CONSTANT (op0))
2322 return op0;
2324 if (code == IMAGPART_EXPR)
2326 if (TREE_CODE (TREE_OPERAND (op0, 0)) == SSA_NAME)
2328 def = SSA_NAME_DEF_STMT (TREE_OPERAND (op0, 0));
2329 if (is_gimple_call (def)
2330 && gimple_call_internal_p (def)
2331 && (gimple_call_internal_fn (def)
2332 == IFN_ATOMIC_COMPARE_EXCHANGE))
2334 /* Assume that any given atomic operation has low contention,
2335 and thus the compare-and-swap operation succeeds. */
2336 *predictor = PRED_COMPARE_AND_SWAP;
2337 return build_one_cst (TREE_TYPE (op0));
2342 if (code != SSA_NAME)
2343 return NULL_TREE;
2345 def = SSA_NAME_DEF_STMT (op0);
2347 /* If we were already here, break the infinite cycle. */
2348 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
2349 return NULL;
2351 if (gimple_code (def) == GIMPLE_PHI)
2353 /* All the arguments of the PHI node must have the same constant
2354 length. */
2355 int i, n = gimple_phi_num_args (def);
2356 tree val = NULL, new_val;
2358 for (i = 0; i < n; i++)
2360 tree arg = PHI_ARG_DEF (def, i);
2361 enum br_predictor predictor2;
2363 /* If this PHI has itself as an argument, we cannot
2364 determine the string length of this argument. However,
2365 if we can find an expected constant value for the other
2366 PHI args then we can still be sure that this is
2367 likely a constant. So be optimistic and just
2368 continue with the next argument. */
2369 if (arg == PHI_RESULT (def))
2370 continue;
2372 HOST_WIDE_INT probability2;
2373 new_val = expr_expected_value (arg, visited, &predictor2,
2374 &probability2);
2376 /* It is difficult to combine value predictors. Simply assume
2377 that later predictor is weaker and take its prediction. */
2378 if (*predictor < predictor2)
2380 *predictor = predictor2;
2381 *probability = probability2;
2383 if (!new_val)
2384 return NULL;
2385 if (!val)
2386 val = new_val;
2387 else if (!operand_equal_p (val, new_val, false))
2388 return NULL;
2390 return val;
2392 if (is_gimple_assign (def))
2394 if (gimple_assign_lhs (def) != op0)
2395 return NULL;
2397 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
2398 gimple_assign_rhs1 (def),
2399 gimple_assign_rhs_code (def),
2400 gimple_assign_rhs2 (def),
2401 visited, predictor, probability);
2404 if (is_gimple_call (def))
2406 tree decl = gimple_call_fndecl (def);
2407 if (!decl)
2409 if (gimple_call_internal_p (def)
2410 && gimple_call_internal_fn (def) == IFN_BUILTIN_EXPECT)
2412 gcc_assert (gimple_call_num_args (def) == 3);
2413 tree val = gimple_call_arg (def, 0);
2414 if (TREE_CONSTANT (val))
2415 return val;
2416 tree val2 = gimple_call_arg (def, 2);
2417 gcc_assert (TREE_CODE (val2) == INTEGER_CST
2418 && tree_fits_uhwi_p (val2)
2419 && tree_to_uhwi (val2) < END_PREDICTORS);
2420 *predictor = (enum br_predictor) tree_to_uhwi (val2);
2421 if (*predictor == PRED_BUILTIN_EXPECT)
2422 *probability
2423 = HITRATE (PARAM_VALUE (BUILTIN_EXPECT_PROBABILITY));
2424 return gimple_call_arg (def, 1);
2426 return NULL;
2429 if (DECL_IS_MALLOC (decl) || DECL_IS_OPERATOR_NEW (decl))
2431 if (predictor)
2432 *predictor = PRED_MALLOC_NONNULL;
2433 return boolean_true_node;
2436 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
2437 switch (DECL_FUNCTION_CODE (decl))
2439 case BUILT_IN_EXPECT:
2441 tree val;
2442 if (gimple_call_num_args (def) != 2)
2443 return NULL;
2444 val = gimple_call_arg (def, 0);
2445 if (TREE_CONSTANT (val))
2446 return val;
2447 *predictor = PRED_BUILTIN_EXPECT;
2448 *probability
2449 = HITRATE (PARAM_VALUE (BUILTIN_EXPECT_PROBABILITY));
2450 return gimple_call_arg (def, 1);
2452 case BUILT_IN_EXPECT_WITH_PROBABILITY:
2454 tree val;
2455 if (gimple_call_num_args (def) != 3)
2456 return NULL;
2457 val = gimple_call_arg (def, 0);
2458 if (TREE_CONSTANT (val))
2459 return val;
2460 /* Compute final probability as:
2461 probability * REG_BR_PROB_BASE. */
2462 tree prob = gimple_call_arg (def, 2);
2463 tree t = TREE_TYPE (prob);
2464 tree base = build_int_cst (integer_type_node,
2465 REG_BR_PROB_BASE);
2466 base = build_real_from_int_cst (t, base);
2467 tree r = fold_build2_initializer_loc (UNKNOWN_LOCATION,
2468 MULT_EXPR, t, prob, base);
2469 HOST_WIDE_INT probi
2470 = real_to_integer (TREE_REAL_CST_PTR (r));
2471 if (probi >= 0 && probi <= REG_BR_PROB_BASE)
2473 *predictor = PRED_BUILTIN_EXPECT_WITH_PROBABILITY;
2474 *probability = probi;
2476 return gimple_call_arg (def, 1);
2479 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
2480 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
2481 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
2482 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
2483 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
2484 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
2485 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
2486 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
2487 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
2488 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
2489 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
2490 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
2491 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
2492 /* Assume that any given atomic operation has low contention,
2493 and thus the compare-and-swap operation succeeds. */
2494 *predictor = PRED_COMPARE_AND_SWAP;
2495 return boolean_true_node;
2496 case BUILT_IN_REALLOC:
2497 if (predictor)
2498 *predictor = PRED_MALLOC_NONNULL;
2499 return boolean_true_node;
2500 default:
2501 break;
2505 return NULL;
2508 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
2510 tree res;
2511 enum br_predictor predictor2;
2512 HOST_WIDE_INT probability2;
2513 op0 = expr_expected_value (op0, visited, predictor, probability);
2514 if (!op0)
2515 return NULL;
2516 op1 = expr_expected_value (op1, visited, &predictor2, &probability2);
2517 if (!op1)
2518 return NULL;
2519 res = fold_build2 (code, type, op0, op1);
2520 if (TREE_CODE (res) == INTEGER_CST
2521 && TREE_CODE (op0) == INTEGER_CST
2522 && TREE_CODE (op1) == INTEGER_CST)
2524 /* Combine binary predictions. */
2525 if (*probability != -1 || probability2 != -1)
2527 HOST_WIDE_INT p1 = get_predictor_value (*predictor, *probability);
2528 HOST_WIDE_INT p2 = get_predictor_value (predictor2, probability2);
2529 *probability = RDIV (p1 * p2, REG_BR_PROB_BASE);
2532 if (*predictor < predictor2)
2533 *predictor = predictor2;
2535 return res;
2537 return NULL;
2539 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
2541 tree res;
2542 op0 = expr_expected_value (op0, visited, predictor, probability);
2543 if (!op0)
2544 return NULL;
2545 res = fold_build1 (code, type, op0);
2546 if (TREE_CONSTANT (res))
2547 return res;
2548 return NULL;
2550 return NULL;
2553 /* Return constant EXPR will likely have at execution time, NULL if unknown.
2554 The function is used by builtin_expect branch predictor so the evidence
2555 must come from this construct and additional possible constant folding.
2557 We may want to implement more involved value guess (such as value range
2558 propagation based prediction), but such tricks shall go to new
2559 implementation. */
2561 static tree
2562 expr_expected_value (tree expr, bitmap visited,
2563 enum br_predictor *predictor,
2564 HOST_WIDE_INT *probability)
2566 enum tree_code code;
2567 tree op0, op1;
2569 if (TREE_CONSTANT (expr))
2571 *predictor = PRED_UNCONDITIONAL;
2572 *probability = -1;
2573 return expr;
2576 extract_ops_from_tree (expr, &code, &op0, &op1);
2577 return expr_expected_value_1 (TREE_TYPE (expr),
2578 op0, code, op1, visited, predictor,
2579 probability);
2583 /* Return probability of a PREDICTOR. If the predictor has variable
2584 probability return passed PROBABILITY. */
2586 static HOST_WIDE_INT
2587 get_predictor_value (br_predictor predictor, HOST_WIDE_INT probability)
2589 switch (predictor)
2591 case PRED_BUILTIN_EXPECT:
2592 case PRED_BUILTIN_EXPECT_WITH_PROBABILITY:
2593 gcc_assert (probability != -1);
2594 return probability;
2595 default:
2596 gcc_assert (probability == -1);
2597 return predictor_info[(int) predictor].hitrate;
2601 /* Predict using opcode of the last statement in basic block. */
2602 static void
2603 tree_predict_by_opcode (basic_block bb)
2605 gimple *stmt = last_stmt (bb);
2606 edge then_edge;
2607 tree op0, op1;
2608 tree type;
2609 tree val;
2610 enum tree_code cmp;
2611 edge_iterator ei;
2612 enum br_predictor predictor;
2613 HOST_WIDE_INT probability;
2615 if (!stmt)
2616 return;
2618 if (gswitch *sw = dyn_cast <gswitch *> (stmt))
2620 tree index = gimple_switch_index (sw);
2621 tree val = expr_expected_value (index, auto_bitmap (),
2622 &predictor, &probability);
2623 if (val && TREE_CODE (val) == INTEGER_CST)
2625 edge e = find_taken_edge_switch_expr (sw, val);
2626 if (predictor == PRED_BUILTIN_EXPECT)
2628 int percent = PARAM_VALUE (BUILTIN_EXPECT_PROBABILITY);
2629 gcc_assert (percent >= 0 && percent <= 100);
2630 predict_edge (e, PRED_BUILTIN_EXPECT,
2631 HITRATE (percent));
2633 else
2634 predict_edge_def (e, predictor, TAKEN);
2638 if (gimple_code (stmt) != GIMPLE_COND)
2639 return;
2640 FOR_EACH_EDGE (then_edge, ei, bb->succs)
2641 if (then_edge->flags & EDGE_TRUE_VALUE)
2642 break;
2643 op0 = gimple_cond_lhs (stmt);
2644 op1 = gimple_cond_rhs (stmt);
2645 cmp = gimple_cond_code (stmt);
2646 type = TREE_TYPE (op0);
2647 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, auto_bitmap (),
2648 &predictor, &probability);
2649 if (val && TREE_CODE (val) == INTEGER_CST)
2651 HOST_WIDE_INT prob = get_predictor_value (predictor, probability);
2652 if (integer_zerop (val))
2653 prob = REG_BR_PROB_BASE - prob;
2654 predict_edge (then_edge, predictor, prob);
2656 /* Try "pointer heuristic."
2657 A comparison ptr == 0 is predicted as false.
2658 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2659 if (POINTER_TYPE_P (type))
2661 if (cmp == EQ_EXPR)
2662 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
2663 else if (cmp == NE_EXPR)
2664 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
2666 else
2668 /* Try "opcode heuristic."
2669 EQ tests are usually false and NE tests are usually true. Also,
2670 most quantities are positive, so we can make the appropriate guesses
2671 about signed comparisons against zero. */
2672 switch (cmp)
2674 case EQ_EXPR:
2675 case UNEQ_EXPR:
2676 /* Floating point comparisons appears to behave in a very
2677 unpredictable way because of special role of = tests in
2678 FP code. */
2679 if (FLOAT_TYPE_P (type))
2681 /* Comparisons with 0 are often used for booleans and there is
2682 nothing useful to predict about them. */
2683 else if (integer_zerop (op0) || integer_zerop (op1))
2685 else
2686 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
2687 break;
2689 case NE_EXPR:
2690 case LTGT_EXPR:
2691 /* Floating point comparisons appears to behave in a very
2692 unpredictable way because of special role of = tests in
2693 FP code. */
2694 if (FLOAT_TYPE_P (type))
2696 /* Comparisons with 0 are often used for booleans and there is
2697 nothing useful to predict about them. */
2698 else if (integer_zerop (op0)
2699 || integer_zerop (op1))
2701 else
2702 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
2703 break;
2705 case ORDERED_EXPR:
2706 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
2707 break;
2709 case UNORDERED_EXPR:
2710 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
2711 break;
2713 case LE_EXPR:
2714 case LT_EXPR:
2715 if (integer_zerop (op1)
2716 || integer_onep (op1)
2717 || integer_all_onesp (op1)
2718 || real_zerop (op1)
2719 || real_onep (op1)
2720 || real_minus_onep (op1))
2721 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
2722 break;
2724 case GE_EXPR:
2725 case GT_EXPR:
2726 if (integer_zerop (op1)
2727 || integer_onep (op1)
2728 || integer_all_onesp (op1)
2729 || real_zerop (op1)
2730 || real_onep (op1)
2731 || real_minus_onep (op1))
2732 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
2733 break;
2735 default:
2736 break;
2740 /* Returns TRUE if the STMT is exit(0) like statement. */
2742 static bool
2743 is_exit_with_zero_arg (const gimple *stmt)
2745 /* This is not exit, _exit or _Exit. */
2746 if (!gimple_call_builtin_p (stmt, BUILT_IN_EXIT)
2747 && !gimple_call_builtin_p (stmt, BUILT_IN__EXIT)
2748 && !gimple_call_builtin_p (stmt, BUILT_IN__EXIT2))
2749 return false;
2751 /* Argument is an interger zero. */
2752 return integer_zerop (gimple_call_arg (stmt, 0));
2755 /* Try to guess whether the value of return means error code. */
2757 static enum br_predictor
2758 return_prediction (tree val, enum prediction *prediction)
2760 /* VOID. */
2761 if (!val)
2762 return PRED_NO_PREDICTION;
2763 /* Different heuristics for pointers and scalars. */
2764 if (POINTER_TYPE_P (TREE_TYPE (val)))
2766 /* NULL is usually not returned. */
2767 if (integer_zerop (val))
2769 *prediction = NOT_TAKEN;
2770 return PRED_NULL_RETURN;
2773 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
2775 /* Negative return values are often used to indicate
2776 errors. */
2777 if (TREE_CODE (val) == INTEGER_CST
2778 && tree_int_cst_sgn (val) < 0)
2780 *prediction = NOT_TAKEN;
2781 return PRED_NEGATIVE_RETURN;
2783 /* Constant return values seems to be commonly taken.
2784 Zero/one often represent booleans so exclude them from the
2785 heuristics. */
2786 if (TREE_CONSTANT (val)
2787 && (!integer_zerop (val) && !integer_onep (val)))
2789 *prediction = NOT_TAKEN;
2790 return PRED_CONST_RETURN;
2793 return PRED_NO_PREDICTION;
2796 /* Return zero if phi result could have values other than -1, 0 or 1,
2797 otherwise return a bitmask, with bits 0, 1 and 2 set if -1, 0 and 1
2798 values are used or likely. */
2800 static int
2801 zero_one_minusone (gphi *phi, int limit)
2803 int phi_num_args = gimple_phi_num_args (phi);
2804 int ret = 0;
2805 for (int i = 0; i < phi_num_args; i++)
2807 tree t = PHI_ARG_DEF (phi, i);
2808 if (TREE_CODE (t) != INTEGER_CST)
2809 continue;
2810 wide_int w = wi::to_wide (t);
2811 if (w == -1)
2812 ret |= 1;
2813 else if (w == 0)
2814 ret |= 2;
2815 else if (w == 1)
2816 ret |= 4;
2817 else
2818 return 0;
2820 for (int i = 0; i < phi_num_args; i++)
2822 tree t = PHI_ARG_DEF (phi, i);
2823 if (TREE_CODE (t) == INTEGER_CST)
2824 continue;
2825 if (TREE_CODE (t) != SSA_NAME)
2826 return 0;
2827 gimple *g = SSA_NAME_DEF_STMT (t);
2828 if (gimple_code (g) == GIMPLE_PHI && limit > 0)
2829 if (int r = zero_one_minusone (as_a <gphi *> (g), limit - 1))
2831 ret |= r;
2832 continue;
2834 if (!is_gimple_assign (g))
2835 return 0;
2836 if (gimple_assign_cast_p (g))
2838 tree rhs1 = gimple_assign_rhs1 (g);
2839 if (TREE_CODE (rhs1) != SSA_NAME
2840 || !INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
2841 || TYPE_PRECISION (TREE_TYPE (rhs1)) != 1
2842 || !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
2843 return 0;
2844 ret |= (2 | 4);
2845 continue;
2847 if (TREE_CODE_CLASS (gimple_assign_rhs_code (g)) != tcc_comparison)
2848 return 0;
2849 ret |= (2 | 4);
2851 return ret;
2854 /* Find the basic block with return expression and look up for possible
2855 return value trying to apply RETURN_PREDICTION heuristics. */
2856 static void
2857 apply_return_prediction (void)
2859 greturn *return_stmt = NULL;
2860 tree return_val;
2861 edge e;
2862 gphi *phi;
2863 int phi_num_args, i;
2864 enum br_predictor pred;
2865 enum prediction direction;
2866 edge_iterator ei;
2868 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2870 gimple *last = last_stmt (e->src);
2871 if (last
2872 && gimple_code (last) == GIMPLE_RETURN)
2874 return_stmt = as_a <greturn *> (last);
2875 break;
2878 if (!e)
2879 return;
2880 return_val = gimple_return_retval (return_stmt);
2881 if (!return_val)
2882 return;
2883 if (TREE_CODE (return_val) != SSA_NAME
2884 || !SSA_NAME_DEF_STMT (return_val)
2885 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
2886 return;
2887 phi = as_a <gphi *> (SSA_NAME_DEF_STMT (return_val));
2888 phi_num_args = gimple_phi_num_args (phi);
2889 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
2891 /* Avoid the case where the function returns -1, 0 and 1 values and
2892 nothing else. Those could be qsort etc. comparison functions
2893 where the negative return isn't less probable than positive.
2894 For this require that the function returns at least -1 or 1
2895 or -1 and a boolean value or comparison result, so that functions
2896 returning just -1 and 0 are treated as if -1 represents error value. */
2897 if (INTEGRAL_TYPE_P (TREE_TYPE (return_val))
2898 && !TYPE_UNSIGNED (TREE_TYPE (return_val))
2899 && TYPE_PRECISION (TREE_TYPE (return_val)) > 1)
2900 if (int r = zero_one_minusone (phi, 3))
2901 if ((r & (1 | 4)) == (1 | 4))
2902 return;
2904 /* Avoid the degenerate case where all return values form the function
2905 belongs to same category (ie they are all positive constants)
2906 so we can hardly say something about them. */
2907 for (i = 1; i < phi_num_args; i++)
2908 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
2909 break;
2910 if (i != phi_num_args)
2911 for (i = 0; i < phi_num_args; i++)
2913 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
2914 if (pred != PRED_NO_PREDICTION)
2915 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
2916 direction);
2920 /* Look for basic block that contains unlikely to happen events
2921 (such as noreturn calls) and mark all paths leading to execution
2922 of this basic blocks as unlikely. */
2924 static void
2925 tree_bb_level_predictions (void)
2927 basic_block bb;
2928 bool has_return_edges = false;
2929 edge e;
2930 edge_iterator ei;
2932 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2933 if (!unlikely_executed_edge_p (e) && !(e->flags & EDGE_ABNORMAL_CALL))
2935 has_return_edges = true;
2936 break;
2939 apply_return_prediction ();
2941 FOR_EACH_BB_FN (bb, cfun)
2943 gimple_stmt_iterator gsi;
2945 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2947 gimple *stmt = gsi_stmt (gsi);
2948 tree decl;
2950 if (is_gimple_call (stmt))
2952 if (gimple_call_noreturn_p (stmt)
2953 && has_return_edges
2954 && !is_exit_with_zero_arg (stmt))
2955 predict_paths_leading_to (bb, PRED_NORETURN,
2956 NOT_TAKEN);
2957 decl = gimple_call_fndecl (stmt);
2958 if (decl
2959 && lookup_attribute ("cold",
2960 DECL_ATTRIBUTES (decl)))
2961 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
2962 NOT_TAKEN);
2963 if (decl && recursive_call_p (current_function_decl, decl))
2964 predict_paths_leading_to (bb, PRED_RECURSIVE_CALL,
2965 NOT_TAKEN);
2967 else if (gimple_code (stmt) == GIMPLE_PREDICT)
2969 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
2970 gimple_predict_outcome (stmt));
2971 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2972 hints to callers. */
2978 /* Callback for hash_map::traverse, asserts that the pointer map is
2979 empty. */
2981 bool
2982 assert_is_empty (const_basic_block const &, edge_prediction *const &value,
2983 void *)
2985 gcc_assert (!value);
2986 return false;
2989 /* Predict branch probabilities and estimate profile for basic block BB.
2990 When LOCAL_ONLY is set do not use any global properties of CFG. */
2992 static void
2993 tree_estimate_probability_bb (basic_block bb, bool local_only)
2995 edge e;
2996 edge_iterator ei;
2998 FOR_EACH_EDGE (e, ei, bb->succs)
3000 /* Look for block we are guarding (ie we dominate it,
3001 but it doesn't postdominate us). */
3002 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun) && e->dest != bb
3003 && !local_only
3004 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
3005 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
3007 gimple_stmt_iterator bi;
3009 /* The call heuristic claims that a guarded function call
3010 is improbable. This is because such calls are often used
3011 to signal exceptional situations such as printing error
3012 messages. */
3013 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
3014 gsi_next (&bi))
3016 gimple *stmt = gsi_stmt (bi);
3017 if (is_gimple_call (stmt)
3018 && !gimple_inexpensive_call_p (as_a <gcall *> (stmt))
3019 /* Constant and pure calls are hardly used to signalize
3020 something exceptional. */
3021 && gimple_has_side_effects (stmt))
3023 if (gimple_call_fndecl (stmt))
3024 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
3025 else if (virtual_method_call_p (gimple_call_fn (stmt)))
3026 predict_edge_def (e, PRED_POLYMORPHIC_CALL, NOT_TAKEN);
3027 else
3028 predict_edge_def (e, PRED_INDIR_CALL, TAKEN);
3029 break;
3034 tree_predict_by_opcode (bb);
3037 /* Predict branch probabilities and estimate profile of the tree CFG.
3038 This function can be called from the loop optimizers to recompute
3039 the profile information.
3040 If DRY_RUN is set, do not modify CFG and only produce dump files. */
3042 void
3043 tree_estimate_probability (bool dry_run)
3045 basic_block bb;
3047 add_noreturn_fake_exit_edges ();
3048 connect_infinite_loops_to_exit ();
3049 /* We use loop_niter_by_eval, which requires that the loops have
3050 preheaders. */
3051 create_preheaders (CP_SIMPLE_PREHEADERS);
3052 calculate_dominance_info (CDI_POST_DOMINATORS);
3054 bb_predictions = new hash_map<const_basic_block, edge_prediction *>;
3055 tree_bb_level_predictions ();
3056 record_loop_exits ();
3058 if (number_of_loops (cfun) > 1)
3059 predict_loops ();
3061 FOR_EACH_BB_FN (bb, cfun)
3062 tree_estimate_probability_bb (bb, false);
3064 FOR_EACH_BB_FN (bb, cfun)
3065 combine_predictions_for_bb (bb, dry_run);
3067 if (flag_checking)
3068 bb_predictions->traverse<void *, assert_is_empty> (NULL);
3070 delete bb_predictions;
3071 bb_predictions = NULL;
3073 if (!dry_run)
3074 estimate_bb_frequencies (false);
3075 free_dominance_info (CDI_POST_DOMINATORS);
3076 remove_fake_exit_edges ();
3079 /* Set edge->probability for each successor edge of BB. */
3080 void
3081 tree_guess_outgoing_edge_probabilities (basic_block bb)
3083 bb_predictions = new hash_map<const_basic_block, edge_prediction *>;
3084 tree_estimate_probability_bb (bb, true);
3085 combine_predictions_for_bb (bb, false);
3086 if (flag_checking)
3087 bb_predictions->traverse<void *, assert_is_empty> (NULL);
3088 delete bb_predictions;
3089 bb_predictions = NULL;
3092 /* Predict edges to successors of CUR whose sources are not postdominated by
3093 BB by PRED and recurse to all postdominators. */
3095 static void
3096 predict_paths_for_bb (basic_block cur, basic_block bb,
3097 enum br_predictor pred,
3098 enum prediction taken,
3099 bitmap visited, struct loop *in_loop = NULL)
3101 edge e;
3102 edge_iterator ei;
3103 basic_block son;
3105 /* If we exited the loop or CUR is unconditional in the loop, there is
3106 nothing to do. */
3107 if (in_loop
3108 && (!flow_bb_inside_loop_p (in_loop, cur)
3109 || dominated_by_p (CDI_DOMINATORS, in_loop->latch, cur)))
3110 return;
3112 /* We are looking for all edges forming edge cut induced by
3113 set of all blocks postdominated by BB. */
3114 FOR_EACH_EDGE (e, ei, cur->preds)
3115 if (e->src->index >= NUM_FIXED_BLOCKS
3116 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
3118 edge e2;
3119 edge_iterator ei2;
3120 bool found = false;
3122 /* Ignore fake edges and eh, we predict them as not taken anyway. */
3123 if (unlikely_executed_edge_p (e))
3124 continue;
3125 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
3127 /* See if there is an edge from e->src that is not abnormal
3128 and does not lead to BB and does not exit the loop. */
3129 FOR_EACH_EDGE (e2, ei2, e->src->succs)
3130 if (e2 != e
3131 && !unlikely_executed_edge_p (e2)
3132 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb)
3133 && (!in_loop || !loop_exit_edge_p (in_loop, e2)))
3135 found = true;
3136 break;
3139 /* If there is non-abnormal path leaving e->src, predict edge
3140 using predictor. Otherwise we need to look for paths
3141 leading to e->src.
3143 The second may lead to infinite loop in the case we are predicitng
3144 regions that are only reachable by abnormal edges. We simply
3145 prevent visiting given BB twice. */
3146 if (found)
3148 if (!edge_predicted_by_p (e, pred, taken))
3149 predict_edge_def (e, pred, taken);
3151 else if (bitmap_set_bit (visited, e->src->index))
3152 predict_paths_for_bb (e->src, e->src, pred, taken, visited, in_loop);
3154 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
3155 son;
3156 son = next_dom_son (CDI_POST_DOMINATORS, son))
3157 predict_paths_for_bb (son, bb, pred, taken, visited, in_loop);
3160 /* Sets branch probabilities according to PREDiction and
3161 FLAGS. */
3163 static void
3164 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
3165 enum prediction taken, struct loop *in_loop)
3167 predict_paths_for_bb (bb, bb, pred, taken, auto_bitmap (), in_loop);
3170 /* Like predict_paths_leading_to but take edge instead of basic block. */
3172 static void
3173 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
3174 enum prediction taken, struct loop *in_loop)
3176 bool has_nonloop_edge = false;
3177 edge_iterator ei;
3178 edge e2;
3180 basic_block bb = e->src;
3181 FOR_EACH_EDGE (e2, ei, bb->succs)
3182 if (e2->dest != e->src && e2->dest != e->dest
3183 && !unlikely_executed_edge_p (e)
3184 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
3186 has_nonloop_edge = true;
3187 break;
3189 if (!has_nonloop_edge)
3191 predict_paths_for_bb (bb, bb, pred, taken, auto_bitmap (), in_loop);
3193 else
3194 predict_edge_def (e, pred, taken);
3197 /* This is used to carry information about basic blocks. It is
3198 attached to the AUX field of the standard CFG block. */
3200 struct block_info
3202 /* Estimated frequency of execution of basic_block. */
3203 sreal frequency;
3205 /* To keep queue of basic blocks to process. */
3206 basic_block next;
3208 /* Number of predecessors we need to visit first. */
3209 int npredecessors;
3212 /* Similar information for edges. */
3213 struct edge_prob_info
3215 /* In case edge is a loopback edge, the probability edge will be reached
3216 in case header is. Estimated number of iterations of the loop can be
3217 then computed as 1 / (1 - back_edge_prob). */
3218 sreal back_edge_prob;
3219 /* True if the edge is a loopback edge in the natural loop. */
3220 unsigned int back_edge:1;
3223 #define BLOCK_INFO(B) ((block_info *) (B)->aux)
3224 #undef EDGE_INFO
3225 #define EDGE_INFO(E) ((edge_prob_info *) (E)->aux)
3227 /* Helper function for estimate_bb_frequencies.
3228 Propagate the frequencies in blocks marked in
3229 TOVISIT, starting in HEAD. */
3231 static void
3232 propagate_freq (basic_block head, bitmap tovisit)
3234 basic_block bb;
3235 basic_block last;
3236 unsigned i;
3237 edge e;
3238 basic_block nextbb;
3239 bitmap_iterator bi;
3241 /* For each basic block we need to visit count number of his predecessors
3242 we need to visit first. */
3243 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
3245 edge_iterator ei;
3246 int count = 0;
3248 bb = BASIC_BLOCK_FOR_FN (cfun, i);
3250 FOR_EACH_EDGE (e, ei, bb->preds)
3252 bool visit = bitmap_bit_p (tovisit, e->src->index);
3254 if (visit && !(e->flags & EDGE_DFS_BACK))
3255 count++;
3256 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
3257 fprintf (dump_file,
3258 "Irreducible region hit, ignoring edge to %i->%i\n",
3259 e->src->index, bb->index);
3261 BLOCK_INFO (bb)->npredecessors = count;
3262 /* When function never returns, we will never process exit block. */
3263 if (!count && bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
3264 bb->count = profile_count::zero ();
3267 BLOCK_INFO (head)->frequency = 1;
3268 last = head;
3269 for (bb = head; bb; bb = nextbb)
3271 edge_iterator ei;
3272 sreal cyclic_probability = 0;
3273 sreal frequency = 0;
3275 nextbb = BLOCK_INFO (bb)->next;
3276 BLOCK_INFO (bb)->next = NULL;
3278 /* Compute frequency of basic block. */
3279 if (bb != head)
3281 if (flag_checking)
3282 FOR_EACH_EDGE (e, ei, bb->preds)
3283 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
3284 || (e->flags & EDGE_DFS_BACK));
3286 FOR_EACH_EDGE (e, ei, bb->preds)
3287 if (EDGE_INFO (e)->back_edge)
3289 cyclic_probability += EDGE_INFO (e)->back_edge_prob;
3291 else if (!(e->flags & EDGE_DFS_BACK))
3293 /* frequency += (e->probability
3294 * BLOCK_INFO (e->src)->frequency /
3295 REG_BR_PROB_BASE); */
3297 /* FIXME: Graphite is producing edges with no profile. Once
3298 this is fixed, drop this. */
3299 sreal tmp = e->probability.initialized_p () ?
3300 e->probability.to_reg_br_prob_base () : 0;
3301 tmp *= BLOCK_INFO (e->src)->frequency;
3302 tmp *= real_inv_br_prob_base;
3303 frequency += tmp;
3306 if (cyclic_probability == 0)
3308 BLOCK_INFO (bb)->frequency = frequency;
3310 else
3312 if (cyclic_probability > real_almost_one)
3313 cyclic_probability = real_almost_one;
3315 /* BLOCK_INFO (bb)->frequency = frequency
3316 / (1 - cyclic_probability) */
3318 cyclic_probability = sreal (1) - cyclic_probability;
3319 BLOCK_INFO (bb)->frequency = frequency / cyclic_probability;
3323 bitmap_clear_bit (tovisit, bb->index);
3325 e = find_edge (bb, head);
3326 if (e)
3328 /* EDGE_INFO (e)->back_edge_prob
3329 = ((e->probability * BLOCK_INFO (bb)->frequency)
3330 / REG_BR_PROB_BASE); */
3332 /* FIXME: Graphite is producing edges with no profile. Once
3333 this is fixed, drop this. */
3334 sreal tmp = e->probability.initialized_p () ?
3335 e->probability.to_reg_br_prob_base () : 0;
3336 tmp *= BLOCK_INFO (bb)->frequency;
3337 EDGE_INFO (e)->back_edge_prob = tmp * real_inv_br_prob_base;
3340 /* Propagate to successor blocks. */
3341 FOR_EACH_EDGE (e, ei, bb->succs)
3342 if (!(e->flags & EDGE_DFS_BACK)
3343 && BLOCK_INFO (e->dest)->npredecessors)
3345 BLOCK_INFO (e->dest)->npredecessors--;
3346 if (!BLOCK_INFO (e->dest)->npredecessors)
3348 if (!nextbb)
3349 nextbb = e->dest;
3350 else
3351 BLOCK_INFO (last)->next = e->dest;
3353 last = e->dest;
3359 /* Estimate frequencies in loops at same nest level. */
3361 static void
3362 estimate_loops_at_level (struct loop *first_loop)
3364 struct loop *loop;
3366 for (loop = first_loop; loop; loop = loop->next)
3368 edge e;
3369 basic_block *bbs;
3370 unsigned i;
3371 auto_bitmap tovisit;
3373 estimate_loops_at_level (loop->inner);
3375 /* Find current loop back edge and mark it. */
3376 e = loop_latch_edge (loop);
3377 EDGE_INFO (e)->back_edge = 1;
3379 bbs = get_loop_body (loop);
3380 for (i = 0; i < loop->num_nodes; i++)
3381 bitmap_set_bit (tovisit, bbs[i]->index);
3382 free (bbs);
3383 propagate_freq (loop->header, tovisit);
3387 /* Propagates frequencies through structure of loops. */
3389 static void
3390 estimate_loops (void)
3392 auto_bitmap tovisit;
3393 basic_block bb;
3395 /* Start by estimating the frequencies in the loops. */
3396 if (number_of_loops (cfun) > 1)
3397 estimate_loops_at_level (current_loops->tree_root->inner);
3399 /* Now propagate the frequencies through all the blocks. */
3400 FOR_ALL_BB_FN (bb, cfun)
3402 bitmap_set_bit (tovisit, bb->index);
3404 propagate_freq (ENTRY_BLOCK_PTR_FOR_FN (cfun), tovisit);
3407 /* Drop the profile for NODE to guessed, and update its frequency based on
3408 whether it is expected to be hot given the CALL_COUNT. */
3410 static void
3411 drop_profile (struct cgraph_node *node, profile_count call_count)
3413 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3414 /* In the case where this was called by another function with a
3415 dropped profile, call_count will be 0. Since there are no
3416 non-zero call counts to this function, we don't know for sure
3417 whether it is hot, and therefore it will be marked normal below. */
3418 bool hot = maybe_hot_count_p (NULL, call_count);
3420 if (dump_file)
3421 fprintf (dump_file,
3422 "Dropping 0 profile for %s. %s based on calls.\n",
3423 node->dump_name (),
3424 hot ? "Function is hot" : "Function is normal");
3425 /* We only expect to miss profiles for functions that are reached
3426 via non-zero call edges in cases where the function may have
3427 been linked from another module or library (COMDATs and extern
3428 templates). See the comments below for handle_missing_profiles.
3429 Also, only warn in cases where the missing counts exceed the
3430 number of training runs. In certain cases with an execv followed
3431 by a no-return call the profile for the no-return call is not
3432 dumped and there can be a mismatch. */
3433 if (!DECL_COMDAT (node->decl) && !DECL_EXTERNAL (node->decl)
3434 && call_count > profile_info->runs)
3436 if (flag_profile_correction)
3438 if (dump_file)
3439 fprintf (dump_file,
3440 "Missing counts for called function %s\n",
3441 node->dump_name ());
3443 else
3444 warning (0, "Missing counts for called function %s",
3445 node->dump_name ());
3448 basic_block bb;
3449 if (opt_for_fn (node->decl, flag_guess_branch_prob))
3451 bool clear_zeros
3452 = !ENTRY_BLOCK_PTR_FOR_FN (fn)->count.nonzero_p ();
3453 FOR_ALL_BB_FN (bb, fn)
3454 if (clear_zeros || !(bb->count == profile_count::zero ()))
3455 bb->count = bb->count.guessed_local ();
3456 fn->cfg->count_max = fn->cfg->count_max.guessed_local ();
3458 else
3460 FOR_ALL_BB_FN (bb, fn)
3461 bb->count = profile_count::uninitialized ();
3462 fn->cfg->count_max = profile_count::uninitialized ();
3465 struct cgraph_edge *e;
3466 for (e = node->callees; e; e = e->next_callee)
3467 e->count = gimple_bb (e->call_stmt)->count;
3468 for (e = node->indirect_calls; e; e = e->next_callee)
3469 e->count = gimple_bb (e->call_stmt)->count;
3470 node->count = ENTRY_BLOCK_PTR_FOR_FN (fn)->count;
3472 profile_status_for_fn (fn)
3473 = (flag_guess_branch_prob ? PROFILE_GUESSED : PROFILE_ABSENT);
3474 node->frequency
3475 = hot ? NODE_FREQUENCY_HOT : NODE_FREQUENCY_NORMAL;
3478 /* In the case of COMDAT routines, multiple object files will contain the same
3479 function and the linker will select one for the binary. In that case
3480 all the other copies from the profile instrument binary will be missing
3481 profile counts. Look for cases where this happened, due to non-zero
3482 call counts going to 0-count functions, and drop the profile to guessed
3483 so that we can use the estimated probabilities and avoid optimizing only
3484 for size.
3486 The other case where the profile may be missing is when the routine
3487 is not going to be emitted to the object file, e.g. for "extern template"
3488 class methods. Those will be marked DECL_EXTERNAL. Emit a warning in
3489 all other cases of non-zero calls to 0-count functions. */
3491 void
3492 handle_missing_profiles (void)
3494 struct cgraph_node *node;
3495 int unlikely_count_fraction = PARAM_VALUE (UNLIKELY_BB_COUNT_FRACTION);
3496 auto_vec<struct cgraph_node *, 64> worklist;
3498 /* See if 0 count function has non-0 count callers. In this case we
3499 lost some profile. Drop its function profile to PROFILE_GUESSED. */
3500 FOR_EACH_DEFINED_FUNCTION (node)
3502 struct cgraph_edge *e;
3503 profile_count call_count = profile_count::zero ();
3504 gcov_type max_tp_first_run = 0;
3505 struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3507 if (node->count.ipa ().nonzero_p ())
3508 continue;
3509 for (e = node->callers; e; e = e->next_caller)
3510 if (e->count.ipa ().initialized_p () && e->count.ipa () > 0)
3512 call_count = call_count + e->count.ipa ();
3514 if (e->caller->tp_first_run > max_tp_first_run)
3515 max_tp_first_run = e->caller->tp_first_run;
3518 /* If time profile is missing, let assign the maximum that comes from
3519 caller functions. */
3520 if (!node->tp_first_run && max_tp_first_run)
3521 node->tp_first_run = max_tp_first_run + 1;
3523 if (call_count > 0
3524 && fn && fn->cfg
3525 && (call_count.apply_scale (unlikely_count_fraction, 1)
3526 >= profile_info->runs))
3528 drop_profile (node, call_count);
3529 worklist.safe_push (node);
3533 /* Propagate the profile dropping to other 0-count COMDATs that are
3534 potentially called by COMDATs we already dropped the profile on. */
3535 while (worklist.length () > 0)
3537 struct cgraph_edge *e;
3539 node = worklist.pop ();
3540 for (e = node->callees; e; e = e->next_caller)
3542 struct cgraph_node *callee = e->callee;
3543 struct function *fn = DECL_STRUCT_FUNCTION (callee->decl);
3545 if (!(e->count.ipa () == profile_count::zero ())
3546 && callee->count.ipa ().nonzero_p ())
3547 continue;
3548 if ((DECL_COMDAT (callee->decl) || DECL_EXTERNAL (callee->decl))
3549 && fn && fn->cfg
3550 && profile_status_for_fn (fn) == PROFILE_READ)
3552 drop_profile (node, profile_count::zero ());
3553 worklist.safe_push (callee);
3559 /* Convert counts measured by profile driven feedback to frequencies.
3560 Return nonzero iff there was any nonzero execution count. */
3562 bool
3563 update_max_bb_count (void)
3565 profile_count true_count_max = profile_count::uninitialized ();
3566 basic_block bb;
3568 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3569 true_count_max = true_count_max.max (bb->count);
3571 cfun->cfg->count_max = true_count_max;
3573 return true_count_max.ipa ().nonzero_p ();
3576 /* Return true if function is likely to be expensive, so there is no point to
3577 optimize performance of prologue, epilogue or do inlining at the expense
3578 of code size growth. THRESHOLD is the limit of number of instructions
3579 function can execute at average to be still considered not expensive. */
3581 bool
3582 expensive_function_p (int threshold)
3584 basic_block bb;
3586 /* If profile was scaled in a way entry block has count 0, then the function
3587 is deifnitly taking a lot of time. */
3588 if (!ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.nonzero_p ())
3589 return true;
3591 profile_count limit = ENTRY_BLOCK_PTR_FOR_FN
3592 (cfun)->count.apply_scale (threshold, 1);
3593 profile_count sum = profile_count::zero ();
3594 FOR_EACH_BB_FN (bb, cfun)
3596 rtx_insn *insn;
3598 if (!bb->count.initialized_p ())
3600 if (dump_file)
3601 fprintf (dump_file, "Function is considered expensive because"
3602 " count of bb %i is not initialized\n", bb->index);
3603 return true;
3606 FOR_BB_INSNS (bb, insn)
3607 if (active_insn_p (insn))
3609 sum += bb->count;
3610 if (sum > limit)
3611 return true;
3615 return false;
3618 /* All basic blocks that are reachable only from unlikely basic blocks are
3619 unlikely. */
3621 void
3622 propagate_unlikely_bbs_forward (void)
3624 auto_vec<basic_block, 64> worklist;
3625 basic_block bb;
3626 edge_iterator ei;
3627 edge e;
3629 if (!(ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ()))
3631 ENTRY_BLOCK_PTR_FOR_FN (cfun)->aux = (void *)(size_t) 1;
3632 worklist.safe_push (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3634 while (worklist.length () > 0)
3636 bb = worklist.pop ();
3637 FOR_EACH_EDGE (e, ei, bb->succs)
3638 if (!(e->count () == profile_count::zero ())
3639 && !(e->dest->count == profile_count::zero ())
3640 && !e->dest->aux)
3642 e->dest->aux = (void *)(size_t) 1;
3643 worklist.safe_push (e->dest);
3648 FOR_ALL_BB_FN (bb, cfun)
3650 if (!bb->aux)
3652 if (!(bb->count == profile_count::zero ())
3653 && (dump_file && (dump_flags & TDF_DETAILS)))
3654 fprintf (dump_file,
3655 "Basic block %i is marked unlikely by forward prop\n",
3656 bb->index);
3657 bb->count = profile_count::zero ();
3659 else
3660 bb->aux = NULL;
3664 /* Determine basic blocks/edges that are known to be unlikely executed and set
3665 their counters to zero.
3666 This is done with first identifying obviously unlikely BBs/edges and then
3667 propagating in both directions. */
3669 static void
3670 determine_unlikely_bbs ()
3672 basic_block bb;
3673 auto_vec<basic_block, 64> worklist;
3674 edge_iterator ei;
3675 edge e;
3677 FOR_EACH_BB_FN (bb, cfun)
3679 if (!(bb->count == profile_count::zero ())
3680 && unlikely_executed_bb_p (bb))
3682 if (dump_file && (dump_flags & TDF_DETAILS))
3683 fprintf (dump_file, "Basic block %i is locally unlikely\n",
3684 bb->index);
3685 bb->count = profile_count::zero ();
3688 FOR_EACH_EDGE (e, ei, bb->succs)
3689 if (!(e->probability == profile_probability::never ())
3690 && unlikely_executed_edge_p (e))
3692 if (dump_file && (dump_flags & TDF_DETAILS))
3693 fprintf (dump_file, "Edge %i->%i is locally unlikely\n",
3694 bb->index, e->dest->index);
3695 e->probability = profile_probability::never ();
3698 gcc_checking_assert (!bb->aux);
3700 propagate_unlikely_bbs_forward ();
3702 auto_vec<int, 64> nsuccs;
3703 nsuccs.safe_grow_cleared (last_basic_block_for_fn (cfun));
3704 FOR_ALL_BB_FN (bb, cfun)
3705 if (!(bb->count == profile_count::zero ())
3706 && bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
3708 nsuccs[bb->index] = 0;
3709 FOR_EACH_EDGE (e, ei, bb->succs)
3710 if (!(e->probability == profile_probability::never ())
3711 && !(e->dest->count == profile_count::zero ()))
3712 nsuccs[bb->index]++;
3713 if (!nsuccs[bb->index])
3714 worklist.safe_push (bb);
3716 while (worklist.length () > 0)
3718 bb = worklist.pop ();
3719 if (bb->count == profile_count::zero ())
3720 continue;
3721 if (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun))
3723 bool found = false;
3724 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
3725 !gsi_end_p (gsi); gsi_next (&gsi))
3726 if (stmt_can_terminate_bb_p (gsi_stmt (gsi))
3727 /* stmt_can_terminate_bb_p special cases noreturns because it
3728 assumes that fake edges are created. We want to know that
3729 noreturn alone does not imply BB to be unlikely. */
3730 || (is_gimple_call (gsi_stmt (gsi))
3731 && (gimple_call_flags (gsi_stmt (gsi)) & ECF_NORETURN)))
3733 found = true;
3734 break;
3736 if (found)
3737 continue;
3739 if (dump_file && (dump_flags & TDF_DETAILS))
3740 fprintf (dump_file,
3741 "Basic block %i is marked unlikely by backward prop\n",
3742 bb->index);
3743 bb->count = profile_count::zero ();
3744 FOR_EACH_EDGE (e, ei, bb->preds)
3745 if (!(e->probability == profile_probability::never ()))
3747 if (!(e->src->count == profile_count::zero ()))
3749 gcc_checking_assert (nsuccs[e->src->index] > 0);
3750 nsuccs[e->src->index]--;
3751 if (!nsuccs[e->src->index])
3752 worklist.safe_push (e->src);
3756 /* Finally all edges from non-0 regions to 0 are unlikely. */
3757 FOR_ALL_BB_FN (bb, cfun)
3758 if (!(bb->count == profile_count::zero ()))
3759 FOR_EACH_EDGE (e, ei, bb->succs)
3760 if (!(e->probability == profile_probability::never ())
3761 && e->dest->count == profile_count::zero ())
3763 if (dump_file && (dump_flags & TDF_DETAILS))
3764 fprintf (dump_file, "Edge %i->%i is unlikely because "
3765 "it enters unlikely block\n",
3766 bb->index, e->dest->index);
3767 e->probability = profile_probability::never ();
3769 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ())
3770 cgraph_node::get (current_function_decl)->count = profile_count::zero ();
3773 /* Estimate and propagate basic block frequencies using the given branch
3774 probabilities. If FORCE is true, the frequencies are used to estimate
3775 the counts even when there are already non-zero profile counts. */
3777 void
3778 estimate_bb_frequencies (bool force)
3780 basic_block bb;
3781 sreal freq_max;
3783 determine_unlikely_bbs ();
3785 if (force || profile_status_for_fn (cfun) != PROFILE_READ
3786 || !update_max_bb_count ())
3788 static int real_values_initialized = 0;
3790 if (!real_values_initialized)
3792 real_values_initialized = 1;
3793 real_br_prob_base = REG_BR_PROB_BASE;
3794 /* Scaling frequencies up to maximal profile count may result in
3795 frequent overflows especially when inlining loops.
3796 Small scalling results in unnecesary precision loss. Stay in
3797 the half of the (exponential) range. */
3798 real_bb_freq_max = (uint64_t)1 << (profile_count::n_bits / 2);
3799 real_one_half = sreal (1, -1);
3800 real_inv_br_prob_base = sreal (1) / real_br_prob_base;
3801 real_almost_one = sreal (1) - real_inv_br_prob_base;
3804 mark_dfs_back_edges ();
3806 single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->probability =
3807 profile_probability::always ();
3809 /* Set up block info for each basic block. */
3810 alloc_aux_for_blocks (sizeof (block_info));
3811 alloc_aux_for_edges (sizeof (edge_prob_info));
3812 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3814 edge e;
3815 edge_iterator ei;
3817 FOR_EACH_EDGE (e, ei, bb->succs)
3819 /* FIXME: Graphite is producing edges with no profile. Once
3820 this is fixed, drop this. */
3821 if (e->probability.initialized_p ())
3822 EDGE_INFO (e)->back_edge_prob
3823 = e->probability.to_reg_br_prob_base ();
3824 else
3825 EDGE_INFO (e)->back_edge_prob = REG_BR_PROB_BASE / 2;
3826 EDGE_INFO (e)->back_edge_prob *= real_inv_br_prob_base;
3830 /* First compute frequencies locally for each loop from innermost
3831 to outermost to examine frequencies for back edges. */
3832 estimate_loops ();
3834 freq_max = 0;
3835 FOR_EACH_BB_FN (bb, cfun)
3836 if (freq_max < BLOCK_INFO (bb)->frequency)
3837 freq_max = BLOCK_INFO (bb)->frequency;
3839 freq_max = real_bb_freq_max / freq_max;
3840 if (freq_max < 16)
3841 freq_max = 16;
3842 profile_count ipa_count = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa ();
3843 cfun->cfg->count_max = profile_count::uninitialized ();
3844 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3846 sreal tmp = BLOCK_INFO (bb)->frequency * freq_max + real_one_half;
3847 profile_count count = profile_count::from_gcov_type (tmp.to_int ());
3849 /* If we have profile feedback in which this function was never
3850 executed, then preserve this info. */
3851 if (!(bb->count == profile_count::zero ()))
3852 bb->count = count.guessed_local ().combine_with_ipa_count (ipa_count);
3853 cfun->cfg->count_max = cfun->cfg->count_max.max (bb->count);
3856 free_aux_for_blocks ();
3857 free_aux_for_edges ();
3859 compute_function_frequency ();
3862 /* Decide whether function is hot, cold or unlikely executed. */
3863 void
3864 compute_function_frequency (void)
3866 basic_block bb;
3867 struct cgraph_node *node = cgraph_node::get (current_function_decl);
3869 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
3870 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
3871 node->only_called_at_startup = true;
3872 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
3873 node->only_called_at_exit = true;
3875 if (profile_status_for_fn (cfun) != PROFILE_READ)
3877 int flags = flags_from_decl_or_type (current_function_decl);
3878 if ((ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa_p ()
3879 && ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa() == profile_count::zero ())
3880 || lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
3881 != NULL)
3883 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
3884 warn_function_cold (current_function_decl);
3886 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
3887 != NULL)
3888 node->frequency = NODE_FREQUENCY_HOT;
3889 else if (flags & ECF_NORETURN)
3890 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
3891 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
3892 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
3893 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
3894 || DECL_STATIC_DESTRUCTOR (current_function_decl))
3895 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
3896 return;
3899 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
3900 warn_function_cold (current_function_decl);
3901 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa() == profile_count::zero ())
3902 return;
3903 FOR_EACH_BB_FN (bb, cfun)
3905 if (maybe_hot_bb_p (cfun, bb))
3907 node->frequency = NODE_FREQUENCY_HOT;
3908 return;
3910 if (!probably_never_executed_bb_p (cfun, bb))
3911 node->frequency = NODE_FREQUENCY_NORMAL;
3915 /* Build PREDICT_EXPR. */
3916 tree
3917 build_predict_expr (enum br_predictor predictor, enum prediction taken)
3919 tree t = build1 (PREDICT_EXPR, void_type_node,
3920 build_int_cst (integer_type_node, predictor));
3921 SET_PREDICT_EXPR_OUTCOME (t, taken);
3922 return t;
3925 const char *
3926 predictor_name (enum br_predictor predictor)
3928 return predictor_info[predictor].name;
3931 /* Predict branch probabilities and estimate profile of the tree CFG. */
3933 namespace {
3935 const pass_data pass_data_profile =
3937 GIMPLE_PASS, /* type */
3938 "profile_estimate", /* name */
3939 OPTGROUP_NONE, /* optinfo_flags */
3940 TV_BRANCH_PROB, /* tv_id */
3941 PROP_cfg, /* properties_required */
3942 0, /* properties_provided */
3943 0, /* properties_destroyed */
3944 0, /* todo_flags_start */
3945 0, /* todo_flags_finish */
3948 class pass_profile : public gimple_opt_pass
3950 public:
3951 pass_profile (gcc::context *ctxt)
3952 : gimple_opt_pass (pass_data_profile, ctxt)
3955 /* opt_pass methods: */
3956 virtual bool gate (function *) { return flag_guess_branch_prob; }
3957 virtual unsigned int execute (function *);
3959 }; // class pass_profile
3961 unsigned int
3962 pass_profile::execute (function *fun)
3964 unsigned nb_loops;
3966 if (profile_status_for_fn (cfun) == PROFILE_GUESSED)
3967 return 0;
3969 loop_optimizer_init (LOOPS_NORMAL);
3970 if (dump_file && (dump_flags & TDF_DETAILS))
3971 flow_loops_dump (dump_file, NULL, 0);
3973 mark_irreducible_loops ();
3975 nb_loops = number_of_loops (fun);
3976 if (nb_loops > 1)
3977 scev_initialize ();
3979 tree_estimate_probability (false);
3981 if (nb_loops > 1)
3982 scev_finalize ();
3984 loop_optimizer_finalize ();
3985 if (dump_file && (dump_flags & TDF_DETAILS))
3986 gimple_dump_cfg (dump_file, dump_flags);
3987 if (profile_status_for_fn (fun) == PROFILE_ABSENT)
3988 profile_status_for_fn (fun) = PROFILE_GUESSED;
3989 if (dump_file && (dump_flags & TDF_DETAILS))
3991 struct loop *loop;
3992 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
3993 if (loop->header->count.initialized_p ())
3994 fprintf (dump_file, "Loop got predicted %d to iterate %i times.\n",
3995 loop->num,
3996 (int)expected_loop_iterations_unbounded (loop));
3998 return 0;
4001 } // anon namespace
4003 gimple_opt_pass *
4004 make_pass_profile (gcc::context *ctxt)
4006 return new pass_profile (ctxt);
4009 /* Return true when PRED predictor should be removed after early
4010 tree passes. Most of the predictors are beneficial to survive
4011 as early inlining can also distribute then into caller's bodies. */
4013 static bool
4014 strip_predictor_early (enum br_predictor pred)
4016 switch (pred)
4018 case PRED_TREE_EARLY_RETURN:
4019 return true;
4020 default:
4021 return false;
4025 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
4026 we no longer need. EARLY is set to true when called from early
4027 optimizations. */
4029 unsigned int
4030 strip_predict_hints (function *fun, bool early)
4032 basic_block bb;
4033 gimple *ass_stmt;
4034 tree var;
4035 bool changed = false;
4037 FOR_EACH_BB_FN (bb, fun)
4039 gimple_stmt_iterator bi;
4040 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
4042 gimple *stmt = gsi_stmt (bi);
4044 if (gimple_code (stmt) == GIMPLE_PREDICT)
4046 if (!early
4047 || strip_predictor_early (gimple_predict_predictor (stmt)))
4049 gsi_remove (&bi, true);
4050 changed = true;
4051 continue;
4054 else if (is_gimple_call (stmt))
4056 tree fndecl = gimple_call_fndecl (stmt);
4058 if (!early
4059 && ((fndecl != NULL_TREE
4060 && fndecl_built_in_p (fndecl, BUILT_IN_EXPECT)
4061 && gimple_call_num_args (stmt) == 2)
4062 || (fndecl != NULL_TREE
4063 && fndecl_built_in_p (fndecl,
4064 BUILT_IN_EXPECT_WITH_PROBABILITY)
4065 && gimple_call_num_args (stmt) == 3)
4066 || (gimple_call_internal_p (stmt)
4067 && gimple_call_internal_fn (stmt) == IFN_BUILTIN_EXPECT)))
4069 var = gimple_call_lhs (stmt);
4070 changed = true;
4071 if (var)
4073 ass_stmt
4074 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
4075 gsi_replace (&bi, ass_stmt, true);
4077 else
4079 gsi_remove (&bi, true);
4080 continue;
4084 gsi_next (&bi);
4087 return changed ? TODO_cleanup_cfg : 0;
4090 namespace {
4092 const pass_data pass_data_strip_predict_hints =
4094 GIMPLE_PASS, /* type */
4095 "*strip_predict_hints", /* name */
4096 OPTGROUP_NONE, /* optinfo_flags */
4097 TV_BRANCH_PROB, /* tv_id */
4098 PROP_cfg, /* properties_required */
4099 0, /* properties_provided */
4100 0, /* properties_destroyed */
4101 0, /* todo_flags_start */
4102 0, /* todo_flags_finish */
4105 class pass_strip_predict_hints : public gimple_opt_pass
4107 public:
4108 pass_strip_predict_hints (gcc::context *ctxt)
4109 : gimple_opt_pass (pass_data_strip_predict_hints, ctxt)
4112 /* opt_pass methods: */
4113 opt_pass * clone () { return new pass_strip_predict_hints (m_ctxt); }
4114 void set_pass_param (unsigned int n, bool param)
4116 gcc_assert (n == 0);
4117 early_p = param;
4120 virtual unsigned int execute (function *);
4122 private:
4123 bool early_p;
4125 }; // class pass_strip_predict_hints
4127 unsigned int
4128 pass_strip_predict_hints::execute (function *fun)
4130 return strip_predict_hints (fun, early_p);
4133 } // anon namespace
4135 gimple_opt_pass *
4136 make_pass_strip_predict_hints (gcc::context *ctxt)
4138 return new pass_strip_predict_hints (ctxt);
4141 /* Rebuild function frequencies. Passes are in general expected to
4142 maintain profile by hand, however in some cases this is not possible:
4143 for example when inlining several functions with loops freuqencies might run
4144 out of scale and thus needs to be recomputed. */
4146 void
4147 rebuild_frequencies (void)
4149 timevar_push (TV_REBUILD_FREQUENCIES);
4151 /* When the max bb count in the function is small, there is a higher
4152 chance that there were truncation errors in the integer scaling
4153 of counts by inlining and other optimizations. This could lead
4154 to incorrect classification of code as being cold when it isn't.
4155 In that case, force the estimation of bb counts/frequencies from the
4156 branch probabilities, rather than computing frequencies from counts,
4157 which may also lead to frequencies incorrectly reduced to 0. There
4158 is less precision in the probabilities, so we only do this for small
4159 max counts. */
4160 cfun->cfg->count_max = profile_count::uninitialized ();
4161 basic_block bb;
4162 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
4163 cfun->cfg->count_max = cfun->cfg->count_max.max (bb->count);
4165 if (profile_status_for_fn (cfun) == PROFILE_GUESSED)
4167 loop_optimizer_init (0);
4168 add_noreturn_fake_exit_edges ();
4169 mark_irreducible_loops ();
4170 connect_infinite_loops_to_exit ();
4171 estimate_bb_frequencies (true);
4172 remove_fake_exit_edges ();
4173 loop_optimizer_finalize ();
4175 else if (profile_status_for_fn (cfun) == PROFILE_READ)
4176 update_max_bb_count ();
4177 else if (profile_status_for_fn (cfun) == PROFILE_ABSENT
4178 && !flag_guess_branch_prob)
4180 else
4181 gcc_unreachable ();
4182 timevar_pop (TV_REBUILD_FREQUENCIES);
4185 /* Perform a dry run of the branch prediction pass and report comparsion of
4186 the predicted and real profile into the dump file. */
4188 void
4189 report_predictor_hitrates (void)
4191 unsigned nb_loops;
4193 loop_optimizer_init (LOOPS_NORMAL);
4194 if (dump_file && (dump_flags & TDF_DETAILS))
4195 flow_loops_dump (dump_file, NULL, 0);
4197 mark_irreducible_loops ();
4199 nb_loops = number_of_loops (cfun);
4200 if (nb_loops > 1)
4201 scev_initialize ();
4203 tree_estimate_probability (true);
4205 if (nb_loops > 1)
4206 scev_finalize ();
4208 loop_optimizer_finalize ();
4211 /* Force edge E to be cold.
4212 If IMPOSSIBLE is true, for edge to have count and probability 0 otherwise
4213 keep low probability to represent possible error in a guess. This is used
4214 i.e. in case we predict loop to likely iterate given number of times but
4215 we are not 100% sure.
4217 This function locally updates profile without attempt to keep global
4218 consistency which can not be reached in full generality without full profile
4219 rebuild from probabilities alone. Doing so is not necessarily a good idea
4220 because frequencies and counts may be more realistic then probabilities.
4222 In some cases (such as for elimination of early exits during full loop
4223 unrolling) the caller can ensure that profile will get consistent
4224 afterwards. */
4226 void
4227 force_edge_cold (edge e, bool impossible)
4229 profile_count count_sum = profile_count::zero ();
4230 profile_probability prob_sum = profile_probability::never ();
4231 edge_iterator ei;
4232 edge e2;
4233 bool uninitialized_exit = false;
4235 /* When branch probability guesses are not known, then do nothing. */
4236 if (!impossible && !e->count ().initialized_p ())
4237 return;
4239 profile_probability goal = (impossible ? profile_probability::never ()
4240 : profile_probability::very_unlikely ());
4242 /* If edge is already improbably or cold, just return. */
4243 if (e->probability <= goal
4244 && (!impossible || e->count () == profile_count::zero ()))
4245 return;
4246 FOR_EACH_EDGE (e2, ei, e->src->succs)
4247 if (e2 != e)
4249 if (e->flags & EDGE_FAKE)
4250 continue;
4251 if (e2->count ().initialized_p ())
4252 count_sum += e2->count ();
4253 if (e2->probability.initialized_p ())
4254 prob_sum += e2->probability;
4255 else
4256 uninitialized_exit = true;
4259 /* If we are not guessing profiles but have some other edges out,
4260 just assume the control flow goes elsewhere. */
4261 if (uninitialized_exit)
4262 e->probability = goal;
4263 /* If there are other edges out of e->src, redistribute probabilitity
4264 there. */
4265 else if (prob_sum > profile_probability::never ())
4267 if (!(e->probability < goal))
4268 e->probability = goal;
4270 profile_probability prob_comp = prob_sum / e->probability.invert ();
4272 if (dump_file && (dump_flags & TDF_DETAILS))
4273 fprintf (dump_file, "Making edge %i->%i %s by redistributing "
4274 "probability to other edges.\n",
4275 e->src->index, e->dest->index,
4276 impossible ? "impossible" : "cold");
4277 FOR_EACH_EDGE (e2, ei, e->src->succs)
4278 if (e2 != e)
4280 e2->probability /= prob_comp;
4282 if (current_ir_type () != IR_GIMPLE
4283 && e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
4284 update_br_prob_note (e->src);
4286 /* If all edges out of e->src are unlikely, the basic block itself
4287 is unlikely. */
4288 else
4290 if (prob_sum == profile_probability::never ())
4291 e->probability = profile_probability::always ();
4292 else
4294 if (impossible)
4295 e->probability = profile_probability::never ();
4296 /* If BB has some edges out that are not impossible, we can not
4297 assume that BB itself is. */
4298 impossible = false;
4300 if (current_ir_type () != IR_GIMPLE
4301 && e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
4302 update_br_prob_note (e->src);
4303 if (e->src->count == profile_count::zero ())
4304 return;
4305 if (count_sum == profile_count::zero () && impossible)
4307 bool found = false;
4308 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
4310 else if (current_ir_type () == IR_GIMPLE)
4311 for (gimple_stmt_iterator gsi = gsi_start_bb (e->src);
4312 !gsi_end_p (gsi); gsi_next (&gsi))
4314 if (stmt_can_terminate_bb_p (gsi_stmt (gsi)))
4316 found = true;
4317 break;
4320 /* FIXME: Implement RTL path. */
4321 else
4322 found = true;
4323 if (!found)
4325 if (dump_file && (dump_flags & TDF_DETAILS))
4326 fprintf (dump_file,
4327 "Making bb %i impossible and dropping count to 0.\n",
4328 e->src->index);
4329 e->src->count = profile_count::zero ();
4330 FOR_EACH_EDGE (e2, ei, e->src->preds)
4331 force_edge_cold (e2, impossible);
4332 return;
4336 /* If we did not adjusting, the source basic block has no likely edeges
4337 leaving other direction. In that case force that bb cold, too.
4338 This in general is difficult task to do, but handle special case when
4339 BB has only one predecestor. This is common case when we are updating
4340 after loop transforms. */
4341 if (!(prob_sum > profile_probability::never ())
4342 && count_sum == profile_count::zero ()
4343 && single_pred_p (e->src) && e->src->count.to_frequency (cfun)
4344 > (impossible ? 0 : 1))
4346 int old_frequency = e->src->count.to_frequency (cfun);
4347 if (dump_file && (dump_flags & TDF_DETAILS))
4348 fprintf (dump_file, "Making bb %i %s.\n", e->src->index,
4349 impossible ? "impossible" : "cold");
4350 int new_frequency = MIN (e->src->count.to_frequency (cfun),
4351 impossible ? 0 : 1);
4352 if (impossible)
4353 e->src->count = profile_count::zero ();
4354 else
4355 e->src->count = e->count ().apply_scale (new_frequency,
4356 old_frequency);
4357 force_edge_cold (single_pred_edge (e->src), impossible);
4359 else if (dump_file && (dump_flags & TDF_DETAILS)
4360 && maybe_hot_bb_p (cfun, e->src))
4361 fprintf (dump_file, "Giving up on making bb %i %s.\n", e->src->index,
4362 impossible ? "impossible" : "cold");
4366 #if CHECKING_P
4368 namespace selftest {
4370 /* Test that value range of predictor values defined in predict.def is
4371 within range (50, 100]. */
4373 struct branch_predictor
4375 const char *name;
4376 int probability;
4379 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) { NAME, HITRATE },
4381 static void
4382 test_prediction_value_range ()
4384 branch_predictor predictors[] = {
4385 #include "predict.def"
4386 { NULL, PROB_UNINITIALIZED }
4389 for (unsigned i = 0; predictors[i].name != NULL; i++)
4391 if (predictors[i].probability == PROB_UNINITIALIZED)
4392 continue;
4394 unsigned p = 100 * predictors[i].probability / REG_BR_PROB_BASE;
4395 ASSERT_TRUE (p >= 50 && p <= 100);
4399 #undef DEF_PREDICTOR
4401 /* Run all of the selfests within this file. */
4403 void
4404 predict_c_tests ()
4406 test_prediction_value_range ();
4409 } // namespace selftest
4410 #endif /* CHECKING_P. */