Remove unused variable and field
[official-gcc.git] / gcc / predict.c
blobec7933826580644cf7d67784c6e115a99d257d1b
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000-2013 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 "tm.h"
34 #include "tree.h"
35 #include "rtl.h"
36 #include "tm_p.h"
37 #include "hard-reg-set.h"
38 #include "basic-block.h"
39 #include "insn-config.h"
40 #include "regs.h"
41 #include "flags.h"
42 #include "function.h"
43 #include "except.h"
44 #include "diagnostic-core.h"
45 #include "recog.h"
46 #include "expr.h"
47 #include "predict.h"
48 #include "coverage.h"
49 #include "sreal.h"
50 #include "params.h"
51 #include "target.h"
52 #include "cfgloop.h"
53 #include "tree-flow.h"
54 #include "ggc.h"
55 #include "tree-pass.h"
56 #include "tree-scalar-evolution.h"
57 #include "cfgloop.h"
58 #include "pointer-set.h"
60 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
61 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
62 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
63 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
65 /* Random guesstimation given names.
66 PROV_VERY_UNLIKELY should be small enough so basic block predicted
67 by it gets below HOT_BB_FREQUENCY_FRACTION. */
68 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
69 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
70 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
71 #define PROB_ALWAYS (REG_BR_PROB_BASE)
73 static void combine_predictions_for_insn (rtx, basic_block);
74 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
75 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
76 static void predict_paths_leading_to_edge (edge, enum br_predictor, enum prediction);
77 static bool can_predict_insn_p (const_rtx);
79 /* Information we hold about each branch predictor.
80 Filled using information from predict.def. */
82 struct predictor_info
84 const char *const name; /* Name used in the debugging dumps. */
85 const int hitrate; /* Expected hitrate used by
86 predict_insn_def call. */
87 const int flags;
90 /* Use given predictor without Dempster-Shaffer theory if it matches
91 using first_match heuristics. */
92 #define PRED_FLAG_FIRST_MATCH 1
94 /* Recompute hitrate in percent to our representation. */
96 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
98 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
99 static const struct predictor_info predictor_info[]= {
100 #include "predict.def"
102 /* Upper bound on predictors. */
103 {NULL, 0, 0}
105 #undef DEF_PREDICTOR
107 /* Return TRUE if frequency FREQ is considered to be hot. */
109 static inline bool
110 maybe_hot_frequency_p (struct function *fun, int freq)
112 struct cgraph_node *node = cgraph_get_node (fun->decl);
113 if (!profile_info || !flag_branch_probabilities)
115 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
116 return false;
117 if (node->frequency == NODE_FREQUENCY_HOT)
118 return true;
120 if (profile_status_for_function (fun) == PROFILE_ABSENT)
121 return true;
122 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
123 && freq < (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun)->frequency * 2 / 3))
124 return false;
125 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION) == 0)
126 return false;
127 if (freq < (ENTRY_BLOCK_PTR_FOR_FUNCTION (fun)->frequency
128 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
129 return false;
130 return true;
133 static gcov_type min_count = -1;
135 /* Determine the threshold for hot BB counts. */
137 gcov_type
138 get_hot_bb_threshold ()
140 gcov_working_set_t *ws;
141 if (min_count == -1)
143 ws = find_working_set (PARAM_VALUE (HOT_BB_COUNT_WS_PERMILLE));
144 gcc_assert (ws);
145 min_count = ws->min_counter;
147 return min_count;
150 /* Set the threshold for hot BB counts. */
152 void
153 set_hot_bb_threshold (gcov_type min)
155 min_count = min;
158 /* Return TRUE if frequency FREQ is considered to be hot. */
160 static inline bool
161 maybe_hot_count_p (struct function *fun, gcov_type count)
163 if (fun && profile_status_for_function (fun) != PROFILE_READ)
164 return true;
165 /* Code executed at most once is not hot. */
166 if (profile_info->runs >= count)
167 return false;
168 return (count >= get_hot_bb_threshold ());
171 /* Return true in case BB can be CPU intensive and should be optimized
172 for maximal performance. */
174 bool
175 maybe_hot_bb_p (struct function *fun, const_basic_block bb)
177 gcc_checking_assert (fun);
178 if (profile_status_for_function (fun) == PROFILE_READ)
179 return maybe_hot_count_p (fun, bb->count);
180 return maybe_hot_frequency_p (fun, bb->frequency);
183 /* Return true if the call can be hot. */
185 bool
186 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
188 if (profile_info && flag_branch_probabilities
189 && !maybe_hot_count_p (NULL,
190 edge->count))
191 return false;
192 if (edge->caller->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED
193 || (edge->callee
194 && edge->callee->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED))
195 return false;
196 if (edge->caller->frequency > NODE_FREQUENCY_UNLIKELY_EXECUTED
197 && (edge->callee
198 && edge->callee->frequency <= NODE_FREQUENCY_EXECUTED_ONCE))
199 return false;
200 if (optimize_size)
201 return false;
202 if (edge->caller->frequency == NODE_FREQUENCY_HOT)
203 return true;
204 if (edge->caller->frequency == NODE_FREQUENCY_EXECUTED_ONCE
205 && edge->frequency < CGRAPH_FREQ_BASE * 3 / 2)
206 return false;
207 if (flag_guess_branch_prob)
209 if (PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION) == 0
210 || edge->frequency <= (CGRAPH_FREQ_BASE
211 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
212 return false;
214 return true;
217 /* Return true in case BB can be CPU intensive and should be optimized
218 for maximal performance. */
220 bool
221 maybe_hot_edge_p (edge e)
223 if (profile_status == PROFILE_READ)
224 return maybe_hot_count_p (cfun, e->count);
225 return maybe_hot_frequency_p (cfun, EDGE_FREQUENCY (e));
229 /* Return true in case BB is probably never executed. */
231 bool
232 probably_never_executed_bb_p (struct function *fun, const_basic_block bb)
234 gcc_checking_assert (fun);
235 if (profile_info && flag_branch_probabilities)
236 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
237 if ((!profile_info || !flag_branch_probabilities)
238 && (cgraph_get_node (fun->decl)->frequency
239 == NODE_FREQUENCY_UNLIKELY_EXECUTED))
240 return true;
241 return false;
244 /* Return true if NODE should be optimized for size. */
246 bool
247 cgraph_optimize_for_size_p (struct cgraph_node *node)
249 if (optimize_size)
250 return true;
251 if (node && (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED))
252 return true;
253 else
254 return false;
257 /* Return true when current function should always be optimized for size. */
259 bool
260 optimize_function_for_size_p (struct function *fun)
262 if (optimize_size)
263 return true;
264 if (!fun || !fun->decl)
265 return false;
266 return cgraph_optimize_for_size_p (cgraph_get_node (fun->decl));
269 /* Return true when current function should always be optimized for speed. */
271 bool
272 optimize_function_for_speed_p (struct function *fun)
274 return !optimize_function_for_size_p (fun);
277 /* Return TRUE when BB should be optimized for size. */
279 bool
280 optimize_bb_for_size_p (const_basic_block bb)
282 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (cfun, bb);
285 /* Return TRUE when BB should be optimized for speed. */
287 bool
288 optimize_bb_for_speed_p (const_basic_block bb)
290 return !optimize_bb_for_size_p (bb);
293 /* Return TRUE when BB should be optimized for size. */
295 bool
296 optimize_edge_for_size_p (edge e)
298 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
301 /* Return TRUE when BB should be optimized for speed. */
303 bool
304 optimize_edge_for_speed_p (edge e)
306 return !optimize_edge_for_size_p (e);
309 /* Return TRUE when BB should be optimized for size. */
311 bool
312 optimize_insn_for_size_p (void)
314 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
317 /* Return TRUE when BB should be optimized for speed. */
319 bool
320 optimize_insn_for_speed_p (void)
322 return !optimize_insn_for_size_p ();
325 /* Return TRUE when LOOP should be optimized for size. */
327 bool
328 optimize_loop_for_size_p (struct loop *loop)
330 return optimize_bb_for_size_p (loop->header);
333 /* Return TRUE when LOOP should be optimized for speed. */
335 bool
336 optimize_loop_for_speed_p (struct loop *loop)
338 return optimize_bb_for_speed_p (loop->header);
341 /* Return TRUE when LOOP nest should be optimized for speed. */
343 bool
344 optimize_loop_nest_for_speed_p (struct loop *loop)
346 struct loop *l = loop;
347 if (optimize_loop_for_speed_p (loop))
348 return true;
349 l = loop->inner;
350 while (l && l != loop)
352 if (optimize_loop_for_speed_p (l))
353 return true;
354 if (l->inner)
355 l = l->inner;
356 else if (l->next)
357 l = l->next;
358 else
360 while (l != loop && !l->next)
361 l = loop_outer (l);
362 if (l != loop)
363 l = l->next;
366 return false;
369 /* Return TRUE when LOOP nest should be optimized for size. */
371 bool
372 optimize_loop_nest_for_size_p (struct loop *loop)
374 return !optimize_loop_nest_for_speed_p (loop);
377 /* Return true when edge E is likely to be well predictable by branch
378 predictor. */
380 bool
381 predictable_edge_p (edge e)
383 if (profile_status == PROFILE_ABSENT)
384 return false;
385 if ((e->probability
386 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
387 || (REG_BR_PROB_BASE - e->probability
388 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
389 return true;
390 return false;
394 /* Set RTL expansion for BB profile. */
396 void
397 rtl_profile_for_bb (basic_block bb)
399 crtl->maybe_hot_insn_p = maybe_hot_bb_p (cfun, bb);
402 /* Set RTL expansion for edge profile. */
404 void
405 rtl_profile_for_edge (edge e)
407 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
410 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
411 void
412 default_rtl_profile (void)
414 crtl->maybe_hot_insn_p = true;
417 /* Return true if the one of outgoing edges is already predicted by
418 PREDICTOR. */
420 bool
421 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
423 rtx note;
424 if (!INSN_P (BB_END (bb)))
425 return false;
426 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
427 if (REG_NOTE_KIND (note) == REG_BR_PRED
428 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
429 return true;
430 return false;
433 /* This map contains for a basic block the list of predictions for the
434 outgoing edges. */
436 static struct pointer_map_t *bb_predictions;
438 /* Structure representing predictions in tree level. */
440 struct edge_prediction {
441 struct edge_prediction *ep_next;
442 edge ep_edge;
443 enum br_predictor ep_predictor;
444 int ep_probability;
447 /* Return true if the one of outgoing edges is already predicted by
448 PREDICTOR. */
450 bool
451 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
453 struct edge_prediction *i;
454 void **preds = pointer_map_contains (bb_predictions, bb);
456 if (!preds)
457 return false;
459 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
460 if (i->ep_predictor == predictor)
461 return true;
462 return false;
465 /* Return true when the probability of edge is reliable.
467 The profile guessing code is good at predicting branch outcome (ie.
468 taken/not taken), that is predicted right slightly over 75% of time.
469 It is however notoriously poor on predicting the probability itself.
470 In general the profile appear a lot flatter (with probabilities closer
471 to 50%) than the reality so it is bad idea to use it to drive optimization
472 such as those disabling dynamic branch prediction for well predictable
473 branches.
475 There are two exceptions - edges leading to noreturn edges and edges
476 predicted by number of iterations heuristics are predicted well. This macro
477 should be able to distinguish those, but at the moment it simply check for
478 noreturn heuristic that is only one giving probability over 99% or bellow
479 1%. In future we might want to propagate reliability information across the
480 CFG if we find this information useful on multiple places. */
481 static bool
482 probability_reliable_p (int prob)
484 return (profile_status == PROFILE_READ
485 || (profile_status == PROFILE_GUESSED
486 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
489 /* Same predicate as above, working on edges. */
490 bool
491 edge_probability_reliable_p (const_edge e)
493 return probability_reliable_p (e->probability);
496 /* Same predicate as edge_probability_reliable_p, working on notes. */
497 bool
498 br_prob_note_reliable_p (const_rtx note)
500 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
501 return probability_reliable_p (INTVAL (XEXP (note, 0)));
504 static void
505 predict_insn (rtx insn, enum br_predictor predictor, int probability)
507 gcc_assert (any_condjump_p (insn));
508 if (!flag_guess_branch_prob)
509 return;
511 add_reg_note (insn, REG_BR_PRED,
512 gen_rtx_CONCAT (VOIDmode,
513 GEN_INT ((int) predictor),
514 GEN_INT ((int) probability)));
517 /* Predict insn by given predictor. */
519 void
520 predict_insn_def (rtx insn, enum br_predictor predictor,
521 enum prediction taken)
523 int probability = predictor_info[(int) predictor].hitrate;
525 if (taken != TAKEN)
526 probability = REG_BR_PROB_BASE - probability;
528 predict_insn (insn, predictor, probability);
531 /* Predict edge E with given probability if possible. */
533 void
534 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
536 rtx last_insn;
537 last_insn = BB_END (e->src);
539 /* We can store the branch prediction information only about
540 conditional jumps. */
541 if (!any_condjump_p (last_insn))
542 return;
544 /* We always store probability of branching. */
545 if (e->flags & EDGE_FALLTHRU)
546 probability = REG_BR_PROB_BASE - probability;
548 predict_insn (last_insn, predictor, probability);
551 /* Predict edge E with the given PROBABILITY. */
552 void
553 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
555 gcc_assert (profile_status != PROFILE_GUESSED);
556 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
557 && flag_guess_branch_prob && optimize)
559 struct edge_prediction *i = XNEW (struct edge_prediction);
560 void **preds = pointer_map_insert (bb_predictions, e->src);
562 i->ep_next = (struct edge_prediction *) *preds;
563 *preds = i;
564 i->ep_probability = probability;
565 i->ep_predictor = predictor;
566 i->ep_edge = e;
570 /* Remove all predictions on given basic block that are attached
571 to edge E. */
572 void
573 remove_predictions_associated_with_edge (edge e)
575 void **preds;
577 if (!bb_predictions)
578 return;
580 preds = pointer_map_contains (bb_predictions, e->src);
582 if (preds)
584 struct edge_prediction **prediction = (struct edge_prediction **) preds;
585 struct edge_prediction *next;
587 while (*prediction)
589 if ((*prediction)->ep_edge == e)
591 next = (*prediction)->ep_next;
592 free (*prediction);
593 *prediction = next;
595 else
596 prediction = &((*prediction)->ep_next);
601 /* Clears the list of predictions stored for BB. */
603 static void
604 clear_bb_predictions (basic_block bb)
606 void **preds = pointer_map_contains (bb_predictions, bb);
607 struct edge_prediction *pred, *next;
609 if (!preds)
610 return;
612 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
614 next = pred->ep_next;
615 free (pred);
617 *preds = NULL;
620 /* Return true when we can store prediction on insn INSN.
621 At the moment we represent predictions only on conditional
622 jumps, not at computed jump or other complicated cases. */
623 static bool
624 can_predict_insn_p (const_rtx insn)
626 return (JUMP_P (insn)
627 && any_condjump_p (insn)
628 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
631 /* Predict edge E by given predictor if possible. */
633 void
634 predict_edge_def (edge e, enum br_predictor predictor,
635 enum prediction taken)
637 int probability = predictor_info[(int) predictor].hitrate;
639 if (taken != TAKEN)
640 probability = REG_BR_PROB_BASE - probability;
642 predict_edge (e, predictor, probability);
645 /* Invert all branch predictions or probability notes in the INSN. This needs
646 to be done each time we invert the condition used by the jump. */
648 void
649 invert_br_probabilities (rtx insn)
651 rtx note;
653 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
654 if (REG_NOTE_KIND (note) == REG_BR_PROB)
655 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
656 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
657 XEXP (XEXP (note, 0), 1)
658 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
661 /* Dump information about the branch prediction to the output file. */
663 static void
664 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
665 basic_block bb, int used)
667 edge e;
668 edge_iterator ei;
670 if (!file)
671 return;
673 FOR_EACH_EDGE (e, ei, bb->succs)
674 if (! (e->flags & EDGE_FALLTHRU))
675 break;
677 fprintf (file, " %s heuristics%s: %.1f%%",
678 predictor_info[predictor].name,
679 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
681 if (bb->count)
683 fprintf (file, " exec ");
684 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
685 if (e)
687 fprintf (file, " hit ");
688 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
689 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
693 fprintf (file, "\n");
696 /* We can not predict the probabilities of outgoing edges of bb. Set them
697 evenly and hope for the best. */
698 static void
699 set_even_probabilities (basic_block bb)
701 int nedges = 0;
702 edge e;
703 edge_iterator ei;
705 FOR_EACH_EDGE (e, ei, bb->succs)
706 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
707 nedges ++;
708 FOR_EACH_EDGE (e, ei, bb->succs)
709 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
710 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
711 else
712 e->probability = 0;
715 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
716 note if not already present. Remove now useless REG_BR_PRED notes. */
718 static void
719 combine_predictions_for_insn (rtx insn, basic_block bb)
721 rtx prob_note;
722 rtx *pnote;
723 rtx note;
724 int best_probability = PROB_EVEN;
725 enum br_predictor best_predictor = END_PREDICTORS;
726 int combined_probability = REG_BR_PROB_BASE / 2;
727 int d;
728 bool first_match = false;
729 bool found = false;
731 if (!can_predict_insn_p (insn))
733 set_even_probabilities (bb);
734 return;
737 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
738 pnote = &REG_NOTES (insn);
739 if (dump_file)
740 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
741 bb->index);
743 /* We implement "first match" heuristics and use probability guessed
744 by predictor with smallest index. */
745 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
746 if (REG_NOTE_KIND (note) == REG_BR_PRED)
748 enum br_predictor predictor = ((enum br_predictor)
749 INTVAL (XEXP (XEXP (note, 0), 0)));
750 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
752 found = true;
753 if (best_predictor > predictor)
754 best_probability = probability, best_predictor = predictor;
756 d = (combined_probability * probability
757 + (REG_BR_PROB_BASE - combined_probability)
758 * (REG_BR_PROB_BASE - probability));
760 /* Use FP math to avoid overflows of 32bit integers. */
761 if (d == 0)
762 /* If one probability is 0% and one 100%, avoid division by zero. */
763 combined_probability = REG_BR_PROB_BASE / 2;
764 else
765 combined_probability = (((double) combined_probability) * probability
766 * REG_BR_PROB_BASE / d + 0.5);
769 /* Decide which heuristic to use. In case we didn't match anything,
770 use no_prediction heuristic, in case we did match, use either
771 first match or Dempster-Shaffer theory depending on the flags. */
773 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
774 first_match = true;
776 if (!found)
777 dump_prediction (dump_file, PRED_NO_PREDICTION,
778 combined_probability, bb, true);
779 else
781 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
782 bb, !first_match);
783 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
784 bb, first_match);
787 if (first_match)
788 combined_probability = best_probability;
789 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
791 while (*pnote)
793 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
795 enum br_predictor predictor = ((enum br_predictor)
796 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
797 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
799 dump_prediction (dump_file, predictor, probability, bb,
800 !first_match || best_predictor == predictor);
801 *pnote = XEXP (*pnote, 1);
803 else
804 pnote = &XEXP (*pnote, 1);
807 if (!prob_note)
809 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
811 /* Save the prediction into CFG in case we are seeing non-degenerated
812 conditional jump. */
813 if (!single_succ_p (bb))
815 BRANCH_EDGE (bb)->probability = combined_probability;
816 FALLTHRU_EDGE (bb)->probability
817 = REG_BR_PROB_BASE - combined_probability;
820 else if (!single_succ_p (bb))
822 int prob = INTVAL (XEXP (prob_note, 0));
824 BRANCH_EDGE (bb)->probability = prob;
825 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
827 else
828 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
831 /* Combine predictions into single probability and store them into CFG.
832 Remove now useless prediction entries. */
834 static void
835 combine_predictions_for_bb (basic_block bb)
837 int best_probability = PROB_EVEN;
838 enum br_predictor best_predictor = END_PREDICTORS;
839 int combined_probability = REG_BR_PROB_BASE / 2;
840 int d;
841 bool first_match = false;
842 bool found = false;
843 struct edge_prediction *pred;
844 int nedges = 0;
845 edge e, first = NULL, second = NULL;
846 edge_iterator ei;
847 void **preds;
849 FOR_EACH_EDGE (e, ei, bb->succs)
850 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
852 nedges ++;
853 if (first && !second)
854 second = e;
855 if (!first)
856 first = e;
859 /* When there is no successor or only one choice, prediction is easy.
861 We are lazy for now and predict only basic blocks with two outgoing
862 edges. It is possible to predict generic case too, but we have to
863 ignore first match heuristics and do more involved combining. Implement
864 this later. */
865 if (nedges != 2)
867 if (!bb->count)
868 set_even_probabilities (bb);
869 clear_bb_predictions (bb);
870 if (dump_file)
871 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
872 nedges, bb->index);
873 return;
876 if (dump_file)
877 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
879 preds = pointer_map_contains (bb_predictions, bb);
880 if (preds)
882 /* We implement "first match" heuristics and use probability guessed
883 by predictor with smallest index. */
884 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
886 enum br_predictor predictor = pred->ep_predictor;
887 int probability = pred->ep_probability;
889 if (pred->ep_edge != first)
890 probability = REG_BR_PROB_BASE - probability;
892 found = true;
893 /* First match heuristics would be widly confused if we predicted
894 both directions. */
895 if (best_predictor > predictor)
897 struct edge_prediction *pred2;
898 int prob = probability;
900 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
901 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
903 int probability2 = pred->ep_probability;
905 if (pred2->ep_edge != first)
906 probability2 = REG_BR_PROB_BASE - probability2;
908 if ((probability < REG_BR_PROB_BASE / 2) !=
909 (probability2 < REG_BR_PROB_BASE / 2))
910 break;
912 /* If the same predictor later gave better result, go for it! */
913 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
914 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
915 prob = probability2;
917 if (!pred2)
918 best_probability = prob, best_predictor = predictor;
921 d = (combined_probability * probability
922 + (REG_BR_PROB_BASE - combined_probability)
923 * (REG_BR_PROB_BASE - probability));
925 /* Use FP math to avoid overflows of 32bit integers. */
926 if (d == 0)
927 /* If one probability is 0% and one 100%, avoid division by zero. */
928 combined_probability = REG_BR_PROB_BASE / 2;
929 else
930 combined_probability = (((double) combined_probability)
931 * probability
932 * REG_BR_PROB_BASE / d + 0.5);
936 /* Decide which heuristic to use. In case we didn't match anything,
937 use no_prediction heuristic, in case we did match, use either
938 first match or Dempster-Shaffer theory depending on the flags. */
940 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
941 first_match = true;
943 if (!found)
944 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
945 else
947 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
948 !first_match);
949 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
950 first_match);
953 if (first_match)
954 combined_probability = best_probability;
955 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
957 if (preds)
959 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
961 enum br_predictor predictor = pred->ep_predictor;
962 int probability = pred->ep_probability;
964 if (pred->ep_edge != EDGE_SUCC (bb, 0))
965 probability = REG_BR_PROB_BASE - probability;
966 dump_prediction (dump_file, predictor, probability, bb,
967 !first_match || best_predictor == predictor);
970 clear_bb_predictions (bb);
972 if (!bb->count)
974 first->probability = combined_probability;
975 second->probability = REG_BR_PROB_BASE - combined_probability;
979 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
980 Return the SSA_NAME if the condition satisfies, NULL otherwise.
982 T1 and T2 should be one of the following cases:
983 1. T1 is SSA_NAME, T2 is NULL
984 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
985 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
987 static tree
988 strips_small_constant (tree t1, tree t2)
990 tree ret = NULL;
991 int value = 0;
993 if (!t1)
994 return NULL;
995 else if (TREE_CODE (t1) == SSA_NAME)
996 ret = t1;
997 else if (host_integerp (t1, 0))
998 value = tree_low_cst (t1, 0);
999 else
1000 return NULL;
1002 if (!t2)
1003 return ret;
1004 else if (host_integerp (t2, 0))
1005 value = tree_low_cst (t2, 0);
1006 else if (TREE_CODE (t2) == SSA_NAME)
1008 if (ret)
1009 return NULL;
1010 else
1011 ret = t2;
1014 if (value <= 4 && value >= -4)
1015 return ret;
1016 else
1017 return NULL;
1020 /* Return the SSA_NAME in T or T's operands.
1021 Return NULL if SSA_NAME cannot be found. */
1023 static tree
1024 get_base_value (tree t)
1026 if (TREE_CODE (t) == SSA_NAME)
1027 return t;
1029 if (!BINARY_CLASS_P (t))
1030 return NULL;
1032 switch (TREE_OPERAND_LENGTH (t))
1034 case 1:
1035 return strips_small_constant (TREE_OPERAND (t, 0), NULL);
1036 case 2:
1037 return strips_small_constant (TREE_OPERAND (t, 0),
1038 TREE_OPERAND (t, 1));
1039 default:
1040 return NULL;
1044 /* Check the compare STMT in LOOP. If it compares an induction
1045 variable to a loop invariant, return true, and save
1046 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1047 Otherwise return false and set LOOP_INVAIANT to NULL. */
1049 static bool
1050 is_comparison_with_loop_invariant_p (gimple stmt, struct loop *loop,
1051 tree *loop_invariant,
1052 enum tree_code *compare_code,
1053 tree *loop_step,
1054 tree *loop_iv_base)
1056 tree op0, op1, bound, base;
1057 affine_iv iv0, iv1;
1058 enum tree_code code;
1059 tree step;
1061 code = gimple_cond_code (stmt);
1062 *loop_invariant = NULL;
1064 switch (code)
1066 case GT_EXPR:
1067 case GE_EXPR:
1068 case NE_EXPR:
1069 case LT_EXPR:
1070 case LE_EXPR:
1071 case EQ_EXPR:
1072 break;
1074 default:
1075 return false;
1078 op0 = gimple_cond_lhs (stmt);
1079 op1 = gimple_cond_rhs (stmt);
1081 if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1082 || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1083 return false;
1084 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1085 return false;
1086 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1087 return false;
1088 if (TREE_CODE (iv0.step) != INTEGER_CST
1089 || TREE_CODE (iv1.step) != INTEGER_CST)
1090 return false;
1091 if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1092 || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1093 return false;
1095 if (integer_zerop (iv0.step))
1097 if (code != NE_EXPR && code != EQ_EXPR)
1098 code = invert_tree_comparison (code, false);
1099 bound = iv0.base;
1100 base = iv1.base;
1101 if (host_integerp (iv1.step, 0))
1102 step = iv1.step;
1103 else
1104 return false;
1106 else
1108 bound = iv1.base;
1109 base = iv0.base;
1110 if (host_integerp (iv0.step, 0))
1111 step = iv0.step;
1112 else
1113 return false;
1116 if (TREE_CODE (bound) != INTEGER_CST)
1117 bound = get_base_value (bound);
1118 if (!bound)
1119 return false;
1120 if (TREE_CODE (base) != INTEGER_CST)
1121 base = get_base_value (base);
1122 if (!base)
1123 return false;
1125 *loop_invariant = bound;
1126 *compare_code = code;
1127 *loop_step = step;
1128 *loop_iv_base = base;
1129 return true;
1132 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1134 static bool
1135 expr_coherent_p (tree t1, tree t2)
1137 gimple stmt;
1138 tree ssa_name_1 = NULL;
1139 tree ssa_name_2 = NULL;
1141 gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1142 gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1144 if (t1 == t2)
1145 return true;
1147 if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1148 return true;
1149 if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1150 return false;
1152 /* Check to see if t1 is expressed/defined with t2. */
1153 stmt = SSA_NAME_DEF_STMT (t1);
1154 gcc_assert (stmt != NULL);
1155 if (is_gimple_assign (stmt))
1157 ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1158 if (ssa_name_1 && ssa_name_1 == t2)
1159 return true;
1162 /* Check to see if t2 is expressed/defined with t1. */
1163 stmt = SSA_NAME_DEF_STMT (t2);
1164 gcc_assert (stmt != NULL);
1165 if (is_gimple_assign (stmt))
1167 ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1168 if (ssa_name_2 && ssa_name_2 == t1)
1169 return true;
1172 /* Compare if t1 and t2's def_stmts are identical. */
1173 if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1174 return true;
1175 else
1176 return false;
1179 /* Predict branch probability of BB when BB contains a branch that compares
1180 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1181 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1183 E.g.
1184 for (int i = 0; i < bound; i++) {
1185 if (i < bound - 2)
1186 computation_1();
1187 else
1188 computation_2();
1191 In this loop, we will predict the branch inside the loop to be taken. */
1193 static void
1194 predict_iv_comparison (struct loop *loop, basic_block bb,
1195 tree loop_bound_var,
1196 tree loop_iv_base_var,
1197 enum tree_code loop_bound_code,
1198 int loop_bound_step)
1200 gimple stmt;
1201 tree compare_var, compare_base;
1202 enum tree_code compare_code;
1203 tree compare_step_var;
1204 edge then_edge;
1205 edge_iterator ei;
1207 if (predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1208 || predicted_by_p (bb, PRED_LOOP_ITERATIONS)
1209 || predicted_by_p (bb, PRED_LOOP_EXIT))
1210 return;
1212 stmt = last_stmt (bb);
1213 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1214 return;
1215 if (!is_comparison_with_loop_invariant_p (stmt, loop, &compare_var,
1216 &compare_code,
1217 &compare_step_var,
1218 &compare_base))
1219 return;
1221 /* Find the taken edge. */
1222 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1223 if (then_edge->flags & EDGE_TRUE_VALUE)
1224 break;
1226 /* When comparing an IV to a loop invariant, NE is more likely to be
1227 taken while EQ is more likely to be not-taken. */
1228 if (compare_code == NE_EXPR)
1230 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1231 return;
1233 else if (compare_code == EQ_EXPR)
1235 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1236 return;
1239 if (!expr_coherent_p (loop_iv_base_var, compare_base))
1240 return;
1242 /* If loop bound, base and compare bound are all constants, we can
1243 calculate the probability directly. */
1244 if (host_integerp (loop_bound_var, 0)
1245 && host_integerp (compare_var, 0)
1246 && host_integerp (compare_base, 0))
1248 int probability;
1249 bool of, overflow = false;
1250 double_int mod, compare_count, tem, loop_count;
1252 double_int loop_bound = tree_to_double_int (loop_bound_var);
1253 double_int compare_bound = tree_to_double_int (compare_var);
1254 double_int base = tree_to_double_int (compare_base);
1255 double_int compare_step = tree_to_double_int (compare_step_var);
1257 /* (loop_bound - base) / compare_step */
1258 tem = loop_bound.sub_with_overflow (base, &of);
1259 overflow |= of;
1260 loop_count = tem.divmod_with_overflow (compare_step,
1261 0, TRUNC_DIV_EXPR,
1262 &mod, &of);
1263 overflow |= of;
1265 if ((!compare_step.is_negative ())
1266 ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1268 /* (loop_bound - compare_bound) / compare_step */
1269 tem = loop_bound.sub_with_overflow (compare_bound, &of);
1270 overflow |= of;
1271 compare_count = tem.divmod_with_overflow (compare_step,
1272 0, TRUNC_DIV_EXPR,
1273 &mod, &of);
1274 overflow |= of;
1276 else
1278 /* (compare_bound - base) / compare_step */
1279 tem = compare_bound.sub_with_overflow (base, &of);
1280 overflow |= of;
1281 compare_count = tem.divmod_with_overflow (compare_step,
1282 0, TRUNC_DIV_EXPR,
1283 &mod, &of);
1284 overflow |= of;
1286 if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1287 ++compare_count;
1288 if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1289 ++loop_count;
1290 if (compare_count.is_negative ())
1291 compare_count = double_int_zero;
1292 if (loop_count.is_negative ())
1293 loop_count = double_int_zero;
1294 if (loop_count.is_zero ())
1295 probability = 0;
1296 else if (compare_count.scmp (loop_count) == 1)
1297 probability = REG_BR_PROB_BASE;
1298 else
1300 /* If loop_count is too big, such that REG_BR_PROB_BASE * loop_count
1301 could overflow, shift both loop_count and compare_count right
1302 a bit so that it doesn't overflow. Note both counts are known not
1303 to be negative at this point. */
1304 int clz_bits = clz_hwi (loop_count.high);
1305 gcc_assert (REG_BR_PROB_BASE < 32768);
1306 if (clz_bits < 16)
1308 loop_count.arshift (16 - clz_bits, HOST_BITS_PER_DOUBLE_INT);
1309 compare_count.arshift (16 - clz_bits, HOST_BITS_PER_DOUBLE_INT);
1311 tem = compare_count.mul_with_sign (double_int::from_shwi
1312 (REG_BR_PROB_BASE), true, &of);
1313 gcc_assert (!of);
1314 tem = tem.divmod (loop_count, true, TRUNC_DIV_EXPR, &mod);
1315 probability = tem.to_uhwi ();
1318 if (!overflow)
1319 predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1321 return;
1324 if (expr_coherent_p (loop_bound_var, compare_var))
1326 if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1327 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1328 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1329 else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1330 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1331 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1332 else if (loop_bound_code == NE_EXPR)
1334 /* If the loop backedge condition is "(i != bound)", we do
1335 the comparison based on the step of IV:
1336 * step < 0 : backedge condition is like (i > bound)
1337 * step > 0 : backedge condition is like (i < bound) */
1338 gcc_assert (loop_bound_step != 0);
1339 if (loop_bound_step > 0
1340 && (compare_code == LT_EXPR
1341 || compare_code == LE_EXPR))
1342 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1343 else if (loop_bound_step < 0
1344 && (compare_code == GT_EXPR
1345 || compare_code == GE_EXPR))
1346 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1347 else
1348 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1350 else
1351 /* The branch is predicted not-taken if loop_bound_code is
1352 opposite with compare_code. */
1353 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1355 else if (expr_coherent_p (loop_iv_base_var, compare_var))
1357 /* For cases like:
1358 for (i = s; i < h; i++)
1359 if (i > s + 2) ....
1360 The branch should be predicted taken. */
1361 if (loop_bound_step > 0
1362 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1363 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1364 else if (loop_bound_step < 0
1365 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1366 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1367 else
1368 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1372 /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1373 exits are resulted from short-circuit conditions that will generate an
1374 if_tmp. E.g.:
1376 if (foo() || global > 10)
1377 break;
1379 This will be translated into:
1381 BB3:
1382 loop header...
1383 BB4:
1384 if foo() goto BB6 else goto BB5
1385 BB5:
1386 if global > 10 goto BB6 else goto BB7
1387 BB6:
1388 goto BB7
1389 BB7:
1390 iftmp = (PHI 0(BB5), 1(BB6))
1391 if iftmp == 1 goto BB8 else goto BB3
1392 BB8:
1393 outside of the loop...
1395 The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1396 From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1397 exits. This function takes BB7->BB8 as input, and finds out the extra loop
1398 exits to predict them using PRED_LOOP_EXIT. */
1400 static void
1401 predict_extra_loop_exits (edge exit_edge)
1403 unsigned i;
1404 bool check_value_one;
1405 gimple phi_stmt;
1406 tree cmp_rhs, cmp_lhs;
1407 gimple cmp_stmt = last_stmt (exit_edge->src);
1409 if (!cmp_stmt || gimple_code (cmp_stmt) != GIMPLE_COND)
1410 return;
1411 cmp_rhs = gimple_cond_rhs (cmp_stmt);
1412 cmp_lhs = gimple_cond_lhs (cmp_stmt);
1413 if (!TREE_CONSTANT (cmp_rhs)
1414 || !(integer_zerop (cmp_rhs) || integer_onep (cmp_rhs)))
1415 return;
1416 if (TREE_CODE (cmp_lhs) != SSA_NAME)
1417 return;
1419 /* If check_value_one is true, only the phi_args with value '1' will lead
1420 to loop exit. Otherwise, only the phi_args with value '0' will lead to
1421 loop exit. */
1422 check_value_one = (((integer_onep (cmp_rhs))
1423 ^ (gimple_cond_code (cmp_stmt) == EQ_EXPR))
1424 ^ ((exit_edge->flags & EDGE_TRUE_VALUE) != 0));
1426 phi_stmt = SSA_NAME_DEF_STMT (cmp_lhs);
1427 if (!phi_stmt || gimple_code (phi_stmt) != GIMPLE_PHI)
1428 return;
1430 for (i = 0; i < gimple_phi_num_args (phi_stmt); i++)
1432 edge e1;
1433 edge_iterator ei;
1434 tree val = gimple_phi_arg_def (phi_stmt, i);
1435 edge e = gimple_phi_arg_edge (phi_stmt, i);
1437 if (!TREE_CONSTANT (val) || !(integer_zerop (val) || integer_onep (val)))
1438 continue;
1439 if ((check_value_one ^ integer_onep (val)) == 1)
1440 continue;
1441 if (EDGE_COUNT (e->src->succs) != 1)
1443 predict_paths_leading_to_edge (e, PRED_LOOP_EXIT, NOT_TAKEN);
1444 continue;
1447 FOR_EACH_EDGE (e1, ei, e->src->preds)
1448 predict_paths_leading_to_edge (e1, PRED_LOOP_EXIT, NOT_TAKEN);
1452 /* Predict edge probabilities by exploiting loop structure. */
1454 static void
1455 predict_loops (void)
1457 loop_iterator li;
1458 struct loop *loop;
1460 /* Try to predict out blocks in a loop that are not part of a
1461 natural loop. */
1462 FOR_EACH_LOOP (li, loop, 0)
1464 basic_block bb, *bbs;
1465 unsigned j, n_exits;
1466 vec<edge> exits;
1467 struct tree_niter_desc niter_desc;
1468 edge ex;
1469 struct nb_iter_bound *nb_iter;
1470 enum tree_code loop_bound_code = ERROR_MARK;
1471 tree loop_bound_step = NULL;
1472 tree loop_bound_var = NULL;
1473 tree loop_iv_base = NULL;
1474 gimple stmt = NULL;
1476 exits = get_loop_exit_edges (loop);
1477 n_exits = exits.length ();
1478 if (!n_exits)
1480 exits.release ();
1481 continue;
1484 FOR_EACH_VEC_ELT (exits, j, ex)
1486 tree niter = NULL;
1487 HOST_WIDE_INT nitercst;
1488 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
1489 int probability;
1490 enum br_predictor predictor;
1492 predict_extra_loop_exits (ex);
1494 if (number_of_iterations_exit (loop, ex, &niter_desc, false, false))
1495 niter = niter_desc.niter;
1496 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
1497 niter = loop_niter_by_eval (loop, ex);
1499 if (TREE_CODE (niter) == INTEGER_CST)
1501 if (host_integerp (niter, 1)
1502 && max
1503 && compare_tree_int (niter, max - 1) == -1)
1504 nitercst = tree_low_cst (niter, 1) + 1;
1505 else
1506 nitercst = max;
1507 predictor = PRED_LOOP_ITERATIONS;
1509 /* If we have just one exit and we can derive some information about
1510 the number of iterations of the loop from the statements inside
1511 the loop, use it to predict this exit. */
1512 else if (n_exits == 1)
1514 nitercst = estimated_stmt_executions_int (loop);
1515 if (nitercst < 0)
1516 continue;
1517 if (nitercst > max)
1518 nitercst = max;
1520 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1522 else
1523 continue;
1525 /* If the prediction for number of iterations is zero, do not
1526 predict the exit edges. */
1527 if (nitercst == 0)
1528 continue;
1530 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
1531 predict_edge (ex, predictor, probability);
1533 exits.release ();
1535 /* Find information about loop bound variables. */
1536 for (nb_iter = loop->bounds; nb_iter;
1537 nb_iter = nb_iter->next)
1538 if (nb_iter->stmt
1539 && gimple_code (nb_iter->stmt) == GIMPLE_COND)
1541 stmt = nb_iter->stmt;
1542 break;
1544 if (!stmt && last_stmt (loop->header)
1545 && gimple_code (last_stmt (loop->header)) == GIMPLE_COND)
1546 stmt = last_stmt (loop->header);
1547 if (stmt)
1548 is_comparison_with_loop_invariant_p (stmt, loop,
1549 &loop_bound_var,
1550 &loop_bound_code,
1551 &loop_bound_step,
1552 &loop_iv_base);
1554 bbs = get_loop_body (loop);
1556 for (j = 0; j < loop->num_nodes; j++)
1558 int header_found = 0;
1559 edge e;
1560 edge_iterator ei;
1562 bb = bbs[j];
1564 /* Bypass loop heuristics on continue statement. These
1565 statements construct loops via "non-loop" constructs
1566 in the source language and are better to be handled
1567 separately. */
1568 if (predicted_by_p (bb, PRED_CONTINUE))
1569 continue;
1571 /* Loop branch heuristics - predict an edge back to a
1572 loop's head as taken. */
1573 if (bb == loop->latch)
1575 e = find_edge (loop->latch, loop->header);
1576 if (e)
1578 header_found = 1;
1579 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1583 /* Loop exit heuristics - predict an edge exiting the loop if the
1584 conditional has no loop header successors as not taken. */
1585 if (!header_found
1586 /* If we already used more reliable loop exit predictors, do not
1587 bother with PRED_LOOP_EXIT. */
1588 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1589 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1591 /* For loop with many exits we don't want to predict all exits
1592 with the pretty large probability, because if all exits are
1593 considered in row, the loop would be predicted to iterate
1594 almost never. The code to divide probability by number of
1595 exits is very rough. It should compute the number of exits
1596 taken in each patch through function (not the overall number
1597 of exits that might be a lot higher for loops with wide switch
1598 statements in them) and compute n-th square root.
1600 We limit the minimal probability by 2% to avoid
1601 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1602 as this was causing regression in perl benchmark containing such
1603 a wide loop. */
1605 int probability = ((REG_BR_PROB_BASE
1606 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1607 / n_exits);
1608 if (probability < HITRATE (2))
1609 probability = HITRATE (2);
1610 FOR_EACH_EDGE (e, ei, bb->succs)
1611 if (e->dest->index < NUM_FIXED_BLOCKS
1612 || !flow_bb_inside_loop_p (loop, e->dest))
1613 predict_edge (e, PRED_LOOP_EXIT, probability);
1615 if (loop_bound_var)
1616 predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
1617 loop_bound_code,
1618 tree_low_cst (loop_bound_step, 0));
1621 /* Free basic blocks from get_loop_body. */
1622 free (bbs);
1626 /* Attempt to predict probabilities of BB outgoing edges using local
1627 properties. */
1628 static void
1629 bb_estimate_probability_locally (basic_block bb)
1631 rtx last_insn = BB_END (bb);
1632 rtx cond;
1634 if (! can_predict_insn_p (last_insn))
1635 return;
1636 cond = get_condition (last_insn, NULL, false, false);
1637 if (! cond)
1638 return;
1640 /* Try "pointer heuristic."
1641 A comparison ptr == 0 is predicted as false.
1642 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1643 if (COMPARISON_P (cond)
1644 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1645 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1647 if (GET_CODE (cond) == EQ)
1648 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1649 else if (GET_CODE (cond) == NE)
1650 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1652 else
1654 /* Try "opcode heuristic."
1655 EQ tests are usually false and NE tests are usually true. Also,
1656 most quantities are positive, so we can make the appropriate guesses
1657 about signed comparisons against zero. */
1658 switch (GET_CODE (cond))
1660 case CONST_INT:
1661 /* Unconditional branch. */
1662 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1663 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1664 break;
1666 case EQ:
1667 case UNEQ:
1668 /* Floating point comparisons appears to behave in a very
1669 unpredictable way because of special role of = tests in
1670 FP code. */
1671 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1673 /* Comparisons with 0 are often used for booleans and there is
1674 nothing useful to predict about them. */
1675 else if (XEXP (cond, 1) == const0_rtx
1676 || XEXP (cond, 0) == const0_rtx)
1678 else
1679 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1680 break;
1682 case NE:
1683 case LTGT:
1684 /* Floating point comparisons appears to behave in a very
1685 unpredictable way because of special role of = tests in
1686 FP code. */
1687 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1689 /* Comparisons with 0 are often used for booleans and there is
1690 nothing useful to predict about them. */
1691 else if (XEXP (cond, 1) == const0_rtx
1692 || XEXP (cond, 0) == const0_rtx)
1694 else
1695 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1696 break;
1698 case ORDERED:
1699 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1700 break;
1702 case UNORDERED:
1703 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1704 break;
1706 case LE:
1707 case LT:
1708 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1709 || XEXP (cond, 1) == constm1_rtx)
1710 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1711 break;
1713 case GE:
1714 case GT:
1715 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1716 || XEXP (cond, 1) == constm1_rtx)
1717 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1718 break;
1720 default:
1721 break;
1725 /* Set edge->probability for each successor edge of BB. */
1726 void
1727 guess_outgoing_edge_probabilities (basic_block bb)
1729 bb_estimate_probability_locally (bb);
1730 combine_predictions_for_insn (BB_END (bb), bb);
1733 static tree expr_expected_value (tree, bitmap);
1735 /* Helper function for expr_expected_value. */
1737 static tree
1738 expr_expected_value_1 (tree type, tree op0, enum tree_code code,
1739 tree op1, bitmap visited)
1741 gimple def;
1743 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1745 if (TREE_CONSTANT (op0))
1746 return op0;
1748 if (code != SSA_NAME)
1749 return NULL_TREE;
1751 def = SSA_NAME_DEF_STMT (op0);
1753 /* If we were already here, break the infinite cycle. */
1754 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
1755 return NULL;
1757 if (gimple_code (def) == GIMPLE_PHI)
1759 /* All the arguments of the PHI node must have the same constant
1760 length. */
1761 int i, n = gimple_phi_num_args (def);
1762 tree val = NULL, new_val;
1764 for (i = 0; i < n; i++)
1766 tree arg = PHI_ARG_DEF (def, i);
1768 /* If this PHI has itself as an argument, we cannot
1769 determine the string length of this argument. However,
1770 if we can find an expected constant value for the other
1771 PHI args then we can still be sure that this is
1772 likely a constant. So be optimistic and just
1773 continue with the next argument. */
1774 if (arg == PHI_RESULT (def))
1775 continue;
1777 new_val = expr_expected_value (arg, visited);
1778 if (!new_val)
1779 return NULL;
1780 if (!val)
1781 val = new_val;
1782 else if (!operand_equal_p (val, new_val, false))
1783 return NULL;
1785 return val;
1787 if (is_gimple_assign (def))
1789 if (gimple_assign_lhs (def) != op0)
1790 return NULL;
1792 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1793 gimple_assign_rhs1 (def),
1794 gimple_assign_rhs_code (def),
1795 gimple_assign_rhs2 (def),
1796 visited);
1799 if (is_gimple_call (def))
1801 tree decl = gimple_call_fndecl (def);
1802 if (!decl)
1803 return NULL;
1804 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
1805 switch (DECL_FUNCTION_CODE (decl))
1807 case BUILT_IN_EXPECT:
1809 tree val;
1810 if (gimple_call_num_args (def) != 2)
1811 return NULL;
1812 val = gimple_call_arg (def, 0);
1813 if (TREE_CONSTANT (val))
1814 return val;
1815 return gimple_call_arg (def, 1);
1818 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
1819 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
1820 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
1821 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
1822 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
1823 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
1824 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
1825 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
1826 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
1827 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
1828 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
1829 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
1830 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
1831 /* Assume that any given atomic operation has low contention,
1832 and thus the compare-and-swap operation succeeds. */
1833 return boolean_true_node;
1837 return NULL;
1840 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1842 tree res;
1843 op0 = expr_expected_value (op0, visited);
1844 if (!op0)
1845 return NULL;
1846 op1 = expr_expected_value (op1, visited);
1847 if (!op1)
1848 return NULL;
1849 res = fold_build2 (code, type, op0, op1);
1850 if (TREE_CONSTANT (res))
1851 return res;
1852 return NULL;
1854 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1856 tree res;
1857 op0 = expr_expected_value (op0, visited);
1858 if (!op0)
1859 return NULL;
1860 res = fold_build1 (code, type, op0);
1861 if (TREE_CONSTANT (res))
1862 return res;
1863 return NULL;
1865 return NULL;
1868 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1869 The function is used by builtin_expect branch predictor so the evidence
1870 must come from this construct and additional possible constant folding.
1872 We may want to implement more involved value guess (such as value range
1873 propagation based prediction), but such tricks shall go to new
1874 implementation. */
1876 static tree
1877 expr_expected_value (tree expr, bitmap visited)
1879 enum tree_code code;
1880 tree op0, op1;
1882 if (TREE_CONSTANT (expr))
1883 return expr;
1885 extract_ops_from_tree (expr, &code, &op0, &op1);
1886 return expr_expected_value_1 (TREE_TYPE (expr),
1887 op0, code, op1, visited);
1891 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1892 we no longer need. */
1893 static unsigned int
1894 strip_predict_hints (void)
1896 basic_block bb;
1897 gimple ass_stmt;
1898 tree var;
1900 FOR_EACH_BB (bb)
1902 gimple_stmt_iterator bi;
1903 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1905 gimple stmt = gsi_stmt (bi);
1907 if (gimple_code (stmt) == GIMPLE_PREDICT)
1909 gsi_remove (&bi, true);
1910 continue;
1912 else if (gimple_code (stmt) == GIMPLE_CALL)
1914 tree fndecl = gimple_call_fndecl (stmt);
1916 if (fndecl
1917 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1918 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1919 && gimple_call_num_args (stmt) == 2)
1921 var = gimple_call_lhs (stmt);
1922 if (var)
1924 ass_stmt
1925 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1926 gsi_replace (&bi, ass_stmt, true);
1928 else
1930 gsi_remove (&bi, true);
1931 continue;
1935 gsi_next (&bi);
1938 return 0;
1941 /* Predict using opcode of the last statement in basic block. */
1942 static void
1943 tree_predict_by_opcode (basic_block bb)
1945 gimple stmt = last_stmt (bb);
1946 edge then_edge;
1947 tree op0, op1;
1948 tree type;
1949 tree val;
1950 enum tree_code cmp;
1951 bitmap visited;
1952 edge_iterator ei;
1954 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1955 return;
1956 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1957 if (then_edge->flags & EDGE_TRUE_VALUE)
1958 break;
1959 op0 = gimple_cond_lhs (stmt);
1960 op1 = gimple_cond_rhs (stmt);
1961 cmp = gimple_cond_code (stmt);
1962 type = TREE_TYPE (op0);
1963 visited = BITMAP_ALLOC (NULL);
1964 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1965 BITMAP_FREE (visited);
1966 if (val)
1968 if (integer_zerop (val))
1969 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1970 else
1971 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1972 return;
1974 /* Try "pointer heuristic."
1975 A comparison ptr == 0 is predicted as false.
1976 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1977 if (POINTER_TYPE_P (type))
1979 if (cmp == EQ_EXPR)
1980 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1981 else if (cmp == NE_EXPR)
1982 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1984 else
1986 /* Try "opcode heuristic."
1987 EQ tests are usually false and NE tests are usually true. Also,
1988 most quantities are positive, so we can make the appropriate guesses
1989 about signed comparisons against zero. */
1990 switch (cmp)
1992 case EQ_EXPR:
1993 case UNEQ_EXPR:
1994 /* Floating point comparisons appears to behave in a very
1995 unpredictable way because of special role of = tests in
1996 FP code. */
1997 if (FLOAT_TYPE_P (type))
1999 /* Comparisons with 0 are often used for booleans and there is
2000 nothing useful to predict about them. */
2001 else if (integer_zerop (op0) || integer_zerop (op1))
2003 else
2004 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
2005 break;
2007 case NE_EXPR:
2008 case LTGT_EXPR:
2009 /* Floating point comparisons appears to behave in a very
2010 unpredictable way because of special role of = tests in
2011 FP code. */
2012 if (FLOAT_TYPE_P (type))
2014 /* Comparisons with 0 are often used for booleans and there is
2015 nothing useful to predict about them. */
2016 else if (integer_zerop (op0)
2017 || integer_zerop (op1))
2019 else
2020 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
2021 break;
2023 case ORDERED_EXPR:
2024 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
2025 break;
2027 case UNORDERED_EXPR:
2028 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
2029 break;
2031 case LE_EXPR:
2032 case LT_EXPR:
2033 if (integer_zerop (op1)
2034 || integer_onep (op1)
2035 || integer_all_onesp (op1)
2036 || real_zerop (op1)
2037 || real_onep (op1)
2038 || real_minus_onep (op1))
2039 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
2040 break;
2042 case GE_EXPR:
2043 case GT_EXPR:
2044 if (integer_zerop (op1)
2045 || integer_onep (op1)
2046 || integer_all_onesp (op1)
2047 || real_zerop (op1)
2048 || real_onep (op1)
2049 || real_minus_onep (op1))
2050 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
2051 break;
2053 default:
2054 break;
2058 /* Try to guess whether the value of return means error code. */
2060 static enum br_predictor
2061 return_prediction (tree val, enum prediction *prediction)
2063 /* VOID. */
2064 if (!val)
2065 return PRED_NO_PREDICTION;
2066 /* Different heuristics for pointers and scalars. */
2067 if (POINTER_TYPE_P (TREE_TYPE (val)))
2069 /* NULL is usually not returned. */
2070 if (integer_zerop (val))
2072 *prediction = NOT_TAKEN;
2073 return PRED_NULL_RETURN;
2076 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
2078 /* Negative return values are often used to indicate
2079 errors. */
2080 if (TREE_CODE (val) == INTEGER_CST
2081 && tree_int_cst_sgn (val) < 0)
2083 *prediction = NOT_TAKEN;
2084 return PRED_NEGATIVE_RETURN;
2086 /* Constant return values seems to be commonly taken.
2087 Zero/one often represent booleans so exclude them from the
2088 heuristics. */
2089 if (TREE_CONSTANT (val)
2090 && (!integer_zerop (val) && !integer_onep (val)))
2092 *prediction = TAKEN;
2093 return PRED_CONST_RETURN;
2096 return PRED_NO_PREDICTION;
2099 /* Find the basic block with return expression and look up for possible
2100 return value trying to apply RETURN_PREDICTION heuristics. */
2101 static void
2102 apply_return_prediction (void)
2104 gimple return_stmt = NULL;
2105 tree return_val;
2106 edge e;
2107 gimple phi;
2108 int phi_num_args, i;
2109 enum br_predictor pred;
2110 enum prediction direction;
2111 edge_iterator ei;
2113 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2115 return_stmt = last_stmt (e->src);
2116 if (return_stmt
2117 && gimple_code (return_stmt) == GIMPLE_RETURN)
2118 break;
2120 if (!e)
2121 return;
2122 return_val = gimple_return_retval (return_stmt);
2123 if (!return_val)
2124 return;
2125 if (TREE_CODE (return_val) != SSA_NAME
2126 || !SSA_NAME_DEF_STMT (return_val)
2127 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
2128 return;
2129 phi = SSA_NAME_DEF_STMT (return_val);
2130 phi_num_args = gimple_phi_num_args (phi);
2131 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
2133 /* Avoid the degenerate case where all return values form the function
2134 belongs to same category (ie they are all positive constants)
2135 so we can hardly say something about them. */
2136 for (i = 1; i < phi_num_args; i++)
2137 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
2138 break;
2139 if (i != phi_num_args)
2140 for (i = 0; i < phi_num_args; i++)
2142 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
2143 if (pred != PRED_NO_PREDICTION)
2144 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
2145 direction);
2149 /* Look for basic block that contains unlikely to happen events
2150 (such as noreturn calls) and mark all paths leading to execution
2151 of this basic blocks as unlikely. */
2153 static void
2154 tree_bb_level_predictions (void)
2156 basic_block bb;
2157 bool has_return_edges = false;
2158 edge e;
2159 edge_iterator ei;
2161 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2162 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
2164 has_return_edges = true;
2165 break;
2168 apply_return_prediction ();
2170 FOR_EACH_BB (bb)
2172 gimple_stmt_iterator gsi;
2174 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2176 gimple stmt = gsi_stmt (gsi);
2177 tree decl;
2179 if (is_gimple_call (stmt))
2181 if ((gimple_call_flags (stmt) & ECF_NORETURN)
2182 && has_return_edges)
2183 predict_paths_leading_to (bb, PRED_NORETURN,
2184 NOT_TAKEN);
2185 decl = gimple_call_fndecl (stmt);
2186 if (decl
2187 && lookup_attribute ("cold",
2188 DECL_ATTRIBUTES (decl)))
2189 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
2190 NOT_TAKEN);
2192 else if (gimple_code (stmt) == GIMPLE_PREDICT)
2194 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
2195 gimple_predict_outcome (stmt));
2196 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2197 hints to callers. */
2203 #ifdef ENABLE_CHECKING
2205 /* Callback for pointer_map_traverse, asserts that the pointer map is
2206 empty. */
2208 static bool
2209 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
2210 void *data ATTRIBUTE_UNUSED)
2212 gcc_assert (!*value);
2213 return false;
2215 #endif
2217 /* Predict branch probabilities and estimate profile for basic block BB. */
2219 static void
2220 tree_estimate_probability_bb (basic_block bb)
2222 edge e;
2223 edge_iterator ei;
2224 gimple last;
2226 FOR_EACH_EDGE (e, ei, bb->succs)
2228 /* Predict edges to user labels with attributes. */
2229 if (e->dest != EXIT_BLOCK_PTR)
2231 gimple_stmt_iterator gi;
2232 for (gi = gsi_start_bb (e->dest); !gsi_end_p (gi); gsi_next (&gi))
2234 gimple stmt = gsi_stmt (gi);
2235 tree decl;
2237 if (gimple_code (stmt) != GIMPLE_LABEL)
2238 break;
2239 decl = gimple_label_label (stmt);
2240 if (DECL_ARTIFICIAL (decl))
2241 continue;
2243 /* Finally, we have a user-defined label. */
2244 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl)))
2245 predict_edge_def (e, PRED_COLD_LABEL, NOT_TAKEN);
2246 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl)))
2247 predict_edge_def (e, PRED_HOT_LABEL, TAKEN);
2251 /* Predict early returns to be probable, as we've already taken
2252 care for error returns and other cases are often used for
2253 fast paths through function.
2255 Since we've already removed the return statements, we are
2256 looking for CFG like:
2258 if (conditional)
2261 goto return_block
2263 some other blocks
2264 return_block:
2265 return_stmt. */
2266 if (e->dest != bb->next_bb
2267 && e->dest != EXIT_BLOCK_PTR
2268 && single_succ_p (e->dest)
2269 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
2270 && (last = last_stmt (e->dest)) != NULL
2271 && gimple_code (last) == GIMPLE_RETURN)
2273 edge e1;
2274 edge_iterator ei1;
2276 if (single_succ_p (bb))
2278 FOR_EACH_EDGE (e1, ei1, bb->preds)
2279 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
2280 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
2281 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
2282 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2284 else
2285 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
2286 && !predicted_by_p (e->src, PRED_CONST_RETURN)
2287 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
2288 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2291 /* Look for block we are guarding (ie we dominate it,
2292 but it doesn't postdominate us). */
2293 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
2294 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
2295 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
2297 gimple_stmt_iterator bi;
2299 /* The call heuristic claims that a guarded function call
2300 is improbable. This is because such calls are often used
2301 to signal exceptional situations such as printing error
2302 messages. */
2303 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
2304 gsi_next (&bi))
2306 gimple stmt = gsi_stmt (bi);
2307 if (is_gimple_call (stmt)
2308 /* Constant and pure calls are hardly used to signalize
2309 something exceptional. */
2310 && gimple_has_side_effects (stmt))
2312 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
2313 break;
2318 tree_predict_by_opcode (bb);
2321 /* Predict branch probabilities and estimate profile of the tree CFG.
2322 This function can be called from the loop optimizers to recompute
2323 the profile information. */
2325 void
2326 tree_estimate_probability (void)
2328 basic_block bb;
2330 add_noreturn_fake_exit_edges ();
2331 connect_infinite_loops_to_exit ();
2332 /* We use loop_niter_by_eval, which requires that the loops have
2333 preheaders. */
2334 create_preheaders (CP_SIMPLE_PREHEADERS);
2335 calculate_dominance_info (CDI_POST_DOMINATORS);
2337 bb_predictions = pointer_map_create ();
2338 tree_bb_level_predictions ();
2339 record_loop_exits ();
2341 if (number_of_loops (cfun) > 1)
2342 predict_loops ();
2344 FOR_EACH_BB (bb)
2345 tree_estimate_probability_bb (bb);
2347 FOR_EACH_BB (bb)
2348 combine_predictions_for_bb (bb);
2350 #ifdef ENABLE_CHECKING
2351 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
2352 #endif
2353 pointer_map_destroy (bb_predictions);
2354 bb_predictions = NULL;
2356 estimate_bb_frequencies ();
2357 free_dominance_info (CDI_POST_DOMINATORS);
2358 remove_fake_exit_edges ();
2361 /* Predict branch probabilities and estimate profile of the tree CFG.
2362 This is the driver function for PASS_PROFILE. */
2364 static unsigned int
2365 tree_estimate_probability_driver (void)
2367 unsigned nb_loops;
2369 loop_optimizer_init (LOOPS_NORMAL);
2370 if (dump_file && (dump_flags & TDF_DETAILS))
2371 flow_loops_dump (dump_file, NULL, 0);
2373 mark_irreducible_loops ();
2375 nb_loops = number_of_loops (cfun);
2376 if (nb_loops > 1)
2377 scev_initialize ();
2379 tree_estimate_probability ();
2381 if (nb_loops > 1)
2382 scev_finalize ();
2384 loop_optimizer_finalize ();
2385 if (dump_file && (dump_flags & TDF_DETAILS))
2386 gimple_dump_cfg (dump_file, dump_flags);
2387 if (profile_status == PROFILE_ABSENT)
2388 profile_status = PROFILE_GUESSED;
2389 return 0;
2392 /* Predict edges to successors of CUR whose sources are not postdominated by
2393 BB by PRED and recurse to all postdominators. */
2395 static void
2396 predict_paths_for_bb (basic_block cur, basic_block bb,
2397 enum br_predictor pred,
2398 enum prediction taken,
2399 bitmap visited)
2401 edge e;
2402 edge_iterator ei;
2403 basic_block son;
2405 /* We are looking for all edges forming edge cut induced by
2406 set of all blocks postdominated by BB. */
2407 FOR_EACH_EDGE (e, ei, cur->preds)
2408 if (e->src->index >= NUM_FIXED_BLOCKS
2409 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
2411 edge e2;
2412 edge_iterator ei2;
2413 bool found = false;
2415 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2416 if (e->flags & (EDGE_EH | EDGE_FAKE))
2417 continue;
2418 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
2420 /* See if there is an edge from e->src that is not abnormal
2421 and does not lead to BB. */
2422 FOR_EACH_EDGE (e2, ei2, e->src->succs)
2423 if (e2 != e
2424 && !(e2->flags & (EDGE_EH | EDGE_FAKE))
2425 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb))
2427 found = true;
2428 break;
2431 /* If there is non-abnormal path leaving e->src, predict edge
2432 using predictor. Otherwise we need to look for paths
2433 leading to e->src.
2435 The second may lead to infinite loop in the case we are predicitng
2436 regions that are only reachable by abnormal edges. We simply
2437 prevent visiting given BB twice. */
2438 if (found)
2439 predict_edge_def (e, pred, taken);
2440 else if (bitmap_set_bit (visited, e->src->index))
2441 predict_paths_for_bb (e->src, e->src, pred, taken, visited);
2443 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
2444 son;
2445 son = next_dom_son (CDI_POST_DOMINATORS, son))
2446 predict_paths_for_bb (son, bb, pred, taken, visited);
2449 /* Sets branch probabilities according to PREDiction and
2450 FLAGS. */
2452 static void
2453 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
2454 enum prediction taken)
2456 bitmap visited = BITMAP_ALLOC (NULL);
2457 predict_paths_for_bb (bb, bb, pred, taken, visited);
2458 BITMAP_FREE (visited);
2461 /* Like predict_paths_leading_to but take edge instead of basic block. */
2463 static void
2464 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
2465 enum prediction taken)
2467 bool has_nonloop_edge = false;
2468 edge_iterator ei;
2469 edge e2;
2471 basic_block bb = e->src;
2472 FOR_EACH_EDGE (e2, ei, bb->succs)
2473 if (e2->dest != e->src && e2->dest != e->dest
2474 && !(e->flags & (EDGE_EH | EDGE_FAKE))
2475 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
2477 has_nonloop_edge = true;
2478 break;
2480 if (!has_nonloop_edge)
2482 bitmap visited = BITMAP_ALLOC (NULL);
2483 predict_paths_for_bb (bb, bb, pred, taken, visited);
2484 BITMAP_FREE (visited);
2486 else
2487 predict_edge_def (e, pred, taken);
2490 /* This is used to carry information about basic blocks. It is
2491 attached to the AUX field of the standard CFG block. */
2493 typedef struct block_info_def
2495 /* Estimated frequency of execution of basic_block. */
2496 sreal frequency;
2498 /* To keep queue of basic blocks to process. */
2499 basic_block next;
2501 /* Number of predecessors we need to visit first. */
2502 int npredecessors;
2503 } *block_info;
2505 /* Similar information for edges. */
2506 typedef struct edge_info_def
2508 /* In case edge is a loopback edge, the probability edge will be reached
2509 in case header is. Estimated number of iterations of the loop can be
2510 then computed as 1 / (1 - back_edge_prob). */
2511 sreal back_edge_prob;
2512 /* True if the edge is a loopback edge in the natural loop. */
2513 unsigned int back_edge:1;
2514 } *edge_info;
2516 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2517 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2519 /* Helper function for estimate_bb_frequencies.
2520 Propagate the frequencies in blocks marked in
2521 TOVISIT, starting in HEAD. */
2523 static void
2524 propagate_freq (basic_block head, bitmap tovisit)
2526 basic_block bb;
2527 basic_block last;
2528 unsigned i;
2529 edge e;
2530 basic_block nextbb;
2531 bitmap_iterator bi;
2533 /* For each basic block we need to visit count number of his predecessors
2534 we need to visit first. */
2535 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
2537 edge_iterator ei;
2538 int count = 0;
2540 bb = BASIC_BLOCK (i);
2542 FOR_EACH_EDGE (e, ei, bb->preds)
2544 bool visit = bitmap_bit_p (tovisit, e->src->index);
2546 if (visit && !(e->flags & EDGE_DFS_BACK))
2547 count++;
2548 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
2549 fprintf (dump_file,
2550 "Irreducible region hit, ignoring edge to %i->%i\n",
2551 e->src->index, bb->index);
2553 BLOCK_INFO (bb)->npredecessors = count;
2554 /* When function never returns, we will never process exit block. */
2555 if (!count && bb == EXIT_BLOCK_PTR)
2556 bb->count = bb->frequency = 0;
2559 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
2560 last = head;
2561 for (bb = head; bb; bb = nextbb)
2563 edge_iterator ei;
2564 sreal cyclic_probability, frequency;
2566 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
2567 memcpy (&frequency, &real_zero, sizeof (real_zero));
2569 nextbb = BLOCK_INFO (bb)->next;
2570 BLOCK_INFO (bb)->next = NULL;
2572 /* Compute frequency of basic block. */
2573 if (bb != head)
2575 #ifdef ENABLE_CHECKING
2576 FOR_EACH_EDGE (e, ei, bb->preds)
2577 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
2578 || (e->flags & EDGE_DFS_BACK));
2579 #endif
2581 FOR_EACH_EDGE (e, ei, bb->preds)
2582 if (EDGE_INFO (e)->back_edge)
2584 sreal_add (&cyclic_probability, &cyclic_probability,
2585 &EDGE_INFO (e)->back_edge_prob);
2587 else if (!(e->flags & EDGE_DFS_BACK))
2589 sreal tmp;
2591 /* frequency += (e->probability
2592 * BLOCK_INFO (e->src)->frequency /
2593 REG_BR_PROB_BASE); */
2595 sreal_init (&tmp, e->probability, 0);
2596 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
2597 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
2598 sreal_add (&frequency, &frequency, &tmp);
2601 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
2603 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
2604 sizeof (frequency));
2606 else
2608 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
2610 memcpy (&cyclic_probability, &real_almost_one,
2611 sizeof (real_almost_one));
2614 /* BLOCK_INFO (bb)->frequency = frequency
2615 / (1 - cyclic_probability) */
2617 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
2618 sreal_div (&BLOCK_INFO (bb)->frequency,
2619 &frequency, &cyclic_probability);
2623 bitmap_clear_bit (tovisit, bb->index);
2625 e = find_edge (bb, head);
2626 if (e)
2628 sreal tmp;
2630 /* EDGE_INFO (e)->back_edge_prob
2631 = ((e->probability * BLOCK_INFO (bb)->frequency)
2632 / REG_BR_PROB_BASE); */
2634 sreal_init (&tmp, e->probability, 0);
2635 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
2636 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2637 &tmp, &real_inv_br_prob_base);
2640 /* Propagate to successor blocks. */
2641 FOR_EACH_EDGE (e, ei, bb->succs)
2642 if (!(e->flags & EDGE_DFS_BACK)
2643 && BLOCK_INFO (e->dest)->npredecessors)
2645 BLOCK_INFO (e->dest)->npredecessors--;
2646 if (!BLOCK_INFO (e->dest)->npredecessors)
2648 if (!nextbb)
2649 nextbb = e->dest;
2650 else
2651 BLOCK_INFO (last)->next = e->dest;
2653 last = e->dest;
2659 /* Estimate probabilities of loopback edges in loops at same nest level. */
2661 static void
2662 estimate_loops_at_level (struct loop *first_loop)
2664 struct loop *loop;
2666 for (loop = first_loop; loop; loop = loop->next)
2668 edge e;
2669 basic_block *bbs;
2670 unsigned i;
2671 bitmap tovisit = BITMAP_ALLOC (NULL);
2673 estimate_loops_at_level (loop->inner);
2675 /* Find current loop back edge and mark it. */
2676 e = loop_latch_edge (loop);
2677 EDGE_INFO (e)->back_edge = 1;
2679 bbs = get_loop_body (loop);
2680 for (i = 0; i < loop->num_nodes; i++)
2681 bitmap_set_bit (tovisit, bbs[i]->index);
2682 free (bbs);
2683 propagate_freq (loop->header, tovisit);
2684 BITMAP_FREE (tovisit);
2688 /* Propagates frequencies through structure of loops. */
2690 static void
2691 estimate_loops (void)
2693 bitmap tovisit = BITMAP_ALLOC (NULL);
2694 basic_block bb;
2696 /* Start by estimating the frequencies in the loops. */
2697 if (number_of_loops (cfun) > 1)
2698 estimate_loops_at_level (current_loops->tree_root->inner);
2700 /* Now propagate the frequencies through all the blocks. */
2701 FOR_ALL_BB (bb)
2703 bitmap_set_bit (tovisit, bb->index);
2705 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2706 BITMAP_FREE (tovisit);
2709 /* Convert counts measured by profile driven feedback to frequencies.
2710 Return nonzero iff there was any nonzero execution count. */
2713 counts_to_freqs (void)
2715 gcov_type count_max, true_count_max = 0;
2716 basic_block bb;
2718 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2719 true_count_max = MAX (bb->count, true_count_max);
2721 count_max = MAX (true_count_max, 1);
2722 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2723 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2725 return true_count_max;
2728 /* Return true if function is likely to be expensive, so there is no point to
2729 optimize performance of prologue, epilogue or do inlining at the expense
2730 of code size growth. THRESHOLD is the limit of number of instructions
2731 function can execute at average to be still considered not expensive. */
2733 bool
2734 expensive_function_p (int threshold)
2736 unsigned int sum = 0;
2737 basic_block bb;
2738 unsigned int limit;
2740 /* We can not compute accurately for large thresholds due to scaled
2741 frequencies. */
2742 gcc_assert (threshold <= BB_FREQ_MAX);
2744 /* Frequencies are out of range. This either means that function contains
2745 internal loop executing more than BB_FREQ_MAX times or profile feedback
2746 is available and function has not been executed at all. */
2747 if (ENTRY_BLOCK_PTR->frequency == 0)
2748 return true;
2750 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2751 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2752 FOR_EACH_BB (bb)
2754 rtx insn;
2756 FOR_BB_INSNS (bb, insn)
2757 if (active_insn_p (insn))
2759 sum += bb->frequency;
2760 if (sum > limit)
2761 return true;
2765 return false;
2768 /* Estimate basic blocks frequency by given branch probabilities. */
2770 void
2771 estimate_bb_frequencies (void)
2773 basic_block bb;
2774 sreal freq_max;
2776 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2778 static int real_values_initialized = 0;
2780 if (!real_values_initialized)
2782 real_values_initialized = 1;
2783 sreal_init (&real_zero, 0, 0);
2784 sreal_init (&real_one, 1, 0);
2785 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2786 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2787 sreal_init (&real_one_half, 1, -1);
2788 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2789 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2792 mark_dfs_back_edges ();
2794 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2796 /* Set up block info for each basic block. */
2797 alloc_aux_for_blocks (sizeof (struct block_info_def));
2798 alloc_aux_for_edges (sizeof (struct edge_info_def));
2799 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2801 edge e;
2802 edge_iterator ei;
2804 FOR_EACH_EDGE (e, ei, bb->succs)
2806 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2807 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2808 &EDGE_INFO (e)->back_edge_prob,
2809 &real_inv_br_prob_base);
2813 /* First compute probabilities locally for each loop from innermost
2814 to outermost to examine probabilities for back edges. */
2815 estimate_loops ();
2817 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2818 FOR_EACH_BB (bb)
2819 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2820 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2822 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2823 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2825 sreal tmp;
2827 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2828 sreal_add (&tmp, &tmp, &real_one_half);
2829 bb->frequency = sreal_to_int (&tmp);
2832 free_aux_for_blocks ();
2833 free_aux_for_edges ();
2835 compute_function_frequency ();
2838 /* Decide whether function is hot, cold or unlikely executed. */
2839 void
2840 compute_function_frequency (void)
2842 basic_block bb;
2843 struct cgraph_node *node = cgraph_get_node (current_function_decl);
2844 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2845 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
2846 node->only_called_at_startup = true;
2847 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
2848 node->only_called_at_exit = true;
2850 if (!profile_info || !flag_branch_probabilities)
2852 int flags = flags_from_decl_or_type (current_function_decl);
2853 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2854 != NULL)
2855 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2856 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2857 != NULL)
2858 node->frequency = NODE_FREQUENCY_HOT;
2859 else if (flags & ECF_NORETURN)
2860 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2861 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
2862 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2863 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2864 || DECL_STATIC_DESTRUCTOR (current_function_decl))
2865 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2866 return;
2868 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2869 FOR_EACH_BB (bb)
2871 if (maybe_hot_bb_p (cfun, bb))
2873 node->frequency = NODE_FREQUENCY_HOT;
2874 return;
2876 if (!probably_never_executed_bb_p (cfun, bb))
2877 node->frequency = NODE_FREQUENCY_NORMAL;
2881 static bool
2882 gate_estimate_probability (void)
2884 return flag_guess_branch_prob;
2887 /* Build PREDICT_EXPR. */
2888 tree
2889 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2891 tree t = build1 (PREDICT_EXPR, void_type_node,
2892 build_int_cst (integer_type_node, predictor));
2893 SET_PREDICT_EXPR_OUTCOME (t, taken);
2894 return t;
2897 const char *
2898 predictor_name (enum br_predictor predictor)
2900 return predictor_info[predictor].name;
2903 namespace {
2905 const pass_data pass_data_profile =
2907 GIMPLE_PASS, /* type */
2908 "profile_estimate", /* name */
2909 OPTGROUP_NONE, /* optinfo_flags */
2910 true, /* has_gate */
2911 true, /* has_execute */
2912 TV_BRANCH_PROB, /* tv_id */
2913 PROP_cfg, /* properties_required */
2914 0, /* properties_provided */
2915 0, /* properties_destroyed */
2916 0, /* todo_flags_start */
2917 TODO_verify_ssa, /* todo_flags_finish */
2920 class pass_profile : public gimple_opt_pass
2922 public:
2923 pass_profile(gcc::context *ctxt)
2924 : gimple_opt_pass(pass_data_profile, ctxt)
2927 /* opt_pass methods: */
2928 bool gate () { return gate_estimate_probability (); }
2929 unsigned int execute () { return tree_estimate_probability_driver (); }
2931 }; // class pass_profile
2933 } // anon namespace
2935 gimple_opt_pass *
2936 make_pass_profile (gcc::context *ctxt)
2938 return new pass_profile (ctxt);
2941 namespace {
2943 const pass_data pass_data_strip_predict_hints =
2945 GIMPLE_PASS, /* type */
2946 "*strip_predict_hints", /* name */
2947 OPTGROUP_NONE, /* optinfo_flags */
2948 false, /* has_gate */
2949 true, /* has_execute */
2950 TV_BRANCH_PROB, /* tv_id */
2951 PROP_cfg, /* properties_required */
2952 0, /* properties_provided */
2953 0, /* properties_destroyed */
2954 0, /* todo_flags_start */
2955 TODO_verify_ssa, /* todo_flags_finish */
2958 class pass_strip_predict_hints : public gimple_opt_pass
2960 public:
2961 pass_strip_predict_hints(gcc::context *ctxt)
2962 : gimple_opt_pass(pass_data_strip_predict_hints, ctxt)
2965 /* opt_pass methods: */
2966 opt_pass * clone () { return new pass_strip_predict_hints (ctxt_); }
2967 unsigned int execute () { return strip_predict_hints (); }
2969 }; // class pass_strip_predict_hints
2971 } // anon namespace
2973 gimple_opt_pass *
2974 make_pass_strip_predict_hints (gcc::context *ctxt)
2976 return new pass_strip_predict_hints (ctxt);
2979 /* Rebuild function frequencies. Passes are in general expected to
2980 maintain profile by hand, however in some cases this is not possible:
2981 for example when inlining several functions with loops freuqencies might run
2982 out of scale and thus needs to be recomputed. */
2984 void
2985 rebuild_frequencies (void)
2987 timevar_push (TV_REBUILD_FREQUENCIES);
2988 if (profile_status == PROFILE_GUESSED)
2990 loop_optimizer_init (0);
2991 add_noreturn_fake_exit_edges ();
2992 mark_irreducible_loops ();
2993 connect_infinite_loops_to_exit ();
2994 estimate_bb_frequencies ();
2995 remove_fake_exit_edges ();
2996 loop_optimizer_finalize ();
2998 else if (profile_status == PROFILE_READ)
2999 counts_to_freqs ();
3000 else
3001 gcc_unreachable ();
3002 timevar_pop (TV_REBUILD_FREQUENCIES);