2002-07-18 H.J. Lu <hjl@gnu.org>
[official-gcc.git] / gcc / predict.c
blob71950ee6766f1b119b2d67f76618c0efce35e537
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 "tree.h"
34 #include "rtl.h"
35 #include "tm_p.h"
36 #include "hard-reg-set.h"
37 #include "basic-block.h"
38 #include "insn-config.h"
39 #include "regs.h"
40 #include "flags.h"
41 #include "output.h"
42 #include "function.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "recog.h"
46 #include "expr.h"
47 #include "predict.h"
48 #include "profile.h"
49 #include "real.h"
50 #include "params.h"
51 #include "target.h"
52 #include "loop.h"
54 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE, 0.5,
55 REAL_BB_FREQ_MAX. */
56 static REAL_VALUE_TYPE real_zero, real_one, real_almost_one, real_br_prob_base,
57 real_one_half, real_bb_freq_max;
59 /* Random guesstimation given names. */
60 #define PROB_NEVER (0)
61 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 10 - 1)
62 #define PROB_UNLIKELY (REG_BR_PROB_BASE * 4 / 10 - 1)
63 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
64 #define PROB_LIKELY (REG_BR_PROB_BASE - PROB_UNLIKELY)
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));
87 /* Information we hold about each branch predictor.
88 Filled using information from predict.def. */
90 struct predictor_info
92 const char *const name; /* Name used in the debugging dumps. */
93 const int hitrate; /* Expected hitrate used by
94 predict_insn_def call. */
95 const int flags;
98 /* Use given predictor without Dempster-Shaffer theory if it matches
99 using first_match heuristics. */
100 #define PRED_FLAG_FIRST_MATCH 1
102 /* Recompute hitrate in percent to our representation. */
104 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
106 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
107 static const struct predictor_info predictor_info[]= {
108 #include "predict.def"
110 /* Upper bound on predictors. */
111 {NULL, 0, 0}
113 #undef DEF_PREDICTOR
115 /* Return true in case BB can be CPU intensive and should be optimized
116 for maximal perofmrance. */
118 bool
119 maybe_hot_bb_p (bb)
120 basic_block bb;
122 if (profile_info.count_profiles_merged
123 && flag_branch_probabilities
124 && (bb->count
125 < profile_info.max_counter_in_program
126 / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
127 return false;
128 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
129 return false;
130 return true;
133 /* Return true in case BB is cold and should be optimized for size. */
135 bool
136 probably_cold_bb_p (bb)
137 basic_block bb;
139 if (profile_info.count_profiles_merged
140 && flag_branch_probabilities
141 && (bb->count
142 < profile_info.max_counter_in_program
143 / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
144 return true;
145 if (bb->frequency < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
146 return true;
147 return false;
150 /* Return true in case BB is probably never executed. */
151 bool
152 probably_never_executed_bb_p (bb)
153 basic_block bb;
155 if (profile_info.count_profiles_merged
156 && flag_branch_probabilities)
157 return ((bb->count + profile_info.count_profiles_merged / 2)
158 / profile_info.count_profiles_merged) == 0;
159 return false;
162 /* Return true if the one of outgoing edges is already predicted by
163 PREDICTOR. */
165 static bool
166 predicted_by_p (bb, predictor)
167 basic_block bb;
168 enum br_predictor predictor;
170 rtx note;
171 if (!INSN_P (bb->end))
172 return false;
173 for (note = REG_NOTES (bb->end); note; note = XEXP (note, 1))
174 if (REG_NOTE_KIND (note) == REG_BR_PRED
175 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
176 return true;
177 return false;
180 void
181 predict_insn (insn, predictor, probability)
182 rtx insn;
183 int probability;
184 enum br_predictor predictor;
186 if (!any_condjump_p (insn))
187 abort ();
189 REG_NOTES (insn)
190 = gen_rtx_EXPR_LIST (REG_BR_PRED,
191 gen_rtx_CONCAT (VOIDmode,
192 GEN_INT ((int) predictor),
193 GEN_INT ((int) probability)),
194 REG_NOTES (insn));
197 /* Predict insn by given predictor. */
199 void
200 predict_insn_def (insn, predictor, taken)
201 rtx insn;
202 enum br_predictor predictor;
203 enum prediction taken;
205 int probability = predictor_info[(int) predictor].hitrate;
207 if (taken != TAKEN)
208 probability = REG_BR_PROB_BASE - probability;
210 predict_insn (insn, predictor, probability);
213 /* Predict edge E with given probability if possible. */
215 void
216 predict_edge (e, predictor, probability)
217 edge e;
218 int probability;
219 enum br_predictor predictor;
221 rtx last_insn;
222 last_insn = e->src->end;
224 /* We can store the branch prediction information only about
225 conditional jumps. */
226 if (!any_condjump_p (last_insn))
227 return;
229 /* We always store probability of branching. */
230 if (e->flags & EDGE_FALLTHRU)
231 probability = REG_BR_PROB_BASE - probability;
233 predict_insn (last_insn, predictor, probability);
236 /* Predict edge E by given predictor if possible. */
238 void
239 predict_edge_def (e, predictor, taken)
240 edge e;
241 enum br_predictor predictor;
242 enum prediction taken;
244 int probability = predictor_info[(int) predictor].hitrate;
246 if (taken != TAKEN)
247 probability = REG_BR_PROB_BASE - probability;
249 predict_edge (e, predictor, probability);
252 /* Invert all branch predictions or probability notes in the INSN. This needs
253 to be done each time we invert the condition used by the jump. */
255 void
256 invert_br_probabilities (insn)
257 rtx insn;
259 rtx note;
261 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
262 if (REG_NOTE_KIND (note) == REG_BR_PROB)
263 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
264 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
265 XEXP (XEXP (note, 0), 1)
266 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
269 /* Dump information about the branch prediction to the output file. */
271 static void
272 dump_prediction (predictor, probability, bb, used)
273 enum br_predictor predictor;
274 int probability;
275 basic_block bb;
276 int used;
278 edge e = bb->succ;
280 if (!rtl_dump_file)
281 return;
283 while (e && (e->flags & EDGE_FALLTHRU))
284 e = e->succ_next;
286 fprintf (rtl_dump_file, " %s heuristics%s: %.1f%%",
287 predictor_info[predictor].name,
288 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
290 if (bb->count)
292 fprintf (rtl_dump_file, " exec ");
293 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
294 if (e)
296 fprintf (rtl_dump_file, " hit ");
297 fprintf (rtl_dump_file, HOST_WIDEST_INT_PRINT_DEC, e->count);
298 fprintf (rtl_dump_file, " (%.1f%%)", e->count * 100.0 / bb->count);
302 fprintf (rtl_dump_file, "\n");
305 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
306 note if not already present. Remove now useless REG_BR_PRED notes. */
308 static void
309 combine_predictions_for_insn (insn, bb)
310 rtx insn;
311 basic_block bb;
313 rtx prob_note = find_reg_note (insn, REG_BR_PROB, 0);
314 rtx *pnote = &REG_NOTES (insn);
315 rtx note;
316 int best_probability = PROB_EVEN;
317 int best_predictor = END_PREDICTORS;
318 int combined_probability = REG_BR_PROB_BASE / 2;
319 int d;
320 bool first_match = false;
321 bool found = false;
323 if (rtl_dump_file)
324 fprintf (rtl_dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
325 bb->index);
327 /* We implement "first match" heuristics and use probability guessed
328 by predictor with smallest index. In the future we will use better
329 probability combination techniques. */
330 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
331 if (REG_NOTE_KIND (note) == REG_BR_PRED)
333 int predictor = INTVAL (XEXP (XEXP (note, 0), 0));
334 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
336 found = true;
337 if (best_predictor > predictor)
338 best_probability = probability, best_predictor = predictor;
340 d = (combined_probability * probability
341 + (REG_BR_PROB_BASE - combined_probability)
342 * (REG_BR_PROB_BASE - probability));
344 /* Use FP math to avoid overflows of 32bit integers. */
345 if (d == 0)
346 /* If one probability is 0% and one 100%, avoid division by zero. */
347 combined_probability = REG_BR_PROB_BASE / 2;
348 else
349 combined_probability = (((double) combined_probability) * probability
350 * REG_BR_PROB_BASE / d + 0.5);
353 /* Decide which heuristic to use. In case we didn't match anything,
354 use no_prediction heuristic, in case we did match, use either
355 first match or Dempster-Shaffer theory depending on the flags. */
357 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
358 first_match = true;
360 if (!found)
361 dump_prediction (PRED_NO_PREDICTION, combined_probability, bb, true);
362 else
364 dump_prediction (PRED_DS_THEORY, combined_probability, bb, !first_match);
365 dump_prediction (PRED_FIRST_MATCH, best_probability, bb, first_match);
368 if (first_match)
369 combined_probability = best_probability;
370 dump_prediction (PRED_COMBINED, combined_probability, bb, true);
372 while (*pnote)
374 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
376 int predictor = INTVAL (XEXP (XEXP (*pnote, 0), 0));
377 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
379 dump_prediction (predictor, probability, bb,
380 !first_match || best_predictor == predictor);
381 *pnote = XEXP (*pnote, 1);
383 else
384 pnote = &XEXP (*pnote, 1);
387 if (!prob_note)
389 REG_NOTES (insn)
390 = gen_rtx_EXPR_LIST (REG_BR_PROB,
391 GEN_INT (combined_probability), REG_NOTES (insn));
393 /* Save the prediction into CFG in case we are seeing non-degenerated
394 conditional jump. */
395 if (bb->succ->succ_next)
397 BRANCH_EDGE (bb)->probability = combined_probability;
398 FALLTHRU_EDGE (bb)->probability
399 = REG_BR_PROB_BASE - combined_probability;
404 /* Statically estimate the probability that a branch will be taken.
405 ??? In the next revision there will be a number of other predictors added
406 from the above references. Further, each heuristic will be factored out
407 into its own function for clarity (and to facilitate the combination of
408 predictions). */
410 void
411 estimate_probability (loops_info)
412 struct loops *loops_info;
414 dominance_info dominators, post_dominators;
415 basic_block bb;
416 int i;
418 connect_infinite_loops_to_exit ();
419 dominators = calculate_dominance_info (CDI_DOMINATORS);
420 post_dominators = calculate_dominance_info (CDI_POST_DOMINATORS);
422 /* Try to predict out blocks in a loop that are not part of a
423 natural loop. */
424 for (i = 1; i < loops_info->num; i++)
426 basic_block bb, *bbs;
427 int j;
428 int exits;
429 struct loop *loop = loops_info->parray[i];
431 flow_loop_scan (loops_info, loop, LOOP_EXIT_EDGES);
432 exits = loop->num_exits;
434 bbs = get_loop_body (loop);
435 for (j = 0; j < loop->num_nodes; j++)
437 int header_found = 0;
438 edge e;
440 bb = bbs[j];
442 /* Bypass loop heuristics on continue statement. These
443 statements construct loops via "non-loop" constructs
444 in the source language and are better to be handled
445 separately. */
446 if (predicted_by_p (bb, PRED_CONTINUE))
447 continue;
449 /* Loop branch heuristics - predict an edge back to a
450 loop's head as taken. */
451 for (e = bb->succ; e; e = e->succ_next)
452 if (e->dest == loop->header
453 && e->src == loop->latch)
455 header_found = 1;
456 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
459 /* Loop exit heuristics - predict an edge exiting the loop if the
460 conditinal has no loop header successors as not taken. */
461 if (!header_found)
462 for (e = bb->succ; e; e = e->succ_next)
463 if (e->dest->index < 0
464 || !flow_bb_inside_loop_p (loop, e->dest))
465 predict_edge
466 (e, PRED_LOOP_EXIT,
467 (REG_BR_PROB_BASE
468 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
469 / exits);
473 /* Attempt to predict conditional jumps using a number of heuristics. */
474 FOR_EACH_BB (bb)
476 rtx last_insn = bb->end;
477 rtx cond, earliest;
478 edge e;
480 if (GET_CODE (last_insn) != JUMP_INSN || ! any_condjump_p (last_insn))
481 continue;
483 for (e = bb->succ; e; e = e->succ_next)
485 /* Predict early returns to be probable, as we've already taken
486 care for error returns and other are often used for fast paths
487 trought function. */
488 if ((e->dest == EXIT_BLOCK_PTR
489 || (e->dest->succ && !e->dest->succ->succ_next
490 && e->dest->succ->dest == EXIT_BLOCK_PTR))
491 && !predicted_by_p (bb, PRED_NULL_RETURN)
492 && !predicted_by_p (bb, PRED_CONST_RETURN)
493 && !predicted_by_p (bb, PRED_NEGATIVE_RETURN)
494 && !last_basic_block_p (e->dest))
495 predict_edge_def (e, PRED_EARLY_RETURN, TAKEN);
497 /* Look for block we are guarding (ie we dominate it,
498 but it doesn't postdominate us). */
499 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
500 && dominated_by_p (dominators, e->dest, e->src)
501 && !dominated_by_p (post_dominators, e->src, e->dest))
503 rtx insn;
505 /* The call heuristic claims that a guarded function call
506 is improbable. This is because such calls are often used
507 to signal exceptional situations such as printing error
508 messages. */
509 for (insn = e->dest->head; insn != NEXT_INSN (e->dest->end);
510 insn = NEXT_INSN (insn))
511 if (GET_CODE (insn) == CALL_INSN
512 /* Constant and pure calls are hardly used to signalize
513 something exceptional. */
514 && ! CONST_OR_PURE_CALL_P (insn))
516 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
517 break;
522 cond = get_condition (last_insn, &earliest);
523 if (! cond)
524 continue;
526 /* Try "pointer heuristic."
527 A comparison ptr == 0 is predicted as false.
528 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
529 if (GET_RTX_CLASS (GET_CODE (cond)) == '<'
530 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
531 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
533 if (GET_CODE (cond) == EQ)
534 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
535 else if (GET_CODE (cond) == NE)
536 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
538 else
540 /* Try "opcode heuristic."
541 EQ tests are usually false and NE tests are usually true. Also,
542 most quantities are positive, so we can make the appropriate guesses
543 about signed comparisons against zero. */
544 switch (GET_CODE (cond))
546 case CONST_INT:
547 /* Unconditional branch. */
548 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
549 cond == const0_rtx ? NOT_TAKEN : TAKEN);
550 break;
552 case EQ:
553 case UNEQ:
554 /* Floating point comparisons appears to behave in a very
555 inpredictable way because of special role of = tests in
556 FP code. */
557 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
559 /* Comparisons with 0 are often used for booleans and there is
560 nothing usefull to predict about them. */
561 else if (XEXP (cond, 1) == const0_rtx
562 || XEXP (cond, 0) == const0_rtx)
564 else
565 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
566 break;
568 case NE:
569 case LTGT:
570 /* Floating point comparisons appears to behave in a very
571 inpredictable way because of special role of = tests in
572 FP code. */
573 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
575 /* Comparisons with 0 are often used for booleans and there is
576 nothing usefull to predict about them. */
577 else if (XEXP (cond, 1) == const0_rtx
578 || XEXP (cond, 0) == const0_rtx)
580 else
581 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
582 break;
584 case ORDERED:
585 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
586 break;
588 case UNORDERED:
589 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
590 break;
592 case LE:
593 case LT:
594 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
595 || XEXP (cond, 1) == constm1_rtx)
596 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
597 break;
599 case GE:
600 case GT:
601 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
602 || XEXP (cond, 1) == constm1_rtx)
603 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
604 break;
606 default:
607 break;
611 /* Attach the combined probability to each conditional jump. */
612 FOR_EACH_BB (bb)
613 if (GET_CODE (bb->end) == JUMP_INSN
614 && any_condjump_p (bb->end)
615 && bb->succ->succ_next != NULL)
616 combine_predictions_for_insn (bb->end, bb);
618 free_dominance_info (post_dominators);
619 free_dominance_info (dominators);
621 remove_fake_edges ();
622 estimate_bb_frequencies (loops_info);
625 /* __builtin_expect dropped tokens into the insn stream describing expected
626 values of registers. Generate branch probabilities based off these
627 values. */
629 void
630 expected_value_to_br_prob ()
632 rtx insn, cond, ev = NULL_RTX, ev_reg = NULL_RTX;
634 for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
636 switch (GET_CODE (insn))
638 case NOTE:
639 /* Look for expected value notes. */
640 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_EXPECTED_VALUE)
642 ev = NOTE_EXPECTED_VALUE (insn);
643 ev_reg = XEXP (ev, 0);
644 delete_insn (insn);
646 continue;
648 case CODE_LABEL:
649 /* Never propagate across labels. */
650 ev = NULL_RTX;
651 continue;
653 case JUMP_INSN:
654 /* Look for simple conditional branches. If we haven't got an
655 expected value yet, no point going further. */
656 if (GET_CODE (insn) != JUMP_INSN || ev == NULL_RTX
657 || ! any_condjump_p (insn))
658 continue;
659 break;
661 default:
662 /* Look for insns that clobber the EV register. */
663 if (ev && reg_set_p (ev_reg, insn))
664 ev = NULL_RTX;
665 continue;
668 /* Collect the branch condition, hopefully relative to EV_REG. */
669 /* ??? At present we'll miss things like
670 (expected_value (eq r70 0))
671 (set r71 -1)
672 (set r80 (lt r70 r71))
673 (set pc (if_then_else (ne r80 0) ...))
674 as canonicalize_condition will render this to us as
675 (lt r70, r71)
676 Could use cselib to try and reduce this further. */
677 cond = XEXP (SET_SRC (pc_set (insn)), 0);
678 cond = canonicalize_condition (insn, cond, 0, NULL, ev_reg);
679 if (! cond || XEXP (cond, 0) != ev_reg
680 || GET_CODE (XEXP (cond, 1)) != CONST_INT)
681 continue;
683 /* Substitute and simplify. Given that the expression we're
684 building involves two constants, we should wind up with either
685 true or false. */
686 cond = gen_rtx_fmt_ee (GET_CODE (cond), VOIDmode,
687 XEXP (ev, 1), XEXP (cond, 1));
688 cond = simplify_rtx (cond);
690 /* Turn the condition into a scaled branch probability. */
691 if (cond != const_true_rtx && cond != const0_rtx)
692 abort ();
693 predict_insn_def (insn, PRED_BUILTIN_EXPECT,
694 cond == const_true_rtx ? TAKEN : NOT_TAKEN);
698 /* Check whether this is the last basic block of function. Commonly tehre
699 is one extra common cleanup block. */
700 static bool
701 last_basic_block_p (bb)
702 basic_block bb;
704 if (bb == EXIT_BLOCK_PTR)
705 return false;
707 return (bb->next_bb == EXIT_BLOCK_PTR
708 || (bb->next_bb->next_bb == EXIT_BLOCK_PTR
709 && bb->succ && !bb->succ->succ_next
710 && bb->succ->dest->next_bb == EXIT_BLOCK_PTR));
713 /* Sets branch probabilities according to PREDiction and FLAGS. HEADS[bb->index]
714 should be index of basic block in that we need to alter branch predictions
715 (i.e. the first of our dominators such that we do not post-dominate it)
716 (but we fill this information on demand, so -1 may be there in case this
717 was not needed yet). */
719 static void
720 process_note_prediction (bb, heads, dominators, post_dominators, pred, flags)
721 basic_block bb;
722 int *heads;
723 dominance_info dominators;
724 dominance_info post_dominators;
725 int pred;
726 int flags;
728 edge e;
729 int y;
730 bool taken;
732 taken = flags & IS_TAKEN;
734 if (heads[bb->index] < 0)
736 /* This is first time we need this field in heads array; so
737 find first dominator that we do not post-dominate (we are
738 using already known members of heads array). */
739 basic_block ai = bb;
740 basic_block next_ai = get_immediate_dominator (dominators, bb);
741 int head;
743 while (heads[next_ai->index] < 0)
745 if (!dominated_by_p (post_dominators, next_ai, bb))
746 break;
747 heads[next_ai->index] = ai->index;
748 ai = next_ai;
749 next_ai = get_immediate_dominator (dominators, next_ai);
751 if (!dominated_by_p (post_dominators, next_ai, bb))
752 head = next_ai->index;
753 else
754 head = heads[next_ai->index];
755 while (next_ai != bb)
757 next_ai = ai;
758 if (heads[ai->index] == ENTRY_BLOCK)
759 ai = ENTRY_BLOCK_PTR;
760 else
761 ai = BASIC_BLOCK (heads[ai->index]);
762 heads[next_ai->index] = head;
765 y = heads[bb->index];
767 /* Now find the edge that leads to our branch and aply the prediction. */
769 if (y == last_basic_block)
770 return;
771 for (e = BASIC_BLOCK (y)->succ; e; e = e->succ_next)
772 if (e->dest->index >= 0
773 && dominated_by_p (post_dominators, e->dest, bb))
774 predict_edge_def (e, pred, taken);
777 /* Gathers NOTE_INSN_PREDICTIONs in given basic block and turns them
778 into branch probabilities. For description of heads array, see
779 process_note_prediction. */
781 static void
782 process_note_predictions (bb, heads, dominators, post_dominators)
783 basic_block bb;
784 int *heads;
785 dominance_info dominators;
786 dominance_info post_dominators;
788 rtx insn;
789 edge e;
791 /* Additionaly, we check here for blocks with no successors. */
792 int contained_noreturn_call = 0;
793 int was_bb_head = 0;
794 int noreturn_block = 1;
796 for (insn = bb->end; insn;
797 was_bb_head |= (insn == bb->head), insn = PREV_INSN (insn))
799 if (GET_CODE (insn) != NOTE)
801 if (was_bb_head)
802 break;
803 else
805 /* Noreturn calls cause program to exit, therefore they are
806 always predicted as not taken. */
807 if (GET_CODE (insn) == CALL_INSN
808 && find_reg_note (insn, REG_NORETURN, NULL))
809 contained_noreturn_call = 1;
810 continue;
813 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_PREDICTION)
815 int alg = (int) NOTE_PREDICTION_ALG (insn);
816 /* Process single prediction note. */
817 process_note_prediction (bb,
818 heads,
819 dominators,
820 post_dominators,
821 alg, (int) NOTE_PREDICTION_FLAGS (insn));
822 delete_insn (insn);
825 for (e = bb->succ; e; e = e->succ_next)
826 if (!(e->flags & EDGE_FAKE))
827 noreturn_block = 0;
828 if (contained_noreturn_call)
830 /* This block ended from other reasons than because of return.
831 If it is because of noreturn call, this should certainly not
832 be taken. Otherwise it is probably some error recovery. */
833 process_note_prediction (bb,
834 heads,
835 dominators,
836 post_dominators, PRED_NORETURN, NOT_TAKEN);
840 /* Gathers NOTE_INSN_PREDICTIONs and turns them into
841 branch probabilities. */
843 void
844 note_prediction_to_br_prob ()
846 basic_block bb;
847 dominance_info post_dominators, dominators;
848 int *heads;
850 /* To enable handling of noreturn blocks. */
851 add_noreturn_fake_exit_edges ();
852 connect_infinite_loops_to_exit ();
854 post_dominators = calculate_dominance_info (CDI_POST_DOMINATORS);
855 dominators = calculate_dominance_info (CDI_DOMINATORS);
857 heads = xmalloc (sizeof (int) * last_basic_block);
858 memset (heads, -1, sizeof (int) * last_basic_block);
859 heads[ENTRY_BLOCK_PTR->next_bb->index] = last_basic_block;
861 /* Process all prediction notes. */
863 FOR_EACH_BB (bb)
864 process_note_predictions (bb, heads, dominators, post_dominators);
866 free_dominance_info (post_dominators);
867 free_dominance_info (dominators);
868 free (heads);
870 remove_fake_edges ();
873 /* This is used to carry information about basic blocks. It is
874 attached to the AUX field of the standard CFG block. */
876 typedef struct block_info_def
878 /* Estimated frequency of execution of basic_block. */
879 REAL_VALUE_TYPE frequency;
881 /* To keep queue of basic blocks to process. */
882 basic_block next;
884 /* True if block needs to be visited in prop_freqency. */
885 int tovisit:1;
887 /* Number of predecessors we need to visit first. */
888 int npredecessors;
889 } *block_info;
891 /* Similar information for edges. */
892 typedef struct edge_info_def
894 /* In case edge is an loopback edge, the probability edge will be reached
895 in case header is. Estimated number of iterations of the loop can be
896 then computed as 1 / (1 - back_edge_prob). */
897 REAL_VALUE_TYPE back_edge_prob;
898 /* True if the edge is an loopback edge in the natural loop. */
899 int back_edge:1;
900 } *edge_info;
902 #define BLOCK_INFO(B) ((block_info) (B)->aux)
903 #define EDGE_INFO(E) ((edge_info) (E)->aux)
905 /* Helper function for estimate_bb_frequencies.
906 Propagate the frequencies for LOOP. */
908 static void
909 propagate_freq (loop)
910 struct loop *loop;
912 basic_block head = loop->header;
913 basic_block bb;
914 basic_block last;
915 edge e;
916 basic_block nextbb;
918 /* For each basic block we need to visit count number of his predecessors
919 we need to visit first. */
920 FOR_EACH_BB (bb)
922 if (BLOCK_INFO (bb)->tovisit)
924 int count = 0;
926 for (e = bb->pred; e; e = e->pred_next)
927 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
928 count++;
929 else if (BLOCK_INFO (e->src)->tovisit
930 && rtl_dump_file && !EDGE_INFO (e)->back_edge)
931 fprintf (rtl_dump_file,
932 "Irreducible region hit, ignoring edge to %i->%i\n",
933 e->src->index, bb->index);
934 BLOCK_INFO (bb)->npredecessors = count;
938 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
939 last = head;
940 for (bb = head; bb; bb = nextbb)
942 REAL_VALUE_TYPE cyclic_probability, frequency;
944 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
945 memcpy (&frequency, &real_zero, sizeof (real_zero));
947 nextbb = BLOCK_INFO (bb)->next;
948 BLOCK_INFO (bb)->next = NULL;
950 /* Compute frequency of basic block. */
951 if (bb != head)
953 #ifdef ENABLE_CHECKING
954 for (e = bb->pred; e; e = e->pred_next)
955 if (BLOCK_INFO (e->src)->tovisit && !(e->flags & EDGE_DFS_BACK))
956 abort ();
957 #endif
959 for (e = bb->pred; e; e = e->pred_next)
960 if (EDGE_INFO (e)->back_edge)
962 REAL_ARITHMETIC (cyclic_probability, PLUS_EXPR,
963 cyclic_probability,
964 EDGE_INFO (e)->back_edge_prob);
966 else if (!(e->flags & EDGE_DFS_BACK))
968 REAL_VALUE_TYPE tmp;
970 /* frequency += (e->probability
971 * BLOCK_INFO (e->src)->frequency /
972 REG_BR_PROB_BASE); */
974 REAL_VALUE_FROM_INT (tmp, e->probability, 0,
975 TYPE_MODE (double_type_node));
976 REAL_ARITHMETIC (tmp, MULT_EXPR, tmp,
977 BLOCK_INFO (e->src)->frequency);
978 REAL_ARITHMETIC (tmp, RDIV_EXPR, tmp, real_br_prob_base);
979 REAL_ARITHMETIC (frequency, PLUS_EXPR, frequency, tmp);
982 if (REAL_VALUES_LESS (real_almost_one, cyclic_probability))
983 memcpy (&cyclic_probability, &real_almost_one, sizeof (real_zero));
985 /* BLOCK_INFO (bb)->frequency = frequency / (1 - cyclic_probability)
988 REAL_ARITHMETIC (cyclic_probability, MINUS_EXPR, real_one,
989 cyclic_probability);
990 REAL_ARITHMETIC (BLOCK_INFO (bb)->frequency,
991 RDIV_EXPR, frequency, cyclic_probability);
994 BLOCK_INFO (bb)->tovisit = 0;
996 /* Compute back edge frequencies. */
997 for (e = bb->succ; e; e = e->succ_next)
998 if (e->dest == head)
1000 REAL_VALUE_TYPE tmp;
1002 /* EDGE_INFO (e)->back_edge_prob
1003 = ((e->probability * BLOCK_INFO (bb)->frequency)
1004 / REG_BR_PROB_BASE); */
1005 REAL_VALUE_FROM_INT (tmp, e->probability, 0,
1006 TYPE_MODE (double_type_node));
1007 REAL_ARITHMETIC (tmp, MULT_EXPR, tmp,
1008 BLOCK_INFO (bb)->frequency);
1009 REAL_ARITHMETIC (EDGE_INFO (e)->back_edge_prob,
1010 RDIV_EXPR, tmp, real_br_prob_base);
1014 /* Propagate to successor blocks. */
1015 for (e = bb->succ; e; e = e->succ_next)
1016 if (!(e->flags & EDGE_DFS_BACK)
1017 && BLOCK_INFO (e->dest)->npredecessors)
1019 BLOCK_INFO (e->dest)->npredecessors--;
1020 if (!BLOCK_INFO (e->dest)->npredecessors)
1022 if (!nextbb)
1023 nextbb = e->dest;
1024 else
1025 BLOCK_INFO (last)->next = e->dest;
1027 last = e->dest;
1033 /* Estimate probabilities of loopback edges in loops at same nest level. */
1035 static void
1036 estimate_loops_at_level (first_loop)
1037 struct loop *first_loop;
1039 struct loop *loop;
1041 for (loop = first_loop; loop; loop = loop->next)
1043 edge e;
1044 basic_block *bbs;
1045 int i;
1047 estimate_loops_at_level (loop->inner);
1049 if (loop->latch->succ) /* Do not do this for dummy function loop. */
1051 /* Find current loop back edge and mark it. */
1052 e = loop_latch_edge (loop);
1053 EDGE_INFO (e)->back_edge = 1;
1056 bbs = get_loop_body (loop);
1057 for (i = 0; i < loop->num_nodes; i++)
1058 BLOCK_INFO (bbs[i])->tovisit = 1;
1059 free (bbs);
1060 propagate_freq (loop);
1064 /* Convert counts measured by profile driven feedback to frequencies. */
1066 static void
1067 counts_to_freqs ()
1069 HOST_WIDEST_INT count_max = 1;
1070 basic_block bb;
1072 FOR_EACH_BB (bb)
1073 count_max = MAX (bb->count, count_max);
1075 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1076 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
1079 /* Return true if function is likely to be expensive, so there is no point to
1080 optimize performance of prologue, epilogue or do inlining at the expense
1081 of code size growth. THRESHOLD is the limit of number of isntructions
1082 function can execute at average to be still considered not expensive. */
1084 bool
1085 expensive_function_p (threshold)
1086 int threshold;
1088 unsigned int sum = 0;
1089 basic_block bb;
1090 unsigned int limit;
1092 /* We can not compute accurately for large thresholds due to scaled
1093 frequencies. */
1094 if (threshold > BB_FREQ_MAX)
1095 abort ();
1097 /* Frequencies are out of range. This either means that function contains
1098 internal loop executing more than BB_FREQ_MAX times or profile feedback
1099 is available and function has not been executed at all. */
1100 if (ENTRY_BLOCK_PTR->frequency == 0)
1101 return true;
1103 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
1104 limit = ENTRY_BLOCK_PTR->frequency * threshold;
1105 FOR_EACH_BB (bb)
1107 rtx insn;
1109 for (insn = bb->head; insn != NEXT_INSN (bb->end);
1110 insn = NEXT_INSN (insn))
1111 if (active_insn_p (insn))
1113 sum += bb->frequency;
1114 if (sum > limit)
1115 return true;
1119 return false;
1122 /* Estimate basic blocks frequency by given branch probabilities. */
1124 static void
1125 estimate_bb_frequencies (loops)
1126 struct loops *loops;
1128 basic_block bb;
1129 REAL_VALUE_TYPE freq_max;
1130 enum machine_mode double_mode = TYPE_MODE (double_type_node);
1132 if (flag_branch_probabilities)
1133 counts_to_freqs ();
1134 else
1136 REAL_VALUE_FROM_INT (real_zero, 0, 0, double_mode);
1137 REAL_VALUE_FROM_INT (real_one, 1, 0, double_mode);
1138 REAL_VALUE_FROM_INT (real_br_prob_base, REG_BR_PROB_BASE, 0, double_mode);
1139 REAL_VALUE_FROM_INT (real_bb_freq_max, BB_FREQ_MAX, 0, double_mode);
1140 REAL_VALUE_FROM_INT (real_one_half, 2, 0, double_mode);
1142 REAL_ARITHMETIC (real_one_half, RDIV_EXPR, real_one, real_one_half);
1144 REAL_ARITHMETIC (real_almost_one, RDIV_EXPR, real_one, real_br_prob_base);
1145 REAL_ARITHMETIC (real_almost_one, MINUS_EXPR, real_one, real_almost_one);
1147 mark_dfs_back_edges ();
1148 /* Fill in the probability values in flowgraph based on the REG_BR_PROB
1149 notes. */
1150 FOR_EACH_BB (bb)
1152 rtx last_insn = bb->end;
1154 if (GET_CODE (last_insn) != JUMP_INSN || !any_condjump_p (last_insn)
1155 /* Avoid handling of conditional jumps jumping to fallthru edge. */
1156 || bb->succ->succ_next == NULL)
1158 /* We can predict only conditional jumps at the moment.
1159 Expect each edge to be equally probable.
1160 ?? In the future we want to make abnormal edges improbable. */
1161 int nedges = 0;
1162 edge e;
1164 for (e = bb->succ; e; e = e->succ_next)
1166 nedges++;
1167 if (e->probability != 0)
1168 break;
1170 if (!e)
1171 for (e = bb->succ; e; e = e->succ_next)
1172 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
1176 ENTRY_BLOCK_PTR->succ->probability = REG_BR_PROB_BASE;
1178 /* Set up block info for each basic block. */
1179 alloc_aux_for_blocks (sizeof (struct block_info_def));
1180 alloc_aux_for_edges (sizeof (struct edge_info_def));
1181 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1183 edge e;
1185 BLOCK_INFO (bb)->tovisit = 0;
1186 for (e = bb->succ; e; e = e->succ_next)
1188 REAL_VALUE_FROM_INT (EDGE_INFO (e)->back_edge_prob,
1189 e->probability, 0, double_mode);
1190 REAL_ARITHMETIC (EDGE_INFO (e)->back_edge_prob,
1191 RDIV_EXPR, EDGE_INFO (e)->back_edge_prob,
1192 real_br_prob_base);
1196 /* First compute probabilities locally for each loop from innermost
1197 to outermost to examine probabilities for back edges. */
1198 estimate_loops_at_level (loops->tree_root);
1200 memcpy (&freq_max, &real_zero, sizeof (real_zero));
1201 FOR_EACH_BB (bb)
1202 if (REAL_VALUES_LESS
1203 (freq_max, BLOCK_INFO (bb)->frequency))
1204 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency,
1205 sizeof (freq_max));
1207 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
1209 REAL_VALUE_TYPE tmp;
1211 REAL_ARITHMETIC (tmp, MULT_EXPR, BLOCK_INFO (bb)->frequency,
1212 real_bb_freq_max);
1213 REAL_ARITHMETIC (tmp, RDIV_EXPR, tmp, freq_max);
1214 REAL_ARITHMETIC (tmp, PLUS_EXPR, tmp, real_one_half);
1215 bb->frequency = REAL_VALUE_UNSIGNED_FIX (tmp);
1218 free_aux_for_blocks ();
1219 free_aux_for_edges ();
1221 compute_function_frequency ();
1222 if (flag_reorder_functions)
1223 choose_function_section ();
1226 /* Decide whether function is hot, cold or unlikely executed. */
1227 static void
1228 compute_function_frequency ()
1230 basic_block bb;
1232 if (!profile_info.count_profiles_merged
1233 || !flag_branch_probabilities)
1234 return;
1235 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
1236 FOR_EACH_BB (bb)
1238 if (maybe_hot_bb_p (bb))
1240 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
1241 return;
1243 if (!probably_never_executed_bb_p (bb))
1244 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
1248 /* Choose appropriate section for the function. */
1249 static void
1250 choose_function_section ()
1252 if (DECL_SECTION_NAME (current_function_decl)
1253 || !targetm.have_named_sections)
1254 return;
1255 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
1256 DECL_SECTION_NAME (current_function_decl) =
1257 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
1258 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
1259 DECL_SECTION_NAME (current_function_decl) =
1260 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
1261 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);