Merge aosp-toolchain/gcc/gcc-4_9 changes.
[official-gcc.git] / gcc-4_6 / gcc / predict.c
blobf7cb7beafaab166479ae0b64d834bda66da76e83
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* References:
23 [1] "Branch Prediction for Free"
24 Ball and Larus; PLDI '93.
25 [2] "Static Branch Frequency and Program Profile Analysis"
26 Wu and Larus; MICRO-27.
27 [3] "Corpus-based Static Branch Prediction"
28 Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
31 #include "config.h"
32 #include "system.h"
33 #include "coretypes.h"
34 #include "tm.h"
35 #include "tree.h"
36 #include "rtl.h"
37 #include "tm_p.h"
38 #include "hard-reg-set.h"
39 #include "basic-block.h"
40 #include "insn-config.h"
41 #include "regs.h"
42 #include "flags.h"
43 #include "output.h"
44 #include "function.h"
45 #include "except.h"
46 #include "diagnostic-core.h"
47 #include "recog.h"
48 #include "expr.h"
49 #include "predict.h"
50 #include "coverage.h"
51 #include "sreal.h"
52 #include "params.h"
53 #include "target.h"
54 #include "cfgloop.h"
55 #include "tree-flow.h"
56 #include "ggc.h"
57 #include "tree-dump.h"
58 #include "tree-pass.h"
59 #include "timevar.h"
60 #include "tree-scalar-evolution.h"
61 #include "cfgloop.h"
62 #include "pointer-set.h"
64 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
65 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
66 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
67 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
69 /* Random guesstimation given names.
70 PROV_VERY_UNLIKELY should be small enough so basic block predicted
71 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
72 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
73 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
74 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
75 #define PROB_ALWAYS (REG_BR_PROB_BASE)
77 static void combine_predictions_for_insn (rtx, basic_block);
78 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
79 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
80 static void predict_paths_leading_to_edge (edge, enum br_predictor, enum prediction);
81 static bool can_predict_insn_p (const_rtx);
83 /* Information we hold about each branch predictor.
84 Filled using information from predict.def. */
86 struct predictor_info
88 const char *const name; /* Name used in the debugging dumps. */
89 const int hitrate; /* Expected hitrate used by
90 predict_insn_def call. */
91 const int flags;
94 /* Use given predictor without Dempster-Shaffer theory if it matches
95 using first_match heuristics. */
96 #define PRED_FLAG_FIRST_MATCH 1
98 /* Recompute hitrate in percent to our representation. */
100 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
102 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
103 static const struct predictor_info predictor_info[]= {
104 #include "predict.def"
106 /* Upper bound on predictors. */
107 {NULL, 0, 0}
109 #undef DEF_PREDICTOR
111 /* Return TRUE if frequency FREQ is considered to be hot. */
113 static inline bool
114 maybe_hot_frequency_p (int freq)
116 struct cgraph_node *node = cgraph_node (current_function_decl);
117 if (!profile_info || !flag_branch_probabilities)
119 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
120 return false;
121 if (node->frequency == NODE_FREQUENCY_HOT)
122 return true;
124 if (profile_status == PROFILE_ABSENT)
125 return true;
126 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
127 && freq <= (ENTRY_BLOCK_PTR->frequency * 2 / 3))
128 return false;
129 if (freq < ENTRY_BLOCK_PTR->frequency / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
130 return false;
131 return true;
134 /* Return TRUE if frequency COUNT is considered to be hot. */
136 bool
137 maybe_hot_count_p (gcov_type count)
139 if (!profile_info)
140 return false;
141 /* Code executed at most once is not hot. */
142 if (profile_info->runs >= count)
143 return false;
144 return (count
145 > profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION));
148 /* Return true in case BB can be CPU intensive and should be optimized
149 for maximal performance. */
151 bool
152 maybe_hot_bb_p (const_basic_block bb)
154 if (profile_status == PROFILE_READ)
155 return maybe_hot_count_p (bb->count);
156 return maybe_hot_frequency_p (bb->frequency);
159 /* Return true if the call can be hot. */
161 bool
162 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
164 if (profile_info && flag_branch_probabilities
165 && (edge->count
166 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
167 return false;
168 if (edge->caller->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED
169 || edge->callee->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
170 return false;
171 if (edge->caller->frequency > NODE_FREQUENCY_UNLIKELY_EXECUTED
172 && edge->callee->frequency <= NODE_FREQUENCY_EXECUTED_ONCE)
173 return false;
174 if (optimize_size)
175 return false;
176 if (edge->caller->frequency == NODE_FREQUENCY_HOT)
177 return true;
178 if (edge->caller->frequency == NODE_FREQUENCY_EXECUTED_ONCE
179 && edge->frequency < CGRAPH_FREQ_BASE * 3 / 2)
180 return false;
181 if (flag_guess_branch_prob
182 && edge->frequency <= (CGRAPH_FREQ_BASE
183 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
184 return false;
185 return true;
188 /* Return true in case BB can be CPU intensive and should be optimized
189 for maximal performance. */
191 bool
192 maybe_hot_edge_p (edge e)
194 if (profile_status == PROFILE_READ)
195 return maybe_hot_count_p (e->count);
196 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
199 /* Return true in case BB is probably never executed. */
200 bool
201 probably_never_executed_bb_p (const_basic_block bb)
203 if (profile_info && flag_branch_probabilities)
204 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
205 if ((!profile_info || !flag_branch_probabilities)
206 && cgraph_node (current_function_decl)->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
207 return true;
208 return false;
211 /* Return true when current function should always be optimized for size. */
213 bool
214 optimize_function_for_size_p (struct function *fun)
216 return (optimize_size
217 || (fun && fun->decl
218 && (cgraph_node (fun->decl)->frequency
219 == NODE_FREQUENCY_UNLIKELY_EXECUTED)));
222 /* Return true when current function should always be optimized for speed. */
224 bool
225 optimize_function_for_speed_p (struct function *fun)
227 return !optimize_function_for_size_p (fun);
230 /* Return TRUE when BB should be optimized for size. */
232 bool
233 optimize_bb_for_size_p (const_basic_block bb)
235 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
238 /* Return TRUE when BB should be optimized for speed. */
240 bool
241 optimize_bb_for_speed_p (const_basic_block bb)
243 return !optimize_bb_for_size_p (bb);
246 /* Return TRUE when BB should be optimized for size. */
248 bool
249 optimize_edge_for_size_p (edge e)
251 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
254 /* Return TRUE when BB should be optimized for speed. */
256 bool
257 optimize_edge_for_speed_p (edge e)
259 return !optimize_edge_for_size_p (e);
262 /* Return TRUE when BB should be optimized for size. */
264 bool
265 optimize_insn_for_size_p (void)
267 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
270 /* Return TRUE when BB should be optimized for speed. */
272 bool
273 optimize_insn_for_speed_p (void)
275 return !optimize_insn_for_size_p ();
278 /* Return TRUE when LOOP should be optimized for size. */
280 bool
281 optimize_loop_for_size_p (struct loop *loop)
283 return optimize_bb_for_size_p (loop->header);
286 /* Return TRUE when LOOP should be optimized for speed. */
288 bool
289 optimize_loop_for_speed_p (struct loop *loop)
291 return optimize_bb_for_speed_p (loop->header);
294 /* Return TRUE when LOOP nest should be optimized for speed. */
296 bool
297 optimize_loop_nest_for_speed_p (struct loop *loop)
299 struct loop *l = loop;
300 if (optimize_loop_for_speed_p (loop))
301 return true;
302 l = loop->inner;
303 while (l && l != loop)
305 if (optimize_loop_for_speed_p (l))
306 return true;
307 if (l->inner)
308 l = l->inner;
309 else if (l->next)
310 l = l->next;
311 else
313 while (l != loop && !l->next)
314 l = loop_outer (l);
315 if (l != loop)
316 l = l->next;
319 return false;
322 /* Return TRUE when LOOP nest should be optimized for size. */
324 bool
325 optimize_loop_nest_for_size_p (struct loop *loop)
327 return !optimize_loop_nest_for_speed_p (loop);
330 /* Return true when edge E is likely to be well predictable by branch
331 predictor. */
333 bool
334 predictable_edge_p (edge e)
336 if (profile_status == PROFILE_ABSENT)
337 return false;
338 if ((e->probability
339 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
340 || (REG_BR_PROB_BASE - e->probability
341 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
342 return true;
343 return false;
347 /* Set RTL expansion for BB profile. */
349 void
350 rtl_profile_for_bb (basic_block bb)
352 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
355 /* Set RTL expansion for edge profile. */
357 void
358 rtl_profile_for_edge (edge e)
360 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
363 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
364 void
365 default_rtl_profile (void)
367 crtl->maybe_hot_insn_p = true;
370 /* Return true if the one of outgoing edges is already predicted by
371 PREDICTOR. */
373 bool
374 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
376 rtx note;
377 if (!INSN_P (BB_END (bb)))
378 return false;
379 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
380 if (REG_NOTE_KIND (note) == REG_BR_PRED
381 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
382 return true;
383 return false;
386 /* This map contains for a basic block the list of predictions for the
387 outgoing edges. */
389 static struct pointer_map_t *bb_predictions;
391 /* Structure representing predictions in tree level. */
393 struct edge_prediction {
394 struct edge_prediction *ep_next;
395 edge ep_edge;
396 enum br_predictor ep_predictor;
397 int ep_probability;
400 /* Return true if the one of outgoing edges is already predicted by
401 PREDICTOR. */
403 bool
404 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
406 struct edge_prediction *i;
407 void **preds = pointer_map_contains (bb_predictions, bb);
409 if (!preds)
410 return false;
412 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
413 if (i->ep_predictor == predictor)
414 return true;
415 return false;
418 /* Return true when the probability of edge is reliable.
420 The profile guessing code is good at predicting branch outcome (ie.
421 taken/not taken), that is predicted right slightly over 75% of time.
422 It is however notoriously poor on predicting the probability itself.
423 In general the profile appear a lot flatter (with probabilities closer
424 to 50%) than the reality so it is bad idea to use it to drive optimization
425 such as those disabling dynamic branch prediction for well predictable
426 branches.
428 There are two exceptions - edges leading to noreturn edges and edges
429 predicted by number of iterations heuristics are predicted well. This macro
430 should be able to distinguish those, but at the moment it simply check for
431 noreturn heuristic that is only one giving probability over 99% or bellow
432 1%. In future we might want to propagate reliability information across the
433 CFG if we find this information useful on multiple places. */
434 static bool
435 probability_reliable_p (int prob)
437 return (profile_status == PROFILE_READ
438 || (profile_status == PROFILE_GUESSED
439 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
442 /* Same predicate as above, working on edges. */
443 bool
444 edge_probability_reliable_p (const_edge e)
446 return probability_reliable_p (e->probability);
449 /* Same predicate as edge_probability_reliable_p, working on notes. */
450 bool
451 br_prob_note_reliable_p (const_rtx note)
453 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
454 return probability_reliable_p (INTVAL (XEXP (note, 0)));
457 static void
458 predict_insn (rtx insn, enum br_predictor predictor, int probability)
460 gcc_assert (any_condjump_p (insn));
461 if (!flag_guess_branch_prob)
462 return;
464 add_reg_note (insn, REG_BR_PRED,
465 gen_rtx_CONCAT (VOIDmode,
466 GEN_INT ((int) predictor),
467 GEN_INT ((int) probability)));
470 /* Predict insn by given predictor. */
472 void
473 predict_insn_def (rtx insn, enum br_predictor predictor,
474 enum prediction taken)
476 int probability = predictor_info[(int) predictor].hitrate;
478 if (taken != TAKEN)
479 probability = REG_BR_PROB_BASE - probability;
481 predict_insn (insn, predictor, probability);
484 /* Predict edge E with given probability if possible. */
486 void
487 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
489 rtx last_insn;
490 last_insn = BB_END (e->src);
492 /* We can store the branch prediction information only about
493 conditional jumps. */
494 if (!any_condjump_p (last_insn))
495 return;
497 /* We always store probability of branching. */
498 if (e->flags & EDGE_FALLTHRU)
499 probability = REG_BR_PROB_BASE - probability;
501 predict_insn (last_insn, predictor, probability);
504 /* Predict edge E with the given PROBABILITY. */
505 void
506 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
508 gcc_assert (profile_status != PROFILE_GUESSED);
509 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
510 && flag_guess_branch_prob && optimize)
512 struct edge_prediction *i = XNEW (struct edge_prediction);
513 void **preds = pointer_map_insert (bb_predictions, e->src);
515 i->ep_next = (struct edge_prediction *) *preds;
516 *preds = i;
517 i->ep_probability = probability;
518 i->ep_predictor = predictor;
519 i->ep_edge = e;
523 /* Remove all predictions on given basic block that are attached
524 to edge E. */
525 void
526 remove_predictions_associated_with_edge (edge e)
528 void **preds;
530 if (!bb_predictions)
531 return;
533 preds = pointer_map_contains (bb_predictions, e->src);
535 if (preds)
537 struct edge_prediction **prediction = (struct edge_prediction **) preds;
538 struct edge_prediction *next;
540 while (*prediction)
542 if ((*prediction)->ep_edge == e)
544 next = (*prediction)->ep_next;
545 free (*prediction);
546 *prediction = next;
548 else
549 prediction = &((*prediction)->ep_next);
554 /* Clears the list of predictions stored for BB. */
556 static void
557 clear_bb_predictions (basic_block bb)
559 void **preds = pointer_map_contains (bb_predictions, bb);
560 struct edge_prediction *pred, *next;
562 if (!preds)
563 return;
565 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
567 next = pred->ep_next;
568 free (pred);
570 *preds = NULL;
573 /* Return true when we can store prediction on insn INSN.
574 At the moment we represent predictions only on conditional
575 jumps, not at computed jump or other complicated cases. */
576 static bool
577 can_predict_insn_p (const_rtx insn)
579 return (JUMP_P (insn)
580 && any_condjump_p (insn)
581 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
584 /* Predict edge E by given predictor if possible. */
586 void
587 predict_edge_def (edge e, enum br_predictor predictor,
588 enum prediction taken)
590 int probability = predictor_info[(int) predictor].hitrate;
592 if (taken != TAKEN)
593 probability = REG_BR_PROB_BASE - probability;
595 predict_edge (e, predictor, probability);
598 /* Invert all branch predictions or probability notes in the INSN. This needs
599 to be done each time we invert the condition used by the jump. */
601 void
602 invert_br_probabilities (rtx insn)
604 rtx note;
606 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
607 if (REG_NOTE_KIND (note) == REG_BR_PROB)
608 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
609 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
610 XEXP (XEXP (note, 0), 1)
611 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
614 /* Dump information about the branch prediction to the output file. */
616 static void
617 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
618 basic_block bb, int used)
620 edge e;
621 edge_iterator ei;
623 if (!file)
624 return;
626 FOR_EACH_EDGE (e, ei, bb->succs)
627 if (! (e->flags & EDGE_FALLTHRU))
628 break;
630 fprintf (file, " %s heuristics%s: %.1f%%",
631 predictor_info[predictor].name,
632 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
634 if (bb->count)
636 fprintf (file, " exec ");
637 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
638 if (e)
640 fprintf (file, " hit ");
641 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
642 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
646 fprintf (file, "\n");
649 /* We can not predict the probabilities of outgoing edges of bb. Set them
650 evenly and hope for the best. */
651 static void
652 set_even_probabilities (basic_block bb)
654 int nedges = 0;
655 edge e;
656 edge_iterator ei;
658 FOR_EACH_EDGE (e, ei, bb->succs)
659 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
660 nedges ++;
661 FOR_EACH_EDGE (e, ei, bb->succs)
662 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
663 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
664 else
665 e->probability = 0;
668 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
669 note if not already present. Remove now useless REG_BR_PRED notes. */
671 static void
672 combine_predictions_for_insn (rtx insn, basic_block bb)
674 rtx prob_note;
675 rtx *pnote;
676 rtx note;
677 int best_probability = PROB_EVEN;
678 enum br_predictor best_predictor = END_PREDICTORS;
679 int combined_probability = REG_BR_PROB_BASE / 2;
680 int d;
681 bool first_match = false;
682 bool found = false;
684 if (!can_predict_insn_p (insn))
686 set_even_probabilities (bb);
687 return;
690 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
691 pnote = &REG_NOTES (insn);
692 if (dump_file)
693 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
694 bb->index);
696 /* We implement "first match" heuristics and use probability guessed
697 by predictor with smallest index. */
698 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
699 if (REG_NOTE_KIND (note) == REG_BR_PRED)
701 enum br_predictor predictor = ((enum br_predictor)
702 INTVAL (XEXP (XEXP (note, 0), 0)));
703 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
705 found = true;
706 if (best_predictor > predictor)
707 best_probability = probability, best_predictor = predictor;
709 d = (combined_probability * probability
710 + (REG_BR_PROB_BASE - combined_probability)
711 * (REG_BR_PROB_BASE - probability));
713 /* Use FP math to avoid overflows of 32bit integers. */
714 if (d == 0)
715 /* If one probability is 0% and one 100%, avoid division by zero. */
716 combined_probability = REG_BR_PROB_BASE / 2;
717 else
718 combined_probability = (((double) combined_probability) * probability
719 * REG_BR_PROB_BASE / d + 0.5);
722 /* Decide which heuristic to use. In case we didn't match anything,
723 use no_prediction heuristic, in case we did match, use either
724 first match or Dempster-Shaffer theory depending on the flags. */
726 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
727 first_match = true;
729 if (!found)
730 dump_prediction (dump_file, PRED_NO_PREDICTION,
731 combined_probability, bb, true);
732 else
734 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
735 bb, !first_match);
736 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
737 bb, first_match);
740 if (first_match)
741 combined_probability = best_probability;
742 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
744 while (*pnote)
746 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
748 enum br_predictor predictor = ((enum br_predictor)
749 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
750 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
752 dump_prediction (dump_file, predictor, probability, bb,
753 !first_match || best_predictor == predictor);
754 *pnote = XEXP (*pnote, 1);
756 else
757 pnote = &XEXP (*pnote, 1);
760 if (!prob_note)
762 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
764 /* Save the prediction into CFG in case we are seeing non-degenerated
765 conditional jump. */
766 if (!single_succ_p (bb))
768 BRANCH_EDGE (bb)->probability = combined_probability;
769 FALLTHRU_EDGE (bb)->probability
770 = REG_BR_PROB_BASE - combined_probability;
773 else if (!single_succ_p (bb))
775 int prob = INTVAL (XEXP (prob_note, 0));
777 BRANCH_EDGE (bb)->probability = prob;
778 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
780 else
781 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
784 /* Combine predictions into single probability and store them into CFG.
785 Remove now useless prediction entries. */
787 static void
788 combine_predictions_for_bb (basic_block bb)
790 int best_probability = PROB_EVEN;
791 enum br_predictor best_predictor = END_PREDICTORS;
792 int combined_probability = REG_BR_PROB_BASE / 2;
793 int d;
794 bool first_match = false;
795 bool found = false;
796 struct edge_prediction *pred;
797 int nedges = 0;
798 edge e, first = NULL, second = NULL;
799 edge_iterator ei;
800 void **preds;
802 FOR_EACH_EDGE (e, ei, bb->succs)
803 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
805 nedges ++;
806 if (first && !second)
807 second = e;
808 if (!first)
809 first = e;
812 /* When there is no successor or only one choice, prediction is easy.
814 We are lazy for now and predict only basic blocks with two outgoing
815 edges. It is possible to predict generic case too, but we have to
816 ignore first match heuristics and do more involved combining. Implement
817 this later. */
818 if (nedges != 2)
820 if (!bb->count)
821 set_even_probabilities (bb);
822 clear_bb_predictions (bb);
823 if (dump_file)
824 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
825 nedges, bb->index);
826 return;
829 if (dump_file)
830 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
832 preds = pointer_map_contains (bb_predictions, bb);
833 if (preds)
835 /* We implement "first match" heuristics and use probability guessed
836 by predictor with smallest index. */
837 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
839 enum br_predictor predictor = pred->ep_predictor;
840 int probability = pred->ep_probability;
842 if (pred->ep_edge != first)
843 probability = REG_BR_PROB_BASE - probability;
845 found = true;
846 /* First match heuristics would be widly confused if we predicted
847 both directions. */
848 if (best_predictor > predictor)
850 struct edge_prediction *pred2;
851 int prob = probability;
853 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
854 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
856 int probability2 = pred->ep_probability;
858 if (pred2->ep_edge != first)
859 probability2 = REG_BR_PROB_BASE - probability2;
861 if ((probability < REG_BR_PROB_BASE / 2) !=
862 (probability2 < REG_BR_PROB_BASE / 2))
863 break;
865 /* If the same predictor later gave better result, go for it! */
866 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
867 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
868 prob = probability2;
870 if (!pred2)
871 best_probability = prob, best_predictor = predictor;
874 d = (combined_probability * probability
875 + (REG_BR_PROB_BASE - combined_probability)
876 * (REG_BR_PROB_BASE - probability));
878 /* Use FP math to avoid overflows of 32bit integers. */
879 if (d == 0)
880 /* If one probability is 0% and one 100%, avoid division by zero. */
881 combined_probability = REG_BR_PROB_BASE / 2;
882 else
883 combined_probability = (((double) combined_probability)
884 * probability
885 * REG_BR_PROB_BASE / d + 0.5);
889 /* Decide which heuristic to use. In case we didn't match anything,
890 use no_prediction heuristic, in case we did match, use either
891 first match or Dempster-Shaffer theory depending on the flags. */
893 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
894 first_match = true;
896 if (!found)
897 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
898 else
900 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
901 !first_match);
902 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
903 first_match);
906 if (first_match)
907 combined_probability = best_probability;
908 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
910 if (preds)
912 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
914 enum br_predictor predictor = pred->ep_predictor;
915 int probability = pred->ep_probability;
917 if (pred->ep_edge != EDGE_SUCC (bb, 0))
918 probability = REG_BR_PROB_BASE - probability;
919 dump_prediction (dump_file, predictor, probability, bb,
920 !first_match || best_predictor == predictor);
923 clear_bb_predictions (bb);
925 if (!bb->count)
927 first->probability = combined_probability;
928 second->probability = REG_BR_PROB_BASE - combined_probability;
932 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
933 Return the SSA_NAME if the condition satisfies, NULL otherwise.
935 T1 and T2 should be one of the following cases:
936 1. T1 is SSA_NAME, T2 is NULL
937 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
938 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
940 static tree
941 strips_small_constant (tree t1, tree t2)
943 tree ret = NULL;
944 int value = 0;
946 if (!t1)
947 return NULL;
948 else if (TREE_CODE (t1) == SSA_NAME)
949 ret = t1;
950 else if (TREE_CODE (t1) == INTEGER_CST && host_integerp (t1, 0))
951 value = tree_low_cst (t1, 0);
952 else
953 return NULL;
955 if (!t2)
956 return ret;
957 else if (TREE_CODE (t2) == INTEGER_CST && host_integerp (t2, 0))
958 value = tree_low_cst (t2, 0);
959 else if (TREE_CODE (t2) == SSA_NAME)
961 if (ret)
962 return NULL;
963 else
964 ret = t2;
967 if (value <= 4 && value >= -4)
968 return ret;
969 else
970 return NULL;
973 /* Return the SSA_NAME in T or T's operands.
974 Return NULL if SSA_NAME cannot be found. */
976 static tree
977 get_base_value (tree t)
979 if (TREE_CODE (t) == SSA_NAME)
980 return t;
982 if (!BINARY_CLASS_P (t))
983 return NULL;
985 switch (TREE_OPERAND_LENGTH (t))
987 case 1:
988 return strips_small_constant (TREE_OPERAND (t, 0), NULL);
989 case 2:
990 return strips_small_constant (TREE_OPERAND (t, 0),
991 TREE_OPERAND (t, 1));
992 default:
993 return NULL;
997 /* Check the compare STMT in LOOP. If it compares an induction
998 variable to a loop invariant, return true, and save
999 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1000 Otherwise return false and set LOOP_INVAIANT to NULL. */
1002 static bool
1003 is_comparison_with_loop_invariant_p (gimple stmt, struct loop *loop,
1004 tree *loop_invariant,
1005 enum tree_code *compare_code,
1006 int *loop_step,
1007 tree *loop_iv_base)
1009 tree op0, op1, bound, base;
1010 affine_iv iv0, iv1;
1011 enum tree_code code;
1012 int step;
1014 code = gimple_cond_code (stmt);
1015 *loop_invariant = NULL;
1017 switch (code)
1019 case GT_EXPR:
1020 case GE_EXPR:
1021 case NE_EXPR:
1022 case LT_EXPR:
1023 case LE_EXPR:
1024 case EQ_EXPR:
1025 break;
1027 default:
1028 return false;
1031 op0 = gimple_cond_lhs (stmt);
1032 op1 = gimple_cond_rhs (stmt);
1034 if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1035 || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1036 return false;
1037 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1038 return false;
1039 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1040 return false;
1041 if (TREE_CODE (iv0.step) != INTEGER_CST
1042 || TREE_CODE (iv1.step) != INTEGER_CST)
1043 return false;
1044 if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1045 || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1046 return false;
1048 if (integer_zerop (iv0.step))
1050 if (code != NE_EXPR && code != EQ_EXPR)
1051 code = invert_tree_comparison (code, false);
1052 bound = iv0.base;
1053 base = iv1.base;
1054 if (host_integerp (iv1.step, 0))
1055 step = tree_low_cst (iv1.step, 0);
1056 else
1057 return false;
1059 else
1061 bound = iv1.base;
1062 base = iv0.base;
1063 if (host_integerp (iv0.step, 0))
1064 step = tree_low_cst (iv0.step, 0);
1065 else
1066 return false;
1069 if (TREE_CODE (bound) != INTEGER_CST)
1070 bound = get_base_value (bound);
1071 if (!bound)
1072 return false;
1073 if (TREE_CODE (base) != INTEGER_CST)
1074 base = get_base_value (base);
1075 if (!base)
1076 return false;
1078 *loop_invariant = bound;
1079 *compare_code = code;
1080 *loop_step = step;
1081 *loop_iv_base = base;
1082 return true;
1085 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1087 static bool
1088 expr_coherent_p (tree t1, tree t2)
1090 gimple stmt;
1091 tree ssa_name_1 = NULL;
1092 tree ssa_name_2 = NULL;
1094 gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1095 gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1097 if (t1 == t2)
1098 return true;
1100 if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1101 return true;
1102 if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1103 return false;
1105 /* Check to see if t1 is expressed/defined with t2. */
1106 stmt = SSA_NAME_DEF_STMT (t1);
1107 gcc_assert (stmt != NULL);
1108 if (is_gimple_assign (stmt))
1110 ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1111 if (ssa_name_1 && ssa_name_1 == t2)
1112 return true;
1115 /* Check to see if t2 is expressed/defined with t1. */
1116 stmt = SSA_NAME_DEF_STMT (t2);
1117 gcc_assert (stmt != NULL);
1118 if (is_gimple_assign (stmt))
1120 ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1121 if (ssa_name_2 && ssa_name_2 == t1)
1122 return true;
1125 /* Compare if t1 and t2's def_stmts are identical. */
1126 if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1127 return true;
1128 else
1129 return false;
1132 /* Predict branch probability of BB when BB contains a branch that compares
1133 an induction variable with LOOP_IV_BASE_VAR in LOOP to LOOP_BOUND_VAR. The
1134 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1136 E.g.
1137 for (int i = 0; i < bound; i++) {
1138 if (i < bound - 2)
1139 computation_1();
1140 else
1141 computation_2();
1144 In this loop, we will predict the branch inside the loop to be taken. */
1146 static void
1147 predict_iv_comparison (struct loop *loop, basic_block bb,
1148 tree loop_bound_var,
1149 tree loop_iv_base_var,
1150 enum tree_code loop_bound_code,
1151 int loop_bound_step)
1153 gimple stmt;
1154 tree compare_var, compare_base;
1155 enum tree_code compare_code;
1156 int compare_step;
1157 edge then_edge;
1158 edge_iterator ei;
1160 if (predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1161 || predicted_by_p (bb, PRED_LOOP_ITERATIONS)
1162 || predicted_by_p (bb, PRED_LOOP_EXIT))
1163 return;
1165 stmt = last_stmt (bb);
1166 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1167 return;
1168 if (!is_comparison_with_loop_invariant_p (stmt, loop, &compare_var,
1169 &compare_code,
1170 &compare_step,
1171 &compare_base))
1172 return;
1174 /* Find the taken edge. */
1175 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1176 if (then_edge->flags & EDGE_TRUE_VALUE)
1177 break;
1179 /* When comparing an IV to a loop invariant, NE is more likely to be
1180 taken while EQ is more likely to be not-taken. */
1181 if (compare_code == NE_EXPR)
1183 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1184 return;
1186 else if (compare_code == EQ_EXPR)
1188 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, NOT_TAKEN);
1189 return;
1192 if (!expr_coherent_p(loop_iv_base_var, compare_base))
1193 return;
1195 /* If loop bound, base and compare bound are all constents, we can
1196 calculate the probability directly. */
1197 if (TREE_CODE (loop_bound_var) == INTEGER_CST
1198 && TREE_CODE (compare_var) == INTEGER_CST
1199 && TREE_CODE (compare_base) == INTEGER_CST
1200 && host_integerp (loop_bound_var, 0)
1201 && host_integerp (compare_var, 0)
1202 && host_integerp (compare_base, 0))
1204 int probability;
1205 HOST_WIDE_INT compare_count;
1206 HOST_WIDE_INT loop_bound = tree_low_cst (loop_bound_var, 0);
1207 HOST_WIDE_INT compare_bound = tree_low_cst (compare_var, 0);
1208 HOST_WIDE_INT base = tree_low_cst (compare_base, 0);
1209 HOST_WIDE_INT loop_count = (loop_bound - base) / compare_step;
1211 if ((compare_step > 0)
1212 ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1213 compare_count = (loop_bound - compare_bound) / compare_step;
1214 else
1215 compare_count = (compare_bound - base) / compare_step;
1217 if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1218 compare_count ++;
1219 if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1220 loop_count ++;
1221 if (compare_count < 0)
1222 compare_count = 0;
1223 if (loop_count < 0)
1224 loop_count = 0;
1226 if (loop_count == 0)
1227 probability = 0;
1228 else if (compare_count > loop_count)
1229 probability = REG_BR_PROB_BASE;
1230 else
1231 probability = (double) REG_BR_PROB_BASE * compare_count / loop_count;
1232 predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1233 return;
1236 if (expr_coherent_p (loop_bound_var, compare_var))
1238 if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1239 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1240 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1241 else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1242 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1243 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1244 else if (loop_bound_code == NE_EXPR)
1246 /* If the loop backedge condition is "(i != bound)", we do
1247 the comparison based on the step of IV:
1248 * step < 0 : backedge condition is like (i > bound)
1249 * step > 0 : backedge condition is like (i < bound) */
1250 gcc_assert (loop_bound_step != 0);
1251 if (loop_bound_step > 0
1252 && (compare_code == LT_EXPR
1253 || compare_code == LE_EXPR))
1254 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1255 else if (loop_bound_step < 0
1256 && (compare_code == GT_EXPR
1257 || compare_code == GE_EXPR))
1258 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1259 else
1260 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, NOT_TAKEN);
1262 else
1263 /* The branch is predicted not-taken if loop_bound_code is
1264 opposite with compare_code. */
1265 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, NOT_TAKEN);
1267 else if (expr_coherent_p (loop_iv_base_var, compare_var))
1269 /* For cases like:
1270 for (i = s; i < h; i++)
1271 if (i > s + 2) ....
1272 The branch should be predicted taken. */
1273 if (loop_bound_step > 0
1274 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1275 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1276 else if (loop_bound_step < 0
1277 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1278 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, TAKEN);
1279 else
1280 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE, NOT_TAKEN);
1284 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1285 exits are resulted from short-circuit conditions that will generate an
1286 if_tmp. E.g.:
1288 if (foo() || global > 10)
1289 break;
1291 This will be translated into:
1293 BB3:
1294 loop header...
1295 BB4:
1296 if foo() goto BB6 else goto BB5
1297 BB5:
1298 if global > 10 goto BB6 else goto BB7
1299 BB6:
1300 goto BB7
1301 BB7:
1302 iftmp = (PHI 0(BB5), 1(BB6))
1303 if iftmp == 1 goto BB8 else goto BB3
1304 BB8:
1305 outside of the loop...
1307 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1308 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1309 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1310 exits to predict them using PRED_LOOP_EXIT. */
1312 static void
1313 predict_extra_loop_exits (edge exit_edge)
1315 unsigned i;
1316 bool check_value_one;
1317 gimple phi_stmt;
1318 tree cmp_rhs, cmp_lhs;
1319 gimple cmp_stmt = last_stmt (exit_edge->src);
1321 if (!cmp_stmt || gimple_code (cmp_stmt) != GIMPLE_COND)
1322 return;
1323 cmp_rhs = gimple_cond_rhs (cmp_stmt);
1324 cmp_lhs = gimple_cond_lhs (cmp_stmt);
1325 if (!TREE_CONSTANT (cmp_rhs)
1326 || !(integer_zerop (cmp_rhs) || integer_onep (cmp_rhs)))
1327 return;
1328 if (TREE_CODE (cmp_lhs) != SSA_NAME)
1329 return;
1331 /* If check_value_one is true, only the phi_args with value '1' will lead
1332 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1333 loop exit. */
1334 check_value_one = (((integer_onep (cmp_rhs))
1335 ^ (gimple_cond_code (cmp_stmt) == EQ_EXPR))
1336 ^ ((exit_edge->flags & EDGE_TRUE_VALUE) != 0));
1338 phi_stmt = SSA_NAME_DEF_STMT (cmp_lhs);
1339 if (!phi_stmt || gimple_code (phi_stmt) != GIMPLE_PHI)
1340 return;
1342 for (i = 0; i < gimple_phi_num_args (phi_stmt); i++)
1344 edge e1;
1345 edge_iterator ei;
1346 tree val = gimple_phi_arg_def (phi_stmt, i);
1347 edge e = gimple_phi_arg_edge (phi_stmt, i);
1349 if (!TREE_CONSTANT (val) || !(integer_zerop (val) || integer_onep (val)))
1350 continue;
1351 if (check_value_one ^ integer_onep (val))
1352 continue;
1353 if (VEC_length (edge, e->src->succs) != 1)
1355 if (!predicted_by_p (exit_edge->src, PRED_LOOP_ITERATIONS_GUESSED)
1356 && !predicted_by_p (exit_edge->src, PRED_LOOP_ITERATIONS)
1357 && !predicted_by_p (exit_edge->src, PRED_LOOP_EXIT))
1358 predict_edge_def (e, PRED_LOOP_EXIT, NOT_TAKEN);
1359 continue;
1362 FOR_EACH_EDGE (e1, ei, e->src->preds)
1363 if (!predicted_by_p (exit_edge->src, PRED_LOOP_ITERATIONS_GUESSED)
1364 && !predicted_by_p (exit_edge->src, PRED_LOOP_ITERATIONS)
1365 && !predicted_by_p (exit_edge->src, PRED_LOOP_EXIT))
1366 predict_edge_def (e1, PRED_LOOP_EXIT, NOT_TAKEN);
1370 /* Predict edge probabilities by exploiting loop structure. */
1372 static void
1373 predict_loops (void)
1375 loop_iterator li;
1376 struct loop *loop;
1378 /* Try to predict out blocks in a loop that are not part of a
1379 natural loop. */
1380 FOR_EACH_LOOP (li, loop, 0)
1382 basic_block bb, *bbs;
1383 unsigned j, n_exits;
1384 VEC (edge, heap) *exits;
1385 struct tree_niter_desc niter_desc;
1386 edge ex;
1387 struct nb_iter_bound *nb_iter;
1388 enum tree_code loop_bound_code = ERROR_MARK;
1389 int loop_bound_step = 0;
1390 tree loop_bound_var = NULL;
1391 tree loop_iv_base = NULL;
1392 gimple stmt = NULL;
1394 exits = get_loop_exit_edges (loop);
1395 n_exits = VEC_length (edge, exits);
1397 FOR_EACH_VEC_ELT (edge, exits, j, ex)
1399 tree niter = NULL;
1400 HOST_WIDE_INT nitercst;
1401 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
1402 int probability;
1403 enum br_predictor predictor;
1405 predict_extra_loop_exits (ex);
1407 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
1408 niter = niter_desc.niter;
1409 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
1410 niter = loop_niter_by_eval (loop, ex);
1412 if (TREE_CODE (niter) == INTEGER_CST)
1414 if (host_integerp (niter, 1)
1415 && compare_tree_int (niter, max-1) == -1)
1416 nitercst = tree_low_cst (niter, 1) + 1;
1417 else
1418 nitercst = max;
1419 predictor = PRED_LOOP_ITERATIONS;
1421 /* If we have just one exit and we can derive some information about
1422 the number of iterations of the loop from the statements inside
1423 the loop, use it to predict this exit. */
1424 else if (n_exits == 1)
1426 nitercst = estimated_loop_iterations_int (loop, false);
1427 if (nitercst < 0)
1428 continue;
1429 if (nitercst > max)
1430 nitercst = max;
1432 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1434 else
1435 continue;
1437 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
1438 predict_edge (ex, predictor, probability);
1440 VEC_free (edge, heap, exits);
1442 /* Find information about loop bound variables. */
1443 for (nb_iter = loop->bounds; nb_iter;
1444 nb_iter = nb_iter->next)
1445 if (nb_iter->stmt
1446 && gimple_code (nb_iter->stmt) == GIMPLE_COND)
1448 stmt = nb_iter->stmt;
1449 break;
1451 if (!stmt && last_stmt (loop->header)
1452 && gimple_code (last_stmt (loop->header)) == GIMPLE_COND)
1453 stmt = last_stmt (loop->header);
1454 if (stmt)
1455 is_comparison_with_loop_invariant_p (stmt, loop,
1456 &loop_bound_var,
1457 &loop_bound_code,
1458 &loop_bound_step,
1459 &loop_iv_base);
1461 bbs = get_loop_body (loop);
1463 for (j = 0; j < loop->num_nodes; j++)
1465 int header_found = 0;
1466 edge e;
1467 edge_iterator ei;
1469 bb = bbs[j];
1471 /* Bypass loop heuristics on continue statement. These
1472 statements construct loops via "non-loop" constructs
1473 in the source language and are better to be handled
1474 separately. */
1475 if (predicted_by_p (bb, PRED_CONTINUE))
1476 continue;
1478 /* Loop branch heuristics - predict an edge back to a
1479 loop's head as taken. */
1480 if (bb == loop->latch)
1482 e = find_edge (loop->latch, loop->header);
1483 if (e)
1485 header_found = 1;
1486 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1490 /* Loop exit heuristics - predict an edge exiting the loop if the
1491 conditional has no loop header successors as not taken. */
1492 if (!header_found
1493 /* If we already used more reliable loop exit predictors, do not
1494 bother with PRED_LOOP_EXIT. */
1495 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1496 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1498 /* For loop with many exits we don't want to predict all exits
1499 with the pretty large probability, because if all exits are
1500 considered in row, the loop would be predicted to iterate
1501 almost never. The code to divide probability by number of
1502 exits is very rough. It should compute the number of exits
1503 taken in each patch through function (not the overall number
1504 of exits that might be a lot higher for loops with wide switch
1505 statements in them) and compute n-th square root.
1507 We limit the minimal probability by 2% to avoid
1508 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1509 as this was causing regression in perl benchmark containing such
1510 a wide loop. */
1512 int probability = ((REG_BR_PROB_BASE
1513 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1514 / n_exits);
1515 if (probability < HITRATE (2))
1516 probability = HITRATE (2);
1517 FOR_EACH_EDGE (e, ei, bb->succs)
1518 if (e->dest->index < NUM_FIXED_BLOCKS
1519 || !flow_bb_inside_loop_p (loop, e->dest))
1520 predict_edge (e, PRED_LOOP_EXIT, probability);
1522 if (loop_bound_var)
1523 predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
1524 loop_bound_code,
1525 loop_bound_step);
1528 /* Free basic blocks from get_loop_body. */
1529 free (bbs);
1533 /* Attempt to predict probabilities of BB outgoing edges using local
1534 properties. */
1535 static void
1536 bb_estimate_probability_locally (basic_block bb)
1538 rtx last_insn = BB_END (bb);
1539 rtx cond;
1541 if (! can_predict_insn_p (last_insn))
1542 return;
1543 cond = get_condition (last_insn, NULL, false, false);
1544 if (! cond)
1545 return;
1547 /* Try "pointer heuristic."
1548 A comparison ptr == 0 is predicted as false.
1549 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1550 if (COMPARISON_P (cond)
1551 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1552 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1554 if (GET_CODE (cond) == EQ)
1555 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1556 else if (GET_CODE (cond) == NE)
1557 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1559 else
1561 /* Try "opcode heuristic."
1562 EQ tests are usually false and NE tests are usually true. Also,
1563 most quantities are positive, so we can make the appropriate guesses
1564 about signed comparisons against zero. */
1565 switch (GET_CODE (cond))
1567 case CONST_INT:
1568 /* Unconditional branch. */
1569 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1570 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1571 break;
1573 case EQ:
1574 case UNEQ:
1575 /* Floating point comparisons appears to behave in a very
1576 unpredictable way because of special role of = tests in
1577 FP code. */
1578 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1580 /* Comparisons with 0 are often used for booleans and there is
1581 nothing useful to predict about them. */
1582 else if (XEXP (cond, 1) == const0_rtx
1583 || XEXP (cond, 0) == const0_rtx)
1585 else
1586 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1587 break;
1589 case NE:
1590 case LTGT:
1591 /* Floating point comparisons appears to behave in a very
1592 unpredictable way because of special role of = tests in
1593 FP code. */
1594 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1596 /* Comparisons with 0 are often used for booleans and there is
1597 nothing useful to predict about them. */
1598 else if (XEXP (cond, 1) == const0_rtx
1599 || XEXP (cond, 0) == const0_rtx)
1601 else
1602 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1603 break;
1605 case ORDERED:
1606 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1607 break;
1609 case UNORDERED:
1610 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1611 break;
1613 case LE:
1614 case LT:
1615 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1616 || XEXP (cond, 1) == constm1_rtx)
1617 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1618 break;
1620 case GE:
1621 case GT:
1622 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1623 || XEXP (cond, 1) == constm1_rtx)
1624 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1625 break;
1627 default:
1628 break;
1632 /* Set edge->probability for each successor edge of BB. */
1633 void
1634 guess_outgoing_edge_probabilities (basic_block bb)
1636 bb_estimate_probability_locally (bb);
1637 combine_predictions_for_insn (BB_END (bb), bb);
1640 static tree expr_expected_value (tree, bitmap);
1642 /* Helper function for expr_expected_value. */
1644 static tree
1645 expr_expected_value_1 (tree type, tree op0, enum tree_code code, tree op1, bitmap visited)
1647 gimple def;
1649 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1651 if (TREE_CONSTANT (op0))
1652 return op0;
1654 if (code != SSA_NAME)
1655 return NULL_TREE;
1657 def = SSA_NAME_DEF_STMT (op0);
1659 /* If we were already here, break the infinite cycle. */
1660 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
1661 return NULL;
1663 if (gimple_code (def) == GIMPLE_PHI)
1665 /* All the arguments of the PHI node must have the same constant
1666 length. */
1667 int i, n = gimple_phi_num_args (def);
1668 tree val = NULL, new_val;
1670 for (i = 0; i < n; i++)
1672 tree arg = PHI_ARG_DEF (def, i);
1674 /* If this PHI has itself as an argument, we cannot
1675 determine the string length of this argument. However,
1676 if we can find an expected constant value for the other
1677 PHI args then we can still be sure that this is
1678 likely a constant. So be optimistic and just
1679 continue with the next argument. */
1680 if (arg == PHI_RESULT (def))
1681 continue;
1683 new_val = expr_expected_value (arg, visited);
1684 if (!new_val)
1685 return NULL;
1686 if (!val)
1687 val = new_val;
1688 else if (!operand_equal_p (val, new_val, false))
1689 return NULL;
1691 return val;
1693 if (is_gimple_assign (def))
1695 if (gimple_assign_lhs (def) != op0)
1696 return NULL;
1698 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1699 gimple_assign_rhs1 (def),
1700 gimple_assign_rhs_code (def),
1701 gimple_assign_rhs2 (def),
1702 visited);
1705 if (is_gimple_call (def))
1707 tree decl = gimple_call_fndecl (def);
1708 if (!decl)
1709 return NULL;
1710 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1711 && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
1713 tree val;
1715 if (gimple_call_num_args (def) != 2)
1716 return NULL;
1717 val = gimple_call_arg (def, 0);
1718 if (TREE_CONSTANT (val))
1719 return val;
1720 return gimple_call_arg (def, 1);
1724 return NULL;
1727 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1729 tree res;
1730 op0 = expr_expected_value (op0, visited);
1731 if (!op0)
1732 return NULL;
1733 op1 = expr_expected_value (op1, visited);
1734 if (!op1)
1735 return NULL;
1736 res = fold_build2 (code, type, op0, op1);
1737 if (TREE_CONSTANT (res))
1738 return res;
1739 return NULL;
1741 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1743 tree res;
1744 op0 = expr_expected_value (op0, visited);
1745 if (!op0)
1746 return NULL;
1747 res = fold_build1 (code, type, op0);
1748 if (TREE_CONSTANT (res))
1749 return res;
1750 return NULL;
1752 return NULL;
1755 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1756 The function is used by builtin_expect branch predictor so the evidence
1757 must come from this construct and additional possible constant folding.
1759 We may want to implement more involved value guess (such as value range
1760 propagation based prediction), but such tricks shall go to new
1761 implementation. */
1763 static tree
1764 expr_expected_value (tree expr, bitmap visited)
1766 enum tree_code code;
1767 tree op0, op1;
1769 if (TREE_CONSTANT (expr))
1770 return expr;
1772 extract_ops_from_tree (expr, &code, &op0, &op1);
1773 return expr_expected_value_1 (TREE_TYPE (expr),
1774 op0, code, op1, visited);
1778 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1779 we no longer need. */
1780 static unsigned int
1781 strip_predict_hints (void)
1783 basic_block bb;
1784 gimple ass_stmt;
1785 tree var;
1787 FOR_EACH_BB (bb)
1789 gimple_stmt_iterator bi;
1790 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1792 gimple stmt = gsi_stmt (bi);
1794 if (gimple_code (stmt) == GIMPLE_PREDICT)
1796 gsi_remove (&bi, true);
1797 continue;
1799 else if (gimple_code (stmt) == GIMPLE_CALL)
1801 tree fndecl = gimple_call_fndecl (stmt);
1803 if (fndecl
1804 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1805 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1806 && gimple_call_num_args (stmt) == 2)
1808 var = gimple_call_lhs (stmt);
1809 if (var)
1811 ass_stmt
1812 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1813 gsi_replace (&bi, ass_stmt, true);
1815 else
1817 gsi_remove (&bi, true);
1818 continue;
1822 gsi_next (&bi);
1825 return 0;
1828 /* Predict using opcode of the last statement in basic block. */
1829 static void
1830 tree_predict_by_opcode (basic_block bb)
1832 gimple stmt = last_stmt (bb);
1833 edge then_edge;
1834 tree op0, op1;
1835 tree type;
1836 tree val;
1837 enum tree_code cmp;
1838 bitmap visited;
1839 edge_iterator ei;
1841 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1842 return;
1843 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1844 if (then_edge->flags & EDGE_TRUE_VALUE)
1845 break;
1846 op0 = gimple_cond_lhs (stmt);
1847 op1 = gimple_cond_rhs (stmt);
1848 cmp = gimple_cond_code (stmt);
1849 type = TREE_TYPE (op0);
1850 visited = BITMAP_ALLOC (NULL);
1851 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1852 BITMAP_FREE (visited);
1853 if (val)
1855 if (integer_zerop (val))
1856 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1857 else
1858 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1859 return;
1861 /* Try "pointer heuristic."
1862 A comparison ptr == 0 is predicted as false.
1863 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1864 if (POINTER_TYPE_P (type))
1866 if (cmp == EQ_EXPR)
1867 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1868 else if (cmp == NE_EXPR)
1869 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1871 else
1873 /* Try "opcode heuristic."
1874 EQ tests are usually false and NE tests are usually true. Also,
1875 most quantities are positive, so we can make the appropriate guesses
1876 about signed comparisons against zero. */
1877 switch (cmp)
1879 case EQ_EXPR:
1880 case UNEQ_EXPR:
1881 /* Floating point comparisons appears to behave in a very
1882 unpredictable way because of special role of = tests in
1883 FP code. */
1884 if (FLOAT_TYPE_P (type))
1886 /* Comparisons with 0 are often used for booleans and there is
1887 nothing useful to predict about them. */
1888 else if (integer_zerop (op0) || integer_zerop (op1))
1890 else
1891 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1892 break;
1894 case NE_EXPR:
1895 case LTGT_EXPR:
1896 /* Floating point comparisons appears to behave in a very
1897 unpredictable way because of special role of = tests in
1898 FP code. */
1899 if (FLOAT_TYPE_P (type))
1901 /* Comparisons with 0 are often used for booleans and there is
1902 nothing useful to predict about them. */
1903 else if (integer_zerop (op0)
1904 || integer_zerop (op1))
1906 else
1907 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1908 break;
1910 case ORDERED_EXPR:
1911 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1912 break;
1914 case UNORDERED_EXPR:
1915 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1916 break;
1918 case LE_EXPR:
1919 case LT_EXPR:
1920 if (integer_zerop (op1)
1921 || integer_onep (op1)
1922 || integer_all_onesp (op1)
1923 || real_zerop (op1)
1924 || real_onep (op1)
1925 || real_minus_onep (op1))
1926 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1927 break;
1929 case GE_EXPR:
1930 case GT_EXPR:
1931 if (integer_zerop (op1)
1932 || integer_onep (op1)
1933 || integer_all_onesp (op1)
1934 || real_zerop (op1)
1935 || real_onep (op1)
1936 || real_minus_onep (op1))
1937 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1938 break;
1940 default:
1941 break;
1945 /* Try to guess whether the value of return means error code. */
1947 static enum br_predictor
1948 return_prediction (tree val, enum prediction *prediction)
1950 /* VOID. */
1951 if (!val)
1952 return PRED_NO_PREDICTION;
1953 /* Different heuristics for pointers and scalars. */
1954 if (POINTER_TYPE_P (TREE_TYPE (val)))
1956 /* NULL is usually not returned. */
1957 if (integer_zerop (val))
1959 *prediction = NOT_TAKEN;
1960 return PRED_NULL_RETURN;
1963 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1965 /* Negative return values are often used to indicate
1966 errors. */
1967 if (TREE_CODE (val) == INTEGER_CST
1968 && tree_int_cst_sgn (val) < 0)
1970 *prediction = NOT_TAKEN;
1971 return PRED_NEGATIVE_RETURN;
1973 /* Constant return values seems to be commonly taken.
1974 Zero/one often represent booleans so exclude them from the
1975 heuristics. */
1976 if (TREE_CONSTANT (val)
1977 && (!integer_zerop (val) && !integer_onep (val)))
1979 *prediction = TAKEN;
1980 return PRED_CONST_RETURN;
1983 return PRED_NO_PREDICTION;
1986 /* Find the basic block with return expression and look up for possible
1987 return value trying to apply RETURN_PREDICTION heuristics. */
1988 static void
1989 apply_return_prediction (void)
1991 gimple return_stmt = NULL;
1992 tree return_val;
1993 edge e;
1994 gimple phi;
1995 int phi_num_args, i;
1996 enum br_predictor pred;
1997 enum prediction direction;
1998 edge_iterator ei;
2000 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2002 return_stmt = last_stmt (e->src);
2003 if (return_stmt
2004 && gimple_code (return_stmt) == GIMPLE_RETURN)
2005 break;
2007 if (!e)
2008 return;
2009 return_val = gimple_return_retval (return_stmt);
2010 if (!return_val)
2011 return;
2012 if (TREE_CODE (return_val) != SSA_NAME
2013 || !SSA_NAME_DEF_STMT (return_val)
2014 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
2015 return;
2016 phi = SSA_NAME_DEF_STMT (return_val);
2017 phi_num_args = gimple_phi_num_args (phi);
2018 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
2020 /* Avoid the degenerate case where all return values form the function
2021 belongs to same category (ie they are all positive constants)
2022 so we can hardly say something about them. */
2023 for (i = 1; i < phi_num_args; i++)
2024 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
2025 break;
2026 if (i != phi_num_args)
2027 for (i = 0; i < phi_num_args; i++)
2029 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
2030 if (pred != PRED_NO_PREDICTION)
2031 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
2032 direction);
2036 /* Look for basic block that contains unlikely to happen events
2037 (such as noreturn calls) and mark all paths leading to execution
2038 of this basic blocks as unlikely. */
2040 static void
2041 tree_bb_level_predictions (void)
2043 basic_block bb;
2044 bool has_return_edges = false;
2045 edge e;
2046 edge_iterator ei;
2048 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2049 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
2051 has_return_edges = true;
2052 break;
2055 apply_return_prediction ();
2057 FOR_EACH_BB (bb)
2059 gimple_stmt_iterator gsi;
2061 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2063 gimple stmt = gsi_stmt (gsi);
2064 tree decl;
2066 if (is_gimple_call (stmt))
2068 if ((gimple_call_flags (stmt) & ECF_NORETURN)
2069 && has_return_edges)
2070 predict_paths_leading_to (bb, PRED_NORETURN,
2071 NOT_TAKEN);
2072 decl = gimple_call_fndecl (stmt);
2073 if (decl
2074 && lookup_attribute ("cold",
2075 DECL_ATTRIBUTES (decl)))
2076 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
2077 NOT_TAKEN);
2079 else if (gimple_code (stmt) == GIMPLE_PREDICT)
2081 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
2082 gimple_predict_outcome (stmt));
2083 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2084 hints to callers. */
2090 #ifdef ENABLE_CHECKING
2092 /* Callback for pointer_map_traverse, asserts that the pointer map is
2093 empty. */
2095 static bool
2096 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
2097 void *data ATTRIBUTE_UNUSED)
2099 gcc_assert (!*value);
2100 return false;
2102 #endif
2104 /* Predict branch probabilities and estimate profile for basic block BB. */
2106 static void
2107 tree_estimate_probability_bb (basic_block bb)
2109 edge e;
2110 edge_iterator ei;
2111 gimple last;
2113 FOR_EACH_EDGE (e, ei, bb->succs)
2115 /* Predict early returns to be probable, as we've already taken
2116 care for error returns and other cases are often used for
2117 fast paths through function.
2119 Since we've already removed the return statements, we are
2120 looking for CFG like:
2122 if (conditional)
2125 goto return_block
2127 some other blocks
2128 return_block:
2129 return_stmt. */
2130 if (e->dest != bb->next_bb
2131 && e->dest != EXIT_BLOCK_PTR
2132 && single_succ_p (e->dest)
2133 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
2134 && (last = last_stmt (e->dest)) != NULL
2135 && gimple_code (last) == GIMPLE_RETURN)
2137 edge e1;
2138 edge_iterator ei1;
2140 if (single_succ_p (bb))
2142 FOR_EACH_EDGE (e1, ei1, bb->preds)
2143 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
2144 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
2145 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
2146 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2148 else
2149 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
2150 && !predicted_by_p (e->src, PRED_CONST_RETURN)
2151 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
2152 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2155 /* Look for block we are guarding (ie we dominate it,
2156 but it doesn't postdominate us). */
2157 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
2158 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
2159 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
2161 gimple_stmt_iterator bi;
2163 /* The call heuristic claims that a guarded function call
2164 is improbable. This is because such calls are often used
2165 to signal exceptional situations such as printing error
2166 messages. */
2167 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
2168 gsi_next (&bi))
2170 gimple stmt = gsi_stmt (bi);
2171 if (is_gimple_call (stmt)
2172 /* Constant and pure calls are hardly used to signalize
2173 something exceptional. */
2174 && gimple_has_side_effects (stmt))
2176 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
2177 break;
2182 tree_predict_by_opcode (bb);
2185 /* Predict branch probabilities and estimate profile of the tree CFG.
2186 This function can be called from the loop optimizers to recompute
2187 the profile information. */
2189 void
2190 tree_estimate_probability (void)
2192 basic_block bb;
2194 add_noreturn_fake_exit_edges ();
2195 connect_infinite_loops_to_exit ();
2196 /* We use loop_niter_by_eval, which requires that the loops have
2197 preheaders. */
2198 create_preheaders (CP_SIMPLE_PREHEADERS);
2199 calculate_dominance_info (CDI_POST_DOMINATORS);
2201 bb_predictions = pointer_map_create ();
2202 tree_bb_level_predictions ();
2203 record_loop_exits ();
2205 if (number_of_loops () > 1)
2206 predict_loops ();
2208 FOR_EACH_BB (bb)
2209 tree_estimate_probability_bb (bb);
2211 FOR_EACH_BB (bb)
2212 combine_predictions_for_bb (bb);
2214 #ifdef ENABLE_CHECKING
2215 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
2216 #endif
2217 pointer_map_destroy (bb_predictions);
2218 bb_predictions = NULL;
2220 estimate_bb_frequencies ();
2221 free_dominance_info (CDI_POST_DOMINATORS);
2222 remove_fake_exit_edges ();
2225 /* Predict branch probabilities and estimate profile of the tree CFG.
2226 This is the driver function for PASS_PROFILE. */
2228 static unsigned int
2229 tree_estimate_probability_driver (void)
2231 unsigned nb_loops;
2233 loop_optimizer_init (0);
2234 if (dump_file && (dump_flags & TDF_DETAILS))
2235 flow_loops_dump (dump_file, NULL, 0);
2237 mark_irreducible_loops ();
2239 nb_loops = number_of_loops ();
2240 if (nb_loops > 1)
2241 scev_initialize ();
2243 tree_estimate_probability ();
2245 if (nb_loops > 1)
2246 scev_finalize ();
2248 loop_optimizer_finalize ();
2249 if (dump_file && (dump_flags & TDF_DETAILS))
2250 gimple_dump_cfg (dump_file, dump_flags);
2251 if (profile_status == PROFILE_ABSENT)
2252 profile_status = PROFILE_GUESSED;
2253 return 0;
2256 /* Predict edges to successors of CUR whose sources are not postdominated by
2257 BB by PRED and recurse to all postdominators. */
2259 static void
2260 predict_paths_for_bb (basic_block cur, basic_block bb,
2261 enum br_predictor pred,
2262 enum prediction taken,
2263 bitmap visited)
2265 edge e;
2266 edge_iterator ei;
2267 basic_block son;
2269 /* We are looking for all edges forming edge cut induced by
2270 set of all blocks postdominated by BB. */
2271 FOR_EACH_EDGE (e, ei, cur->preds)
2272 if (e->src->index >= NUM_FIXED_BLOCKS
2273 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
2275 edge e2;
2276 edge_iterator ei2;
2277 bool found = false;
2279 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2280 if (e->flags & (EDGE_EH | EDGE_FAKE))
2281 continue;
2282 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
2284 /* See if there is an edge from e->src that is not abnormal
2285 and does not lead to BB. */
2286 FOR_EACH_EDGE (e2, ei2, e->src->succs)
2287 if (e2 != e
2288 && !(e2->flags & (EDGE_EH | EDGE_FAKE))
2289 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb))
2291 found = true;
2292 break;
2295 /* If there is non-abnormal path leaving e->src, predict edge
2296 using predictor. Otherwise we need to look for paths
2297 leading to e->src.
2299 The second may lead to infinite loop in the case we are predicitng
2300 regions that are only reachable by abnormal edges. We simply
2301 prevent visiting given BB twice. */
2302 if (found)
2303 predict_edge_def (e, pred, taken);
2304 else if (bitmap_set_bit (visited, e->src->index))
2305 predict_paths_for_bb (e->src, e->src, pred, taken, visited);
2307 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
2308 son;
2309 son = next_dom_son (CDI_POST_DOMINATORS, son))
2310 predict_paths_for_bb (son, bb, pred, taken, visited);
2313 /* Sets branch probabilities according to PREDiction and
2314 FLAGS. */
2316 static void
2317 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
2318 enum prediction taken)
2320 bitmap visited = BITMAP_ALLOC (NULL);
2321 predict_paths_for_bb (bb, bb, pred, taken, visited);
2322 BITMAP_FREE (visited);
2325 /* Like predict_paths_leading_to but take edge instead of basic block. */
2327 static void
2328 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
2329 enum prediction taken)
2331 bool has_nonloop_edge = false;
2332 edge_iterator ei;
2333 edge e2;
2335 basic_block bb = e->src;
2336 FOR_EACH_EDGE (e2, ei, bb->succs)
2337 if (e2->dest != e->src && e2->dest != e->dest
2338 && !(e->flags & (EDGE_EH | EDGE_FAKE))
2339 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
2341 has_nonloop_edge = true;
2342 break;
2344 if (!has_nonloop_edge)
2346 bitmap visited = BITMAP_ALLOC (NULL);
2347 predict_paths_for_bb (bb, bb, pred, taken, visited);
2348 BITMAP_FREE (visited);
2350 else
2351 predict_edge_def (e, pred, taken);
2354 /* This is used to carry information about basic blocks. It is
2355 attached to the AUX field of the standard CFG block. */
2357 typedef struct block_info_def
2359 /* Estimated frequency of execution of basic_block. */
2360 sreal frequency;
2362 /* To keep queue of basic blocks to process. */
2363 basic_block next;
2365 /* Number of predecessors we need to visit first. */
2366 int npredecessors;
2367 } *block_info;
2369 /* Similar information for edges. */
2370 typedef struct edge_info_def
2372 /* In case edge is a loopback edge, the probability edge will be reached
2373 in case header is. Estimated number of iterations of the loop can be
2374 then computed as 1 / (1 - back_edge_prob). */
2375 sreal back_edge_prob;
2376 /* True if the edge is a loopback edge in the natural loop. */
2377 unsigned int back_edge:1;
2378 } *edge_info;
2380 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2381 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2383 /* Helper function for estimate_bb_frequencies.
2384 Propagate the frequencies in blocks marked in
2385 TOVISIT, starting in HEAD. */
2387 static void
2388 propagate_freq (basic_block head, bitmap tovisit)
2390 basic_block bb;
2391 basic_block last;
2392 unsigned i;
2393 edge e;
2394 basic_block nextbb;
2395 bitmap_iterator bi;
2397 /* For each basic block we need to visit count number of his predecessors
2398 we need to visit first. */
2399 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
2401 edge_iterator ei;
2402 int count = 0;
2404 bb = BASIC_BLOCK (i);
2406 FOR_EACH_EDGE (e, ei, bb->preds)
2408 bool visit = bitmap_bit_p (tovisit, e->src->index);
2410 if (visit && !(e->flags & EDGE_DFS_BACK))
2411 count++;
2412 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
2413 fprintf (dump_file,
2414 "Irreducible region hit, ignoring edge to %i->%i\n",
2415 e->src->index, bb->index);
2417 BLOCK_INFO (bb)->npredecessors = count;
2418 /* When function never returns, we will never process exit block. */
2419 if (!count && bb == EXIT_BLOCK_PTR)
2420 bb->count = bb->frequency = 0;
2423 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
2424 last = head;
2425 for (bb = head; bb; bb = nextbb)
2427 edge_iterator ei;
2428 sreal cyclic_probability, frequency;
2430 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
2431 memcpy (&frequency, &real_zero, sizeof (real_zero));
2433 nextbb = BLOCK_INFO (bb)->next;
2434 BLOCK_INFO (bb)->next = NULL;
2436 /* Compute frequency of basic block. */
2437 if (bb != head)
2439 #ifdef ENABLE_CHECKING
2440 FOR_EACH_EDGE (e, ei, bb->preds)
2441 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
2442 || (e->flags & EDGE_DFS_BACK));
2443 #endif
2445 FOR_EACH_EDGE (e, ei, bb->preds)
2446 if (EDGE_INFO (e)->back_edge)
2448 sreal_add (&cyclic_probability, &cyclic_probability,
2449 &EDGE_INFO (e)->back_edge_prob);
2451 else if (!(e->flags & EDGE_DFS_BACK))
2453 sreal tmp;
2455 /* frequency += (e->probability
2456 * BLOCK_INFO (e->src)->frequency /
2457 REG_BR_PROB_BASE); */
2459 sreal_init (&tmp, e->probability, 0);
2460 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
2461 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
2462 sreal_add (&frequency, &frequency, &tmp);
2465 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
2467 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
2468 sizeof (frequency));
2470 else
2472 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
2474 memcpy (&cyclic_probability, &real_almost_one,
2475 sizeof (real_almost_one));
2478 /* BLOCK_INFO (bb)->frequency = frequency
2479 / (1 - cyclic_probability) */
2481 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
2482 sreal_div (&BLOCK_INFO (bb)->frequency,
2483 &frequency, &cyclic_probability);
2487 bitmap_clear_bit (tovisit, bb->index);
2489 e = find_edge (bb, head);
2490 if (e)
2492 sreal tmp;
2494 /* EDGE_INFO (e)->back_edge_prob
2495 = ((e->probability * BLOCK_INFO (bb)->frequency)
2496 / REG_BR_PROB_BASE); */
2498 sreal_init (&tmp, e->probability, 0);
2499 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
2500 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2501 &tmp, &real_inv_br_prob_base);
2504 /* Propagate to successor blocks. */
2505 FOR_EACH_EDGE (e, ei, bb->succs)
2506 if (!(e->flags & EDGE_DFS_BACK)
2507 && BLOCK_INFO (e->dest)->npredecessors)
2509 BLOCK_INFO (e->dest)->npredecessors--;
2510 if (!BLOCK_INFO (e->dest)->npredecessors)
2512 if (!nextbb)
2513 nextbb = e->dest;
2514 else
2515 BLOCK_INFO (last)->next = e->dest;
2517 last = e->dest;
2523 /* Estimate probabilities of loopback edges in loops at same nest level. */
2525 static void
2526 estimate_loops_at_level (struct loop *first_loop)
2528 struct loop *loop;
2530 for (loop = first_loop; loop; loop = loop->next)
2532 edge e;
2533 basic_block *bbs;
2534 unsigned i;
2535 bitmap tovisit = BITMAP_ALLOC (NULL);
2537 estimate_loops_at_level (loop->inner);
2539 /* Find current loop back edge and mark it. */
2540 e = loop_latch_edge (loop);
2541 EDGE_INFO (e)->back_edge = 1;
2543 bbs = get_loop_body (loop);
2544 for (i = 0; i < loop->num_nodes; i++)
2545 bitmap_set_bit (tovisit, bbs[i]->index);
2546 free (bbs);
2547 propagate_freq (loop->header, tovisit);
2548 BITMAP_FREE (tovisit);
2552 /* Propagates frequencies through structure of loops. */
2554 static void
2555 estimate_loops (void)
2557 bitmap tovisit = BITMAP_ALLOC (NULL);
2558 basic_block bb;
2560 /* Start by estimating the frequencies in the loops. */
2561 if (number_of_loops () > 1)
2562 estimate_loops_at_level (current_loops->tree_root->inner);
2564 /* Now propagate the frequencies through all the blocks. */
2565 FOR_ALL_BB (bb)
2567 bitmap_set_bit (tovisit, bb->index);
2569 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2570 BITMAP_FREE (tovisit);
2573 /* Convert counts measured by profile driven feedback to frequencies.
2574 Return nonzero iff there was any nonzero execution count. */
2577 counts_to_freqs (void)
2579 gcov_type count_max, true_count_max = 0;
2580 basic_block bb;
2582 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2583 true_count_max = MAX (bb->count, true_count_max);
2585 count_max = MAX (true_count_max, 1);
2586 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2587 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2589 return true_count_max;
2592 /* Return true if function is likely to be expensive, so there is no point to
2593 optimize performance of prologue, epilogue or do inlining at the expense
2594 of code size growth. THRESHOLD is the limit of number of instructions
2595 function can execute at average to be still considered not expensive. */
2597 bool
2598 expensive_function_p (int threshold)
2600 unsigned int sum = 0;
2601 basic_block bb;
2602 unsigned int limit;
2604 /* We can not compute accurately for large thresholds due to scaled
2605 frequencies. */
2606 gcc_assert (threshold <= BB_FREQ_MAX);
2608 /* Frequencies are out of range. This either means that function contains
2609 internal loop executing more than BB_FREQ_MAX times or profile feedback
2610 is available and function has not been executed at all. */
2611 if (ENTRY_BLOCK_PTR->frequency == 0)
2612 return true;
2614 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2615 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2616 FOR_EACH_BB (bb)
2618 rtx insn;
2620 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
2621 insn = NEXT_INSN (insn))
2622 if (active_insn_p (insn))
2624 sum += bb->frequency;
2625 if (sum > limit)
2626 return true;
2630 return false;
2633 /* Estimate basic blocks frequency by given branch probabilities. */
2635 void
2636 estimate_bb_frequencies (void)
2638 basic_block bb;
2639 sreal freq_max;
2641 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2643 static int real_values_initialized = 0;
2645 if (!real_values_initialized)
2647 real_values_initialized = 1;
2648 sreal_init (&real_zero, 0, 0);
2649 sreal_init (&real_one, 1, 0);
2650 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2651 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2652 sreal_init (&real_one_half, 1, -1);
2653 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2654 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2657 mark_dfs_back_edges ();
2659 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2661 /* Set up block info for each basic block. */
2662 alloc_aux_for_blocks (sizeof (struct block_info_def));
2663 alloc_aux_for_edges (sizeof (struct edge_info_def));
2664 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2666 edge e;
2667 edge_iterator ei;
2669 FOR_EACH_EDGE (e, ei, bb->succs)
2671 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2672 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2673 &EDGE_INFO (e)->back_edge_prob,
2674 &real_inv_br_prob_base);
2678 /* First compute probabilities locally for each loop from innermost
2679 to outermost to examine probabilities for back edges. */
2680 estimate_loops ();
2682 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2683 FOR_EACH_BB (bb)
2684 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2685 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2687 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2688 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2690 sreal tmp;
2692 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2693 sreal_add (&tmp, &tmp, &real_one_half);
2694 bb->frequency = sreal_to_int (&tmp);
2697 free_aux_for_blocks ();
2698 free_aux_for_edges ();
2700 compute_function_frequency ();
2703 /* Decide whether function is hot, cold or unlikely executed. */
2704 void
2705 compute_function_frequency (void)
2707 basic_block bb;
2708 struct cgraph_node *node = cgraph_node (current_function_decl);
2709 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2710 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
2711 node->only_called_at_startup = true;
2712 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
2713 node->only_called_at_exit = true;
2715 if (!profile_info || !flag_branch_probabilities)
2717 int flags = flags_from_decl_or_type (current_function_decl);
2718 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2719 != NULL)
2720 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2721 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2722 != NULL)
2723 node->frequency = NODE_FREQUENCY_HOT;
2724 else if (flags & ECF_NORETURN)
2725 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2726 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
2727 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2728 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2729 || DECL_STATIC_DESTRUCTOR (current_function_decl))
2730 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2731 return;
2733 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2734 FOR_EACH_BB (bb)
2736 if (maybe_hot_bb_p (bb))
2738 node->frequency = NODE_FREQUENCY_HOT;
2739 return;
2741 if (!probably_never_executed_bb_p (bb))
2742 node->frequency = NODE_FREQUENCY_NORMAL;
2746 static bool
2747 gate_estimate_probability (void)
2749 return flag_guess_branch_prob;
2752 /* Build PREDICT_EXPR. */
2753 tree
2754 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2756 tree t = build1 (PREDICT_EXPR, void_type_node,
2757 build_int_cst (NULL, predictor));
2758 SET_PREDICT_EXPR_OUTCOME (t, taken);
2759 return t;
2762 const char *
2763 predictor_name (enum br_predictor predictor)
2765 return predictor_info[predictor].name;
2768 struct gimple_opt_pass pass_profile =
2771 GIMPLE_PASS,
2772 "profile_estimate", /* name */
2773 gate_estimate_probability, /* gate */
2774 tree_estimate_probability_driver, /* execute */
2775 NULL, /* sub */
2776 NULL, /* next */
2777 0, /* static_pass_number */
2778 TV_BRANCH_PROB, /* tv_id */
2779 PROP_cfg, /* properties_required */
2780 0, /* properties_provided */
2781 0, /* properties_destroyed */
2782 0, /* todo_flags_start */
2783 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2787 struct gimple_opt_pass pass_strip_predict_hints =
2790 GIMPLE_PASS,
2791 "*strip_predict_hints", /* name */
2792 NULL, /* gate */
2793 strip_predict_hints, /* execute */
2794 NULL, /* sub */
2795 NULL, /* next */
2796 0, /* static_pass_number */
2797 TV_BRANCH_PROB, /* tv_id */
2798 PROP_cfg, /* properties_required */
2799 0, /* properties_provided */
2800 0, /* properties_destroyed */
2801 0, /* todo_flags_start */
2802 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2806 /* Rebuild function frequencies. Passes are in general expected to
2807 maintain profile by hand, however in some cases this is not possible:
2808 for example when inlining several functions with loops freuqencies might run
2809 out of scale and thus needs to be recomputed. */
2811 void
2812 rebuild_frequencies (void)
2814 timevar_push (TV_REBUILD_FREQUENCIES);
2815 if (profile_status == PROFILE_GUESSED)
2817 loop_optimizer_init (0);
2818 add_noreturn_fake_exit_edges ();
2819 mark_irreducible_loops ();
2820 connect_infinite_loops_to_exit ();
2821 estimate_bb_frequencies ();
2822 remove_fake_exit_edges ();
2823 loop_optimizer_finalize ();
2825 else if (profile_status == PROFILE_READ)
2826 counts_to_freqs ();
2827 else
2828 gcc_unreachable ();
2829 timevar_pop (TV_REBUILD_FREQUENCIES);