2003-02-28 Aldy Hernandez <aldyh@redhat.com>
[official-gcc.git] / gcc / predict.c
blob704f269a7f61779dc69edf42ca44733e9cba1ce2
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002 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 2, 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 COPYING. If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA. */
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 "toplev.h"
47 #include "recog.h"
48 #include "expr.h"
49 #include "predict.h"
50 #include "profile.h"
51 #include "sreal.h"
52 #include "params.h"
53 #include "target.h"
54 #include "loop.h"
55 #include "cfgloop.h"
57 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
58 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
59 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
60 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
62 /* Random guesstimation given names. */
63 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 10 - 1)
64 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
65 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
66 #define PROB_ALWAYS (REG_BR_PROB_BASE)
68 static bool predicted_by_p PARAMS ((basic_block,
69 enum br_predictor));
70 static void combine_predictions_for_insn PARAMS ((rtx, basic_block));
71 static void dump_prediction PARAMS ((enum br_predictor, int,
72 basic_block, int));
73 static void estimate_loops_at_level PARAMS ((struct loop *loop));
74 static void propagate_freq PARAMS ((struct loop *));
75 static void estimate_bb_frequencies PARAMS ((struct loops *));
76 static void counts_to_freqs PARAMS ((void));
77 static void process_note_predictions PARAMS ((basic_block, int *,
78 dominance_info,
79 dominance_info));
80 static void process_note_prediction PARAMS ((basic_block, int *,
81 dominance_info,
82 dominance_info, int, int));
83 static bool last_basic_block_p PARAMS ((basic_block));
84 static void compute_function_frequency PARAMS ((void));
85 static void choose_function_section PARAMS ((void));
86 static bool can_predict_insn_p PARAMS ((rtx));
88 /* Information we hold about each branch predictor.
89 Filled using information from predict.def. */
91 struct predictor_info
93 const char *const name; /* Name used in the debugging dumps. */
94 const int hitrate; /* Expected hitrate used by
95 predict_insn_def call. */
96 const int flags;
99 /* Use given predictor without Dempster-Shaffer theory if it matches
100 using first_match heuristics. */
101 #define PRED_FLAG_FIRST_MATCH 1
103 /* Recompute hitrate in percent to our representation. */
105 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
107 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
108 static const struct predictor_info predictor_info[]= {
109 #include "predict.def"
111 /* Upper bound on predictors. */
112 {NULL, 0, 0}
114 #undef DEF_PREDICTOR
116 /* Return true in case BB can be CPU intensive and should be optimized
117 for maximal performance. */
119 bool
120 maybe_hot_bb_p (bb)
121 basic_block bb;
123 if (profile_info.count_profiles_merged
124 && flag_branch_probabilities
125 && (bb->count
126 < profile_info.max_counter_in_program
127 / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
128 return false;
129 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
130 return false;
131 return true;
134 /* Return true in case BB is cold and should be optimized for size. */
136 bool
137 probably_cold_bb_p (bb)
138 basic_block bb;
140 if (profile_info.count_profiles_merged
141 && flag_branch_probabilities
142 && (bb->count
143 < profile_info.max_counter_in_program
144 / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
145 return true;
146 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
147 return true;
148 return false;
151 /* Return true in case BB is probably never executed. */
152 bool
153 probably_never_executed_bb_p (bb)
154 basic_block bb;
156 if (profile_info.count_profiles_merged
157 && flag_branch_probabilities)
158 return ((bb->count + profile_info.count_profiles_merged / 2)
159 / profile_info.count_profiles_merged) == 0;
160 return false;
163 /* Return true if the one of outgoing edges is already predicted by
164 PREDICTOR. */
166 static bool
167 predicted_by_p (bb, predictor)
168 basic_block bb;
169 enum br_predictor predictor;
171 rtx note;
172 if (!INSN_P (bb->end))
173 return false;
174 for (note = REG_NOTES (bb->end); note; note = XEXP (note, 1))
175 if (REG_NOTE_KIND (note) == REG_BR_PRED
176 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
177 return true;
178 return false;
181 void
182 predict_insn (insn, predictor, probability)
183 rtx insn;
184 int probability;
185 enum br_predictor predictor;
187 if (!any_condjump_p (insn))
188 abort ();
189 if (!flag_guess_branch_prob)
190 return;
192 REG_NOTES (insn)
193 = gen_rtx_EXPR_LIST (REG_BR_PRED,
194 gen_rtx_CONCAT (VOIDmode,
195 GEN_INT ((int) predictor),
196 GEN_INT ((int) probability)),
197 REG_NOTES (insn));
200 /* Predict insn by given predictor. */
202 void
203 predict_insn_def (insn, predictor, taken)
204 rtx insn;
205 enum br_predictor predictor;
206 enum prediction taken;
208 int probability = predictor_info[(int) predictor].hitrate;
210 if (taken != TAKEN)
211 probability = REG_BR_PROB_BASE - probability;
213 predict_insn (insn, predictor, probability);
216 /* Predict edge E with given probability if possible. */
218 void
219 predict_edge (e, predictor, probability)
220 edge e;
221 int probability;
222 enum br_predictor predictor;
224 rtx last_insn;
225 last_insn = e->src->end;
227 /* We can store the branch prediction information only about
228 conditional jumps. */
229 if (!any_condjump_p (last_insn))
230 return;
232 /* We always store probability of branching. */
233 if (e->flags & EDGE_FALLTHRU)
234 probability = REG_BR_PROB_BASE - probability;
236 predict_insn (last_insn, predictor, probability);
239 /* Return true when we can store prediction on insn INSN.
240 At the moment we represent predictions only on conditional
241 jumps, not at computed jump or other complicated cases. */
242 static bool
243 can_predict_insn_p (insn)
244 rtx insn;
246 return (GET_CODE (insn) == JUMP_INSN
247 && any_condjump_p (insn)
248 && BLOCK_FOR_INSN (insn)->succ->succ_next);
251 /* Predict edge E by given predictor if possible. */
253 void
254 predict_edge_def (e, predictor, taken)
255 edge e;
256 enum br_predictor predictor;
257 enum prediction taken;
259 int probability = predictor_info[(int) predictor].hitrate;
261 if (taken != TAKEN)
262 probability = REG_BR_PROB_BASE - probability;
264 predict_edge (e, predictor, probability);
267 /* Invert all branch predictions or probability notes in the INSN. This needs
268 to be done each time we invert the condition used by the jump. */
270 void
271 invert_br_probabilities (insn)
272 rtx insn;
274 rtx note;
276 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
277 if (REG_NOTE_KIND (note) == REG_BR_PROB)
278 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
279 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
280 XEXP (XEXP (note, 0), 1)
281 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
284 /* Dump information about the branch prediction to the output file. */
286 static void
287 dump_prediction (predictor, probability, bb, used)
288 enum br_predictor predictor;
289 int probability;
290 basic_block bb;
291 int used;
293 edge e = bb->succ;
295 if (!rtl_dump_file)
296 return;
298 while (e && (e->flags & EDGE_FALLTHRU))
299 e = e->succ_next;
301 fprintf (rtl_dump_file, " %s heuristics%s: %.1f%%",
302 predictor_info[predictor].name,
303 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
305 if (bb->count)
307 fprintf (rtl_dump_file, " exec ");
308 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
309 if (e)
311 fprintf (rtl_dump_file, " hit ");
312 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC, e->count);
313 fprintf (rtl_dump_file, " (%.1f%%)", e->count * 100.0 / bb->count);
317 fprintf (rtl_dump_file, "\n");
320 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
321 note if not already present. Remove now useless REG_BR_PRED notes. */
323 static void
324 combine_predictions_for_insn (insn, bb)
325 rtx insn;
326 basic_block bb;
328 rtx prob_note = find_reg_note (insn, REG_BR_PROB, 0);
329 rtx *pnote = &REG_NOTES (insn);
330 rtx note;
331 int best_probability = PROB_EVEN;
332 int best_predictor = END_PREDICTORS;
333 int combined_probability = REG_BR_PROB_BASE / 2;
334 int d;
335 bool first_match = false;
336 bool found = false;
338 if (rtl_dump_file)
339 fprintf (rtl_dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
340 bb->index);
342 /* We implement "first match" heuristics and use probability guessed
343 by predictor with smallest index. In the future we will use better
344 probability combination techniques. */
345 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
346 if (REG_NOTE_KIND (note) == REG_BR_PRED)
348 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
349 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
351 found = true;
352 if (best_predictor > predictor)
353 best_probability = probability, best_predictor = predictor;
355 d = (combined_probability * probability
356 + (REG_BR_PROB_BASE - combined_probability)
357 * (REG_BR_PROB_BASE - probability));
359 /* Use FP math to avoid overflows of 32bit integers. */
360 if (d == 0)
361 /* If one probability is 0% and one 100%, avoid division by zero. */
362 combined_probability = REG_BR_PROB_BASE / 2;
363 else
364 combined_probability = (((double) combined_probability) * probability
365 * REG_BR_PROB_BASE / d + 0.5);
368 /* Decide which heuristic to use. In case we didn't match anything,
369 use no_prediction heuristic, in case we did match, use either
370 first match or Dempster-Shaffer theory depending on the flags. */
372 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
373 first_match = true;
375 if (!found)
376 dump_prediction (PRED_NO_PREDICTION, combined_probability, bb, true);
377 else
379 dump_prediction (PRED_DS_THEORY, combined_probability, bb, !first_match);
380 dump_prediction (PRED_FIRST_MATCH, best_probability, bb, first_match);
383 if (first_match)
384 combined_probability = best_probability;
385 dump_prediction (PRED_COMBINED, combined_probability, bb, true);
387 while (*pnote)
389 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
391 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
392 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
394 dump_prediction (predictor, probability, bb,
395 !first_match || best_predictor == predictor);
396 *pnote = XEXP (*pnote, 1);
398 else
399 pnote = &XEXP (*pnote, 1);
402 if (!prob_note)
404 REG_NOTES (insn)
405 = gen_rtx_EXPR_LIST (REG_BR_PROB,
406 GEN_INT (combined_probability), REG_NOTES (insn));
408 /* Save the prediction into CFG in case we are seeing non-degenerated
409 conditional jump. */
410 if (bb->succ->succ_next)
412 BRANCH_EDGE (bb)->probability = combined_probability;
413 FALLTHRU_EDGE (bb)->probability
414 = REG_BR_PROB_BASE - combined_probability;
419 /* Statically estimate the probability that a branch will be taken.
420 ??? In the next revision there will be a number of other predictors added
421 from the above references. Further, each heuristic will be factored out
422 into its own function for clarity (and to facilitate the combination of
423 predictions). */
425 void
426 estimate_probability (loops_info)
427 struct loops *loops_info;
429 dominance_info dominators, post_dominators;
430 basic_block bb;
431 unsigned i;
433 connect_infinite_loops_to_exit ();
434 dominators = calculate_dominance_info (CDI_DOMINATORS);
435 post_dominators = calculate_dominance_info (CDI_POST_DOMINATORS);
437 /* Try to predict out blocks in a loop that are not part of a
438 natural loop. */
439 for (i = 1; i < loops_info->num; i++)
441 basic_block bb, *bbs;
442 unsigned j;
443 int exits;
444 struct loop *loop = loops_info->parray[i];
445 struct loop_desc desc;
446 unsigned HOST_WIDE_INT niter;
448 flow_loop_scan (loops_info, loop, LOOP_EXIT_EDGES);
449 exits = loop->num_exits;
451 if (simple_loop_p (loops_info, loop, &desc)
452 && desc.const_iter)
454 int prob;
455 niter = desc.niter + 1;
456 if (niter == 0) /* We might overflow here. */
457 niter = desc.niter;
459 prob = (REG_BR_PROB_BASE
460 - (REG_BR_PROB_BASE + niter /2) / niter);
461 /* Branch prediction algorithm gives 0 frequency for everything
462 after the end of loop for loop having 0 probability to finish. */
463 if (prob == REG_BR_PROB_BASE)
464 prob = REG_BR_PROB_BASE - 1;
465 predict_edge (desc.in_edge, PRED_LOOP_ITERATIONS,
466 prob);
469 bbs = get_loop_body (loop);
470 for (j = 0; j < loop->num_nodes; j++)
472 int header_found = 0;
473 edge e;
475 bb = bbs[j];
477 /* Bypass loop heuristics on continue statement. These
478 statements construct loops via "non-loop" constructs
479 in the source language and are better to be handled
480 separately. */
481 if (!can_predict_insn_p (bb->end)
482 || predicted_by_p (bb, PRED_CONTINUE))
483 continue;
485 /* Loop branch heuristics - predict an edge back to a
486 loop's head as taken. */
487 for (e = bb->succ; e; e = e->succ_next)
488 if (e->dest == loop->header
489 && e->src == loop->latch)
491 header_found = 1;
492 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
495 /* Loop exit heuristics - predict an edge exiting the loop if the
496 conditional has no loop header successors as not taken. */
497 if (!header_found)
498 for (e = bb->succ; e; e = e->succ_next)
499 if (e->dest->index < 0
500 || !flow_bb_inside_loop_p (loop, e->dest))
501 predict_edge
502 (e, PRED_LOOP_EXIT,
503 (REG_BR_PROB_BASE
504 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
505 / exits);
509 /* Attempt to predict conditional jumps using a number of heuristics. */
510 FOR_EACH_BB (bb)
512 rtx last_insn = bb->end;
513 rtx cond, earliest;
514 edge e;
516 if (! can_predict_insn_p (last_insn))
517 continue;
519 for (e = bb->succ; e; e = e->succ_next)
521 /* Predict early returns to be probable, as we've already taken
522 care for error returns and other are often used for fast paths
523 trought function. */
524 if ((e->dest == EXIT_BLOCK_PTR
525 || (e->dest->succ && !e->dest->succ->succ_next
526 && e->dest->succ->dest == EXIT_BLOCK_PTR))
527 && !predicted_by_p (bb, PRED_NULL_RETURN)
528 && !predicted_by_p (bb, PRED_CONST_RETURN)
529 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
530 && !last_basic_block_p (e->dest))
531 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
533 /* Look for block we are guarding (ie we dominate it,
534 but it doesn't postdominate us). */
535 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
536 && dominated_by_p (dominators, e->dest, e->src)
537 && !dominated_by_p (post_dominators, e->src, e->dest))
539 rtx insn;
541 /* The call heuristic claims that a guarded function call
542 is improbable. This is because such calls are often used
543 to signal exceptional situations such as printing error
544 messages. */
545 for (insn = e->dest->head; insn != NEXT_INSN (e->dest->end);
546 insn = NEXT_INSN (insn))
547 if (GET_CODE (insn) == CALL_INSN
548 /* Constant and pure calls are hardly used to signalize
549 something exceptional. */
550 && ! CONST_OR_PURE_CALL_P (insn))
552 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
553 break;
558 cond = get_condition (last_insn, &earliest);
559 if (! cond)
560 continue;
562 /* Try "pointer heuristic."
563 A comparison ptr == 0 is predicted as false.
564 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
565 if (GET_RTX_CLASS (GET_CODE (cond)) == '<'
566 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
567 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
569 if (GET_CODE (cond) == EQ)
570 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
571 else if (GET_CODE (cond) == NE)
572 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
574 else
576 /* Try "opcode heuristic."
577 EQ tests are usually false and NE tests are usually true. Also,
578 most quantities are positive, so we can make the appropriate guesses
579 about signed comparisons against zero. */
580 switch (GET_CODE (cond))
582 case CONST_INT:
583 /* Unconditional branch. */
584 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
585 cond == const0_rtx ? NOT_TAKEN : TAKEN);
586 break;
588 case EQ:
589 case UNEQ:
590 /* Floating point comparisons appears to behave in a very
591 unpredictable way because of special role of = tests in
592 FP code. */
593 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
595 /* Comparisons with 0 are often used for booleans and there is
596 nothing useful to predict about them. */
597 else if (XEXP (cond, 1) == const0_rtx
598 || XEXP (cond, 0) == const0_rtx)
600 else
601 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
602 break;
604 case NE:
605 case LTGT:
606 /* Floating point comparisons appears to behave in a very
607 unpredictable way because of special role of = tests in
608 FP code. */
609 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
611 /* Comparisons with 0 are often used for booleans and there is
612 nothing useful to predict about them. */
613 else if (XEXP (cond, 1) == const0_rtx
614 || XEXP (cond, 0) == const0_rtx)
616 else
617 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
618 break;
620 case ORDERED:
621 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
622 break;
624 case UNORDERED:
625 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
626 break;
628 case LE:
629 case LT:
630 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
631 || XEXP (cond, 1) == constm1_rtx)
632 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
633 break;
635 case GE:
636 case GT:
637 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
638 || XEXP (cond, 1) == constm1_rtx)
639 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
640 break;
642 default:
643 break;
647 /* Attach the combined probability to each conditional jump. */
648 FOR_EACH_BB (bb)
649 if (GET_CODE (bb->end) == JUMP_INSN
650 && any_condjump_p (bb->end)
651 && bb->succ->succ_next != NULL)
652 combine_predictions_for_insn (bb->end, bb);
654 free_dominance_info (post_dominators);
655 free_dominance_info (dominators);
657 remove_fake_edges ();
658 estimate_bb_frequencies (loops_info);
661 /* __builtin_expect dropped tokens into the insn stream describing expected
662 values of registers. Generate branch probabilities based off these
663 values. */
665 void
666 expected_value_to_br_prob ()
668 rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
670 for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
672 switch (GET_CODE (insn))
674 case NOTE:
675 /* Look for expected value notes. */
676 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
678 ev = NOTE_EXPECTED_VALUE (insn);
679 ev_reg = XEXP (ev, 0);
680 delete_insn (insn);
682 continue;
684 case CODE_LABEL:
685 /* Never propagate across labels. */
686 ev = NULL_RTX;
687 continue;
689 case JUMP_INSN:
690 /* Look for simple conditional branches. If we haven't got an
691 expected value yet, no point going further. */
692 if (GET_CODE (insn) != JUMP_INSN || ev == NULL_RTX
693 || ! any_condjump_p (insn))
694 continue;
695 break;
697 default:
698 /* Look for insns that clobber the EV register. */
699 if (ev && reg_set_p (ev_reg, insn))
700 ev = NULL_RTX;
701 continue;
704 /* Collect the branch condition, hopefully relative to EV_REG. */
705 /* ??? At present we'll miss things like
706 (expected_value (eq r70 0))
707 (set r71 -1)
708 (set r80 (lt r70 r71))
709 (set pc (if_then_else (ne r80 0) ...))
710 as canonicalize_condition will render this to us as
711 (lt r70, r71)
712 Could use cselib to try and reduce this further. */
713 cond = XEXP (SET_SRC (pc_set (insn)), 0);
714 cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg);
715 if (! cond || XEXP (cond, 0) != ev_reg
716 || GET_CODE (XEXP (cond, 1)) != CONST_INT)
717 continue;
719 /* Substitute and simplify. Given that the expression we're
720 building involves two constants, we should wind up with either
721 true or false. */
722 cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
723 XEXP (ev, 1), XEXP (cond, 1));
724 cond = simplify_rtx (cond);
726 /* Turn the condition into a scaled branch probability. */
727 if (cond != const_true_rtx && cond != const0_rtx)
728 abort ();
729 predict_insn_def (insn, PRED_BUILTIN_EXPECT,
730 cond == const_true_rtx ? TAKEN : NOT_TAKEN);
734 /* Check whether this is the last basic block of function. Commonly tehre
735 is one extra common cleanup block. */
736 static bool
737 last_basic_block_p (bb)
738 basic_block bb;
740 if (bb == EXIT_BLOCK_PTR)
741 return false;
743 return (bb->next_bb == EXIT_BLOCK_PTR
744 || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
745 && bb->succ && !bb->succ->succ_next
746 && bb->succ->dest->next_bb == EXIT_BLOCK_PTR));
749 /* Sets branch probabilities according to PREDiction and FLAGS. HEADS[bb->index]
750 should be index of basic block in that we need to alter branch predictions
751 (i.e. the first of our dominators such that we do not post-dominate it)
752 (but we fill this information on demand, so -1 may be there in case this
753 was not needed yet). */
755 static void
756 process_note_prediction (bb, heads, dominators, post_dominators, pred, flags)
757 basic_block bb;
758 int *heads;
759 dominance_info dominators;
760 dominance_info post_dominators;
761 int pred;
762 int flags;
764 edge e;
765 int y;
766 bool taken;
768 taken = flags & IS_TAKEN;
770 if (heads[bb->index] < 0)
772 /* This is first time we need this field in heads array; so
773 find first dominator that we do not post-dominate (we are
774 using already known members of heads array). */
775 basic_block ai = bb;
776 basic_block next_ai = get_immediate_dominator (dominators, bb);
777 int head;
779 while (heads[next_ai->index] < 0)
781 if (!dominated_by_p (post_dominators, next_ai, bb))
782 break;
783 heads[next_ai->index] = ai->index;
784 ai = next_ai;
785 next_ai = get_immediate_dominator (dominators, next_ai);
787 if (!dominated_by_p (post_dominators, next_ai, bb))
788 head = next_ai->index;
789 else
790 head = heads[next_ai->index];
791 while (next_ai != bb)
793 next_ai = ai;
794 if (heads[ai->index] == ENTRY_BLOCK)
795 ai = ENTRY_BLOCK_PTR;
796 else
797 ai = BASIC_BLOCK (heads[ai->index]);
798 heads[next_ai->index] = head;
801 y = heads[bb->index];
803 /* Now find the edge that leads to our branch and aply the prediction. */
805 if (y == last_basic_block || !can_predict_insn_p (BASIC_BLOCK (y)->end))
806 return;
807 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
808 if (e->dest->index >= 0
809 && dominated_by_p (post_dominators, e->dest, bb))
810 predict_edge_def (e, pred, taken);
813 /* Gathers NOTE_INSN_PREDICTIONs in given basic block and turns them
814 into branch probabilities. For description of heads array, see
815 process_note_prediction. */
817 static void
818 process_note_predictions (bb, heads, dominators, post_dominators)
819 basic_block bb;
820 int *heads;
821 dominance_info dominators;
822 dominance_info post_dominators;
824 rtx insn;
825 edge e;
827 /* Additionally, we check here for blocks with no successors. */
828 int contained_noreturn_call = 0;
829 int was_bb_head = 0;
830 int noreturn_block = 1;
832 for (insn = bb->end; insn;
833 was_bb_head |= (insn == bb->head), insn = PREV_INSN (insn))
835 if (GET_CODE (insn) != NOTE)
837 if (was_bb_head)
838 break;
839 else
841 /* Noreturn calls cause program to exit, therefore they are
842 always predicted as not taken. */
843 if (GET_CODE (insn) == CALL_INSN
844 && find_reg_note (insn, REG_NORETURN, NULL))
845 contained_noreturn_call = 1;
846 continue;
849 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_PREDICTION)
851 int alg = (int) NOTE_PREDICTION_ALG (insn);
852 /* Process single prediction note. */
853 process_note_prediction (bb,
854 heads,
855 dominators,
856 post_dominators,
857 alg, (int) NOTE_PREDICTION_FLAGS (insn));
858 delete_insn (insn);
861 for (e = bb->succ; e; e = e->succ_next)
862 if (!(e->flags & EDGE_FAKE))
863 noreturn_block = 0;
864 if (contained_noreturn_call)
866 /* This block ended from other reasons than because of return.
867 If it is because of noreturn call, this should certainly not
868 be taken. Otherwise it is probably some error recovery. */
869 process_note_prediction (bb,
870 heads,
871 dominators,
872 post_dominators, PRED_NORETURN, NOT_TAKEN);
876 /* Gathers NOTE_INSN_PREDICTIONs and turns them into
877 branch probabilities. */
879 void
880 note_prediction_to_br_prob ()
882 basic_block bb;
883 dominance_info post_dominators, dominators;
884 int *heads;
886 /* To enable handling of noreturn blocks. */
887 add_noreturn_fake_exit_edges ();
888 connect_infinite_loops_to_exit ();
890 post_dominators = calculate_dominance_info (CDI_POST_DOMINATORS);
891 dominators = calculate_dominance_info (CDI_DOMINATORS);
893 heads = xmalloc (sizeof (int) * last_basic_block);
894 memset (heads, -1, sizeof (int) * last_basic_block);
895 heads[ENTRY_BLOCK_PTR->next_bb->index] = last_basic_block;
897 /* Process all prediction notes. */
899 FOR_EACH_BB (bb)
900 process_note_predictions (bb, heads, dominators, post_dominators);
902 free_dominance_info (post_dominators);
903 free_dominance_info (dominators);
904 free (heads);
906 remove_fake_edges ();
909 /* This is used to carry information about basic blocks. It is
910 attached to the AUX field of the standard CFG block. */
912 typedef struct block_info_def
914 /* Estimated frequency of execution of basic_block. */
915 sreal frequency;
917 /* To keep queue of basic blocks to process. */
918 basic_block next;
920 /* True if block needs to be visited in prop_freqency. */
921 int tovisit:1;
923 /* Number of predecessors we need to visit first. */
924 int npredecessors;
925 } *block_info;
927 /* Similar information for edges. */
928 typedef struct edge_info_def
930 /* In case edge is an loopback edge, the probability edge will be reached
931 in case header is. Estimated number of iterations of the loop can be
932 then computed as 1 / (1 - back_edge_prob). */
933 sreal back_edge_prob;
934 /* True if the edge is an loopback edge in the natural loop. */
935 int back_edge:1;
936 } *edge_info;
938 #define BLOCK_INFO(B) ((block_info) (B)->aux)
939 #define EDGE_INFO(E) ((edge_info) (E)->aux)
941 /* Helper function for estimate_bb_frequencies.
942 Propagate the frequencies for LOOP. */
944 static void
945 propagate_freq (loop)
946 struct loop *loop;
948 basic_block head = loop->header;
949 basic_block bb;
950 basic_block last;
951 edge e;
952 basic_block nextbb;
954 /* For each basic block we need to visit count number of his predecessors
955 we need to visit first. */
956 FOR_EACH_BB (bb)
958 if (BLOCK_INFO (bb)->tovisit)
960 int count = 0;
962 for (e = bb->pred; e; e = e->pred_next)
963 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
964 count++;
965 else if (BLOCK_INFO (e->src)->tovisit
966 && rtl_dump_file && !EDGE_INFO (e)->back_edge)
967 fprintf (rtl_dump_file,
968 "Irreducible region hit, ignoring edge to %i->%i\n",
969 e->src->index, bb->index);
970 BLOCK_INFO (bb)->npredecessors = count;
974 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
975 last = head;
976 for (bb = head; bb; bb = nextbb)
978 sreal cyclic_probability, frequency;
980 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
981 memcpy (&frequency, &real_zero, sizeof (real_zero));
983 nextbb = BLOCK_INFO (bb)->next;
984 BLOCK_INFO (bb)->next = NULL;
986 /* Compute frequency of basic block. */
987 if (bb != head)
989 #ifdef ENABLE_CHECKING
990 for (e = bb->pred; e; e = e->pred_next)
991 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
992 abort ();
993 #endif
995 for (e = bb->pred; e; e = e->pred_next)
996 if (EDGE_INFO (e)->back_edge)
998 sreal_add (&cyclic_probability, &cyclic_probability,
999 &EDGE_INFO (e)->back_edge_prob);
1001 else if (!(e->flags & EDGE_DFS_BACK))
1003 sreal tmp;
1005 /* frequency += (e->probability
1006 * BLOCK_INFO (e->src)->frequency /
1007 REG_BR_PROB_BASE); */
1009 sreal_init (&tmp, e->probability, 0);
1010 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1011 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1012 sreal_add (&frequency, &frequency, &tmp);
1015 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1017 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1018 sizeof (frequency));
1020 else
1022 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1024 memcpy (&cyclic_probability, &real_almost_one,
1025 sizeof (real_almost_one));
1028 /* BLOCK_INFO (bb)->frequency = frequency
1029 / (1 - cyclic_probability) */
1031 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1032 sreal_div (&BLOCK_INFO (bb)->frequency,
1033 &frequency, &cyclic_probability);
1037 BLOCK_INFO (bb)->tovisit = 0;
1039 /* Compute back edge frequencies. */
1040 for (e = bb->succ; e; e = e->succ_next)
1041 if (e->dest == head)
1043 sreal tmp;
1045 /* EDGE_INFO (e)->back_edge_prob
1046 = ((e->probability * BLOCK_INFO (bb)->frequency)
1047 / REG_BR_PROB_BASE); */
1049 sreal_init (&tmp, e->probability, 0);
1050 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1051 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1052 &tmp, &real_inv_br_prob_base);
1055 /* Propagate to successor blocks. */
1056 for (e = bb->succ; e; e = e->succ_next)
1057 if (!(e->flags & EDGE_DFS_BACK)
1058 && BLOCK_INFO (e->dest)->npredecessors)
1060 BLOCK_INFO (e->dest)->npredecessors--;
1061 if (!BLOCK_INFO (e->dest)->npredecessors)
1063 if (!nextbb)
1064 nextbb = e->dest;
1065 else
1066 BLOCK_INFO (last)->next = e->dest;
1068 last = e->dest;
1074 /* Estimate probabilities of loopback edges in loops at same nest level. */
1076 static void
1077 estimate_loops_at_level (first_loop)
1078 struct loop *first_loop;
1080 struct loop *loop;
1082 for (loop = first_loop; loop; loop = loop->next)
1084 edge e;
1085 basic_block *bbs;
1086 unsigned i;
1088 estimate_loops_at_level (loop->inner);
1090 if (loop->latch->succ) /* Do not do this for dummy function loop. */
1092 /* Find current loop back edge and mark it. */
1093 e = loop_latch_edge (loop);
1094 EDGE_INFO (e)->back_edge = 1;
1097 bbs = get_loop_body (loop);
1098 for (i = 0; i < loop->num_nodes; i++)
1099 BLOCK_INFO (bbs[i])->tovisit = 1;
1100 free (bbs);
1101 propagate_freq (loop);
1105 /* Convert counts measured by profile driven feedback to frequencies. */
1107 static void
1108 counts_to_freqs ()
1110 gcov_type count_max = 1;
1111 basic_block bb;
1113 FOR_EACH_BB (bb)
1114 count_max = MAX (bb->count, count_max);
1116 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1117 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1120 /* Return true if function is likely to be expensive, so there is no point to
1121 optimize performance of prologue, epilogue or do inlining at the expense
1122 of code size growth. THRESHOLD is the limit of number of instructions
1123 function can execute at average to be still considered not expensive. */
1125 bool
1126 expensive_function_p (threshold)
1127 int threshold;
1129 unsigned int sum = 0;
1130 basic_block bb;
1131 unsigned int limit;
1133 /* We can not compute accurately for large thresholds due to scaled
1134 frequencies. */
1135 if (threshold > BB_FREQ_MAX)
1136 abort ();
1138 /* Frequencies are out of range. This either means that function contains
1139 internal loop executing more than BB_FREQ_MAX times or profile feedback
1140 is available and function has not been executed at all. */
1141 if (ENTRY_BLOCK_PTR->frequency == 0)
1142 return true;
1144 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1145 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1146 FOR_EACH_BB (bb)
1148 rtx insn;
1150 for (insn = bb->head; insn != NEXT_INSN (bb->end);
1151 insn = NEXT_INSN (insn))
1152 if (active_insn_p (insn))
1154 sum += bb->frequency;
1155 if (sum > limit)
1156 return true;
1160 return false;
1163 /* Estimate basic blocks frequency by given branch probabilities. */
1165 static void
1166 estimate_bb_frequencies (loops)
1167 struct loops *loops;
1169 basic_block bb;
1170 sreal freq_max;
1172 if (flag_branch_probabilities)
1173 counts_to_freqs ();
1174 else
1176 sreal_init (&real_zero, 0, 0);
1177 sreal_init (&real_one, 1, 0);
1178 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
1179 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
1180 sreal_init (&real_one_half, 1, -1);
1181 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
1182 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
1184 mark_dfs_back_edges ();
1185 /* Fill in the probability values in flowgraph based on the REG_BR_PROB
1186 notes. */
1187 FOR_EACH_BB (bb)
1189 rtx last_insn = bb->end;
1191 if (!can_predict_insn_p (last_insn))
1193 /* We can predict only conditional jumps at the moment.
1194 Expect each edge to be equally probable.
1195 ?? In the future we want to make abnormal edges improbable. */
1196 int nedges = 0;
1197 edge e;
1199 for (e = bb->succ; e; e = e->succ_next)
1201 nedges++;
1202 if (e->probability != 0)
1203 break;
1205 if (!e)
1206 for (e = bb->succ; e; e = e->succ_next)
1207 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
1211 ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
1213 /* Set up block info for each basic block. */
1214 alloc_aux_for_blocks (sizeof (struct block_info_def));
1215 alloc_aux_for_edges (sizeof (struct edge_info_def));
1216 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1218 edge e;
1220 BLOCK_INFO (bb)->tovisit = 0;
1221 for (e = bb->succ; e; e = e->succ_next)
1223 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
1224 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1225 &EDGE_INFO (e)->back_edge_prob,
1226 &real_inv_br_prob_base);
1230 /* First compute probabilities locally for each loop from innermost
1231 to outermost to examine probabilities for back edges. */
1232 estimate_loops_at_level (loops->tree_root);
1234 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1235 FOR_EACH_BB (bb)
1236 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
1237 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
1239 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
1240 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1242 sreal tmp;
1244 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
1245 sreal_add (&tmp, &tmp, &real_one_half);
1246 bb->frequency = sreal_to_int (&tmp);
1249 free_aux_for_blocks ();
1250 free_aux_for_edges ();
1252 compute_function_frequency ();
1253 if (flag_reorder_functions)
1254 choose_function_section ();
1257 /* Decide whether function is hot, cold or unlikely executed. */
1258 static void
1259 compute_function_frequency ()
1261 basic_block bb;
1263 if (!profile_info.count_profiles_merged
1264 || !flag_branch_probabilities)
1265 return;
1266 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1267 FOR_EACH_BB (bb)
1269 if (maybe_hot_bb_p (bb))
1271 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1272 return;
1274 if (!probably_never_executed_bb_p (bb))
1275 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1279 /* Choose appropriate section for the function. */
1280 static void
1281 choose_function_section ()
1283 if (DECL_SECTION_NAME (current_function_decl)
1284 || !targetm.have_named_sections
1285 /* Theoretically we can split the gnu.linkonce text section too,
1286 but this requires more work as the frequency needs to match
1287 for all generated objects so we need to merge the frequency
1288 of all instances. For now just never set frequency for these. */
1289 || DECL_ONE_ONLY (current_function_decl))
1290 return;
1291 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1292 DECL_SECTION_NAME (current_function_decl) =
1293 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1294 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1295 DECL_SECTION_NAME (current_function_decl) =
1296 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1297 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);