Recompute profile after Graphite.
[gcc.git] / gcc / predict.c
1 /* Branch prediction routines for the GNU compiler.
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
3 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 /* References:
22
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. */
29
30
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 "coverage.h"
51 #include "sreal.h"
52 #include "params.h"
53 #include "target.h"
54 #include "cfgloop.h"
55 #include "tree-flow.h"
56 #include "ggc.h"
57 #include "tree-dump.h"
58 #include "tree-pass.h"
59 #include "timevar.h"
60 #include "tree-scalar-evolution.h"
61 #include "cfgloop.h"
62 #include "pointer-set.h"
63
64 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
65 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
66 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
67 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
68
69 /* Random guesstimation given names.
70 PROV_VERY_UNLIKELY should be small enough so basic block predicted
71 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
72 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
73 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
74 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
75 #define PROB_ALWAYS (REG_BR_PROB_BASE)
76
77 static void combine_predictions_for_insn (rtx, basic_block);
78 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
79 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
80 static void compute_function_frequency (void);
81 static void choose_function_section (void);
82 static bool can_predict_insn_p (const_rtx);
83
84 /* Information we hold about each branch predictor.
85 Filled using information from predict.def. */
86
87 struct predictor_info
88 {
89 const char *const name; /* Name used in the debugging dumps. */
90 const int hitrate; /* Expected hitrate used by
91 predict_insn_def call. */
92 const int flags;
93 };
94
95 /* Use given predictor without Dempster-Shaffer theory if it matches
96 using first_match heuristics. */
97 #define PRED_FLAG_FIRST_MATCH 1
98
99 /* Recompute hitrate in percent to our representation. */
100
101 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
102
103 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
104 static const struct predictor_info predictor_info[]= {
105 #include "predict.def"
106
107 /* Upper bound on predictors. */
108 {NULL, 0, 0}
109 };
110 #undef DEF_PREDICTOR
111
112 /* Return TRUE if frequency FREQ is considered to be hot. */
113
114 static inline bool
115 maybe_hot_frequency_p (int freq)
116 {
117 if (!profile_info || !flag_branch_probabilities)
118 {
119 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
120 return false;
121 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
122 return true;
123 }
124 if (profile_status == PROFILE_ABSENT)
125 return true;
126 if (freq < BB_FREQ_MAX / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION))
127 return false;
128 return true;
129 }
130
131 /* Return TRUE if frequency FREQ is considered to be hot. */
132
133 static inline bool
134 maybe_hot_count_p (gcov_type count)
135 {
136 if (profile_status != PROFILE_READ)
137 return true;
138 /* Code executed at most once is not hot. */
139 if (profile_info->runs >= count)
140 return false;
141 return (count
142 > profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION));
143 }
144
145 /* Return true in case BB can be CPU intensive and should be optimized
146 for maximal performance. */
147
148 bool
149 maybe_hot_bb_p (const_basic_block bb)
150 {
151 if (profile_status == PROFILE_READ)
152 return maybe_hot_count_p (bb->count);
153 return maybe_hot_frequency_p (bb->frequency);
154 }
155
156 /* Return true if the call can be hot. */
157
158 bool
159 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
160 {
161 if (profile_info && flag_branch_probabilities
162 && (edge->count
163 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
164 return false;
165 if (lookup_attribute ("cold", DECL_ATTRIBUTES (edge->callee->decl))
166 || lookup_attribute ("cold", DECL_ATTRIBUTES (edge->caller->decl)))
167 return false;
168 if (lookup_attribute ("hot", DECL_ATTRIBUTES (edge->caller->decl)))
169 return true;
170 if (flag_guess_branch_prob
171 && edge->frequency <= (CGRAPH_FREQ_BASE
172 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
173 return false;
174 return true;
175 }
176
177 /* Return true in case BB can be CPU intensive and should be optimized
178 for maximal performance. */
179
180 bool
181 maybe_hot_edge_p (edge e)
182 {
183 if (profile_status == PROFILE_READ)
184 return maybe_hot_count_p (e->count);
185 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
186 }
187
188 /* Return true in case BB is probably never executed. */
189 bool
190 probably_never_executed_bb_p (const_basic_block bb)
191 {
192 if (profile_info && flag_branch_probabilities)
193 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
194 if ((!profile_info || !flag_branch_probabilities)
195 && cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
196 return true;
197 return false;
198 }
199
200 /* Return true when current function should always be optimized for size. */
201
202 bool
203 optimize_function_for_size_p (struct function *fun)
204 {
205 return (optimize_size
206 || (fun && (fun->function_frequency
207 == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)));
208 }
209
210 /* Return true when current function should always be optimized for speed. */
211
212 bool
213 optimize_function_for_speed_p (struct function *fun)
214 {
215 return !optimize_function_for_size_p (fun);
216 }
217
218 /* Return TRUE when BB should be optimized for size. */
219
220 bool
221 optimize_bb_for_size_p (const_basic_block bb)
222 {
223 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
224 }
225
226 /* Return TRUE when BB should be optimized for speed. */
227
228 bool
229 optimize_bb_for_speed_p (const_basic_block bb)
230 {
231 return !optimize_bb_for_size_p (bb);
232 }
233
234 /* Return TRUE when BB should be optimized for size. */
235
236 bool
237 optimize_edge_for_size_p (edge e)
238 {
239 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
240 }
241
242 /* Return TRUE when BB should be optimized for speed. */
243
244 bool
245 optimize_edge_for_speed_p (edge e)
246 {
247 return !optimize_edge_for_size_p (e);
248 }
249
250 /* Return TRUE when BB should be optimized for size. */
251
252 bool
253 optimize_insn_for_size_p (void)
254 {
255 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
256 }
257
258 /* Return TRUE when BB should be optimized for speed. */
259
260 bool
261 optimize_insn_for_speed_p (void)
262 {
263 return !optimize_insn_for_size_p ();
264 }
265
266 /* Return TRUE when LOOP should be optimized for size. */
267
268 bool
269 optimize_loop_for_size_p (struct loop *loop)
270 {
271 return optimize_bb_for_size_p (loop->header);
272 }
273
274 /* Return TRUE when LOOP should be optimized for speed. */
275
276 bool
277 optimize_loop_for_speed_p (struct loop *loop)
278 {
279 return optimize_bb_for_speed_p (loop->header);
280 }
281
282 /* Return TRUE when LOOP nest should be optimized for speed. */
283
284 bool
285 optimize_loop_nest_for_speed_p (struct loop *loop)
286 {
287 struct loop *l = loop;
288 if (optimize_loop_for_speed_p (loop))
289 return true;
290 l = loop->inner;
291 while (l && l != loop)
292 {
293 if (optimize_loop_for_speed_p (l))
294 return true;
295 if (l->inner)
296 l = l->inner;
297 else if (l->next)
298 l = l->next;
299 else
300 {
301 while (l != loop && !l->next)
302 l = loop_outer (l);
303 if (l != loop)
304 l = l->next;
305 }
306 }
307 return false;
308 }
309
310 /* Return TRUE when LOOP nest should be optimized for size. */
311
312 bool
313 optimize_loop_nest_for_size_p (struct loop *loop)
314 {
315 return !optimize_loop_nest_for_speed_p (loop);
316 }
317
318 /* Return true when edge E is likely to be well predictable by branch
319 predictor. */
320
321 bool
322 predictable_edge_p (edge e)
323 {
324 if (profile_status == PROFILE_ABSENT)
325 return false;
326 if ((e->probability
327 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
328 || (REG_BR_PROB_BASE - e->probability
329 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
330 return true;
331 return false;
332 }
333
334
335 /* Set RTL expansion for BB profile. */
336
337 void
338 rtl_profile_for_bb (basic_block bb)
339 {
340 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
341 }
342
343 /* Set RTL expansion for edge profile. */
344
345 void
346 rtl_profile_for_edge (edge e)
347 {
348 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
349 }
350
351 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
352 void
353 default_rtl_profile (void)
354 {
355 crtl->maybe_hot_insn_p = true;
356 }
357
358 /* Return true if the one of outgoing edges is already predicted by
359 PREDICTOR. */
360
361 bool
362 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
363 {
364 rtx note;
365 if (!INSN_P (BB_END (bb)))
366 return false;
367 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
368 if (REG_NOTE_KIND (note) == REG_BR_PRED
369 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
370 return true;
371 return false;
372 }
373
374 /* This map contains for a basic block the list of predictions for the
375 outgoing edges. */
376
377 static struct pointer_map_t *bb_predictions;
378
379 /* Return true if the one of outgoing edges is already predicted by
380 PREDICTOR. */
381
382 bool
383 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
384 {
385 struct edge_prediction *i;
386 void **preds = pointer_map_contains (bb_predictions, bb);
387
388 if (!preds)
389 return false;
390
391 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
392 if (i->ep_predictor == predictor)
393 return true;
394 return false;
395 }
396
397 /* Return true when the probability of edge is reliable.
398
399 The profile guessing code is good at predicting branch outcome (ie.
400 taken/not taken), that is predicted right slightly over 75% of time.
401 It is however notoriously poor on predicting the probability itself.
402 In general the profile appear a lot flatter (with probabilities closer
403 to 50%) than the reality so it is bad idea to use it to drive optimization
404 such as those disabling dynamic branch prediction for well predictable
405 branches.
406
407 There are two exceptions - edges leading to noreturn edges and edges
408 predicted by number of iterations heuristics are predicted well. This macro
409 should be able to distinguish those, but at the moment it simply check for
410 noreturn heuristic that is only one giving probability over 99% or bellow
411 1%. In future we might want to propagate reliability information across the
412 CFG if we find this information useful on multiple places. */
413 static bool
414 probability_reliable_p (int prob)
415 {
416 return (profile_status == PROFILE_READ
417 || (profile_status == PROFILE_GUESSED
418 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
419 }
420
421 /* Same predicate as above, working on edges. */
422 bool
423 edge_probability_reliable_p (const_edge e)
424 {
425 return probability_reliable_p (e->probability);
426 }
427
428 /* Same predicate as edge_probability_reliable_p, working on notes. */
429 bool
430 br_prob_note_reliable_p (const_rtx note)
431 {
432 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
433 return probability_reliable_p (INTVAL (XEXP (note, 0)));
434 }
435
436 static void
437 predict_insn (rtx insn, enum br_predictor predictor, int probability)
438 {
439 gcc_assert (any_condjump_p (insn));
440 if (!flag_guess_branch_prob)
441 return;
442
443 add_reg_note (insn, REG_BR_PRED,
444 gen_rtx_CONCAT (VOIDmode,
445 GEN_INT ((int) predictor),
446 GEN_INT ((int) probability)));
447 }
448
449 /* Predict insn by given predictor. */
450
451 void
452 predict_insn_def (rtx insn, enum br_predictor predictor,
453 enum prediction taken)
454 {
455 int probability = predictor_info[(int) predictor].hitrate;
456
457 if (taken != TAKEN)
458 probability = REG_BR_PROB_BASE - probability;
459
460 predict_insn (insn, predictor, probability);
461 }
462
463 /* Predict edge E with given probability if possible. */
464
465 void
466 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
467 {
468 rtx last_insn;
469 last_insn = BB_END (e->src);
470
471 /* We can store the branch prediction information only about
472 conditional jumps. */
473 if (!any_condjump_p (last_insn))
474 return;
475
476 /* We always store probability of branching. */
477 if (e->flags & EDGE_FALLTHRU)
478 probability = REG_BR_PROB_BASE - probability;
479
480 predict_insn (last_insn, predictor, probability);
481 }
482
483 /* Predict edge E with the given PROBABILITY. */
484 void
485 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
486 {
487 gcc_assert (profile_status != PROFILE_GUESSED);
488 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
489 && flag_guess_branch_prob && optimize)
490 {
491 struct edge_prediction *i = XNEW (struct edge_prediction);
492 void **preds = pointer_map_insert (bb_predictions, e->src);
493
494 i->ep_next = (struct edge_prediction *) *preds;
495 *preds = i;
496 i->ep_probability = probability;
497 i->ep_predictor = predictor;
498 i->ep_edge = e;
499 }
500 }
501
502 /* Remove all predictions on given basic block that are attached
503 to edge E. */
504 void
505 remove_predictions_associated_with_edge (edge e)
506 {
507 void **preds;
508
509 if (!bb_predictions)
510 return;
511
512 preds = pointer_map_contains (bb_predictions, e->src);
513
514 if (preds)
515 {
516 struct edge_prediction **prediction = (struct edge_prediction **) preds;
517 struct edge_prediction *next;
518
519 while (*prediction)
520 {
521 if ((*prediction)->ep_edge == e)
522 {
523 next = (*prediction)->ep_next;
524 free (*prediction);
525 *prediction = next;
526 }
527 else
528 prediction = &((*prediction)->ep_next);
529 }
530 }
531 }
532
533 /* Clears the list of predictions stored for BB. */
534
535 static void
536 clear_bb_predictions (basic_block bb)
537 {
538 void **preds = pointer_map_contains (bb_predictions, bb);
539 struct edge_prediction *pred, *next;
540
541 if (!preds)
542 return;
543
544 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
545 {
546 next = pred->ep_next;
547 free (pred);
548 }
549 *preds = NULL;
550 }
551
552 /* Return true when we can store prediction on insn INSN.
553 At the moment we represent predictions only on conditional
554 jumps, not at computed jump or other complicated cases. */
555 static bool
556 can_predict_insn_p (const_rtx insn)
557 {
558 return (JUMP_P (insn)
559 && any_condjump_p (insn)
560 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
561 }
562
563 /* Predict edge E by given predictor if possible. */
564
565 void
566 predict_edge_def (edge e, enum br_predictor predictor,
567 enum prediction taken)
568 {
569 int probability = predictor_info[(int) predictor].hitrate;
570
571 if (taken != TAKEN)
572 probability = REG_BR_PROB_BASE - probability;
573
574 predict_edge (e, predictor, probability);
575 }
576
577 /* Invert all branch predictions or probability notes in the INSN. This needs
578 to be done each time we invert the condition used by the jump. */
579
580 void
581 invert_br_probabilities (rtx insn)
582 {
583 rtx note;
584
585 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
586 if (REG_NOTE_KIND (note) == REG_BR_PROB)
587 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
588 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
589 XEXP (XEXP (note, 0), 1)
590 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
591 }
592
593 /* Dump information about the branch prediction to the output file. */
594
595 static void
596 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
597 basic_block bb, int used)
598 {
599 edge e;
600 edge_iterator ei;
601
602 if (!file)
603 return;
604
605 FOR_EACH_EDGE (e, ei, bb->succs)
606 if (! (e->flags & EDGE_FALLTHRU))
607 break;
608
609 fprintf (file, " %s heuristics%s: %.1f%%",
610 predictor_info[predictor].name,
611 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
612
613 if (bb->count)
614 {
615 fprintf (file, " exec ");
616 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
617 if (e)
618 {
619 fprintf (file, " hit ");
620 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
621 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
622 }
623 }
624
625 fprintf (file, "\n");
626 }
627
628 /* We can not predict the probabilities of outgoing edges of bb. Set them
629 evenly and hope for the best. */
630 static void
631 set_even_probabilities (basic_block bb)
632 {
633 int nedges = 0;
634 edge e;
635 edge_iterator ei;
636
637 FOR_EACH_EDGE (e, ei, bb->succs)
638 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
639 nedges ++;
640 FOR_EACH_EDGE (e, ei, bb->succs)
641 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
642 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
643 else
644 e->probability = 0;
645 }
646
647 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
648 note if not already present. Remove now useless REG_BR_PRED notes. */
649
650 static void
651 combine_predictions_for_insn (rtx insn, basic_block bb)
652 {
653 rtx prob_note;
654 rtx *pnote;
655 rtx note;
656 int best_probability = PROB_EVEN;
657 enum br_predictor best_predictor = END_PREDICTORS;
658 int combined_probability = REG_BR_PROB_BASE / 2;
659 int d;
660 bool first_match = false;
661 bool found = false;
662
663 if (!can_predict_insn_p (insn))
664 {
665 set_even_probabilities (bb);
666 return;
667 }
668
669 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
670 pnote = &REG_NOTES (insn);
671 if (dump_file)
672 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
673 bb->index);
674
675 /* We implement "first match" heuristics and use probability guessed
676 by predictor with smallest index. */
677 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
678 if (REG_NOTE_KIND (note) == REG_BR_PRED)
679 {
680 enum br_predictor predictor = ((enum br_predictor)
681 INTVAL (XEXP (XEXP (note, 0), 0)));
682 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
683
684 found = true;
685 if (best_predictor > predictor)
686 best_probability = probability, best_predictor = predictor;
687
688 d = (combined_probability * probability
689 + (REG_BR_PROB_BASE - combined_probability)
690 * (REG_BR_PROB_BASE - probability));
691
692 /* Use FP math to avoid overflows of 32bit integers. */
693 if (d == 0)
694 /* If one probability is 0% and one 100%, avoid division by zero. */
695 combined_probability = REG_BR_PROB_BASE / 2;
696 else
697 combined_probability = (((double) combined_probability) * probability
698 * REG_BR_PROB_BASE / d + 0.5);
699 }
700
701 /* Decide which heuristic to use. In case we didn't match anything,
702 use no_prediction heuristic, in case we did match, use either
703 first match or Dempster-Shaffer theory depending on the flags. */
704
705 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
706 first_match = true;
707
708 if (!found)
709 dump_prediction (dump_file, PRED_NO_PREDICTION,
710 combined_probability, bb, true);
711 else
712 {
713 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
714 bb, !first_match);
715 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
716 bb, first_match);
717 }
718
719 if (first_match)
720 combined_probability = best_probability;
721 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
722
723 while (*pnote)
724 {
725 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
726 {
727 enum br_predictor predictor = ((enum br_predictor)
728 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
729 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
730
731 dump_prediction (dump_file, predictor, probability, bb,
732 !first_match || best_predictor == predictor);
733 *pnote = XEXP (*pnote, 1);
734 }
735 else
736 pnote = &XEXP (*pnote, 1);
737 }
738
739 if (!prob_note)
740 {
741 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
742
743 /* Save the prediction into CFG in case we are seeing non-degenerated
744 conditional jump. */
745 if (!single_succ_p (bb))
746 {
747 BRANCH_EDGE (bb)->probability = combined_probability;
748 FALLTHRU_EDGE (bb)->probability
749 = REG_BR_PROB_BASE - combined_probability;
750 }
751 }
752 else if (!single_succ_p (bb))
753 {
754 int prob = INTVAL (XEXP (prob_note, 0));
755
756 BRANCH_EDGE (bb)->probability = prob;
757 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
758 }
759 else
760 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
761 }
762
763 /* Combine predictions into single probability and store them into CFG.
764 Remove now useless prediction entries. */
765
766 static void
767 combine_predictions_for_bb (basic_block bb)
768 {
769 int best_probability = PROB_EVEN;
770 enum br_predictor best_predictor = END_PREDICTORS;
771 int combined_probability = REG_BR_PROB_BASE / 2;
772 int d;
773 bool first_match = false;
774 bool found = false;
775 struct edge_prediction *pred;
776 int nedges = 0;
777 edge e, first = NULL, second = NULL;
778 edge_iterator ei;
779 void **preds;
780
781 FOR_EACH_EDGE (e, ei, bb->succs)
782 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
783 {
784 nedges ++;
785 if (first && !second)
786 second = e;
787 if (!first)
788 first = e;
789 }
790
791 /* When there is no successor or only one choice, prediction is easy.
792
793 We are lazy for now and predict only basic blocks with two outgoing
794 edges. It is possible to predict generic case too, but we have to
795 ignore first match heuristics and do more involved combining. Implement
796 this later. */
797 if (nedges != 2)
798 {
799 if (!bb->count)
800 set_even_probabilities (bb);
801 clear_bb_predictions (bb);
802 if (dump_file)
803 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
804 nedges, bb->index);
805 return;
806 }
807
808 if (dump_file)
809 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
810
811 preds = pointer_map_contains (bb_predictions, bb);
812 if (preds)
813 {
814 /* We implement "first match" heuristics and use probability guessed
815 by predictor with smallest index. */
816 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
817 {
818 enum br_predictor predictor = pred->ep_predictor;
819 int probability = pred->ep_probability;
820
821 if (pred->ep_edge != first)
822 probability = REG_BR_PROB_BASE - probability;
823
824 found = true;
825 /* First match heuristics would be widly confused if we predicted
826 both directions. */
827 if (best_predictor > predictor)
828 {
829 struct edge_prediction *pred2;
830 int prob = probability;
831
832 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
833 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
834 {
835 int probability2 = pred->ep_probability;
836
837 if (pred2->ep_edge != first)
838 probability2 = REG_BR_PROB_BASE - probability2;
839
840 if ((probability < REG_BR_PROB_BASE / 2) !=
841 (probability2 < REG_BR_PROB_BASE / 2))
842 break;
843
844 /* If the same predictor later gave better result, go for it! */
845 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
846 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
847 prob = probability2;
848 }
849 if (!pred2)
850 best_probability = prob, best_predictor = predictor;
851 }
852
853 d = (combined_probability * probability
854 + (REG_BR_PROB_BASE - combined_probability)
855 * (REG_BR_PROB_BASE - probability));
856
857 /* Use FP math to avoid overflows of 32bit integers. */
858 if (d == 0)
859 /* If one probability is 0% and one 100%, avoid division by zero. */
860 combined_probability = REG_BR_PROB_BASE / 2;
861 else
862 combined_probability = (((double) combined_probability)
863 * probability
864 * REG_BR_PROB_BASE / d + 0.5);
865 }
866 }
867
868 /* Decide which heuristic to use. In case we didn't match anything,
869 use no_prediction heuristic, in case we did match, use either
870 first match or Dempster-Shaffer theory depending on the flags. */
871
872 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
873 first_match = true;
874
875 if (!found)
876 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
877 else
878 {
879 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
880 !first_match);
881 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
882 first_match);
883 }
884
885 if (first_match)
886 combined_probability = best_probability;
887 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
888
889 if (preds)
890 {
891 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
892 {
893 enum br_predictor predictor = pred->ep_predictor;
894 int probability = pred->ep_probability;
895
896 if (pred->ep_edge != EDGE_SUCC (bb, 0))
897 probability = REG_BR_PROB_BASE - probability;
898 dump_prediction (dump_file, predictor, probability, bb,
899 !first_match || best_predictor == predictor);
900 }
901 }
902 clear_bb_predictions (bb);
903
904 if (!bb->count)
905 {
906 first->probability = combined_probability;
907 second->probability = REG_BR_PROB_BASE - combined_probability;
908 }
909 }
910
911 /* Predict edge probabilities by exploiting loop structure. */
912
913 static void
914 predict_loops (void)
915 {
916 loop_iterator li;
917 struct loop *loop;
918
919 /* Try to predict out blocks in a loop that are not part of a
920 natural loop. */
921 FOR_EACH_LOOP (li, loop, 0)
922 {
923 basic_block bb, *bbs;
924 unsigned j, n_exits;
925 VEC (edge, heap) *exits;
926 struct tree_niter_desc niter_desc;
927 edge ex;
928
929 exits = get_loop_exit_edges (loop);
930 n_exits = VEC_length (edge, exits);
931
932 for (j = 0; VEC_iterate (edge, exits, j, ex); j++)
933 {
934 tree niter = NULL;
935 HOST_WIDE_INT nitercst;
936 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
937 int probability;
938 enum br_predictor predictor;
939
940 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
941 niter = niter_desc.niter;
942 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
943 niter = loop_niter_by_eval (loop, ex);
944
945 if (TREE_CODE (niter) == INTEGER_CST)
946 {
947 if (host_integerp (niter, 1)
948 && compare_tree_int (niter, max-1) == -1)
949 nitercst = tree_low_cst (niter, 1) + 1;
950 else
951 nitercst = max;
952 predictor = PRED_LOOP_ITERATIONS;
953 }
954 /* If we have just one exit and we can derive some information about
955 the number of iterations of the loop from the statements inside
956 the loop, use it to predict this exit. */
957 else if (n_exits == 1)
958 {
959 nitercst = estimated_loop_iterations_int (loop, false);
960 if (nitercst < 0)
961 continue;
962 if (nitercst > max)
963 nitercst = max;
964
965 predictor = PRED_LOOP_ITERATIONS_GUESSED;
966 }
967 else
968 continue;
969
970 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
971 predict_edge (ex, predictor, probability);
972 }
973 VEC_free (edge, heap, exits);
974
975 bbs = get_loop_body (loop);
976
977 for (j = 0; j < loop->num_nodes; j++)
978 {
979 int header_found = 0;
980 edge e;
981 edge_iterator ei;
982
983 bb = bbs[j];
984
985 /* Bypass loop heuristics on continue statement. These
986 statements construct loops via "non-loop" constructs
987 in the source language and are better to be handled
988 separately. */
989 if (predicted_by_p (bb, PRED_CONTINUE))
990 continue;
991
992 /* Loop branch heuristics - predict an edge back to a
993 loop's head as taken. */
994 if (bb == loop->latch)
995 {
996 e = find_edge (loop->latch, loop->header);
997 if (e)
998 {
999 header_found = 1;
1000 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1001 }
1002 }
1003
1004 /* Loop exit heuristics - predict an edge exiting the loop if the
1005 conditional has no loop header successors as not taken. */
1006 if (!header_found
1007 /* If we already used more reliable loop exit predictors, do not
1008 bother with PRED_LOOP_EXIT. */
1009 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1010 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1011 {
1012 /* For loop with many exits we don't want to predict all exits
1013 with the pretty large probability, because if all exits are
1014 considered in row, the loop would be predicted to iterate
1015 almost never. The code to divide probability by number of
1016 exits is very rough. It should compute the number of exits
1017 taken in each patch through function (not the overall number
1018 of exits that might be a lot higher for loops with wide switch
1019 statements in them) and compute n-th square root.
1020
1021 We limit the minimal probability by 2% to avoid
1022 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1023 as this was causing regression in perl benchmark containing such
1024 a wide loop. */
1025
1026 int probability = ((REG_BR_PROB_BASE
1027 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1028 / n_exits);
1029 if (probability < HITRATE (2))
1030 probability = HITRATE (2);
1031 FOR_EACH_EDGE (e, ei, bb->succs)
1032 if (e->dest->index < NUM_FIXED_BLOCKS
1033 || !flow_bb_inside_loop_p (loop, e->dest))
1034 predict_edge (e, PRED_LOOP_EXIT, probability);
1035 }
1036 }
1037
1038 /* Free basic blocks from get_loop_body. */
1039 free (bbs);
1040 }
1041 }
1042
1043 /* Attempt to predict probabilities of BB outgoing edges using local
1044 properties. */
1045 static void
1046 bb_estimate_probability_locally (basic_block bb)
1047 {
1048 rtx last_insn = BB_END (bb);
1049 rtx cond;
1050
1051 if (! can_predict_insn_p (last_insn))
1052 return;
1053 cond = get_condition (last_insn, NULL, false, false);
1054 if (! cond)
1055 return;
1056
1057 /* Try "pointer heuristic."
1058 A comparison ptr == 0 is predicted as false.
1059 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1060 if (COMPARISON_P (cond)
1061 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1062 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1063 {
1064 if (GET_CODE (cond) == EQ)
1065 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1066 else if (GET_CODE (cond) == NE)
1067 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1068 }
1069 else
1070
1071 /* Try "opcode heuristic."
1072 EQ tests are usually false and NE tests are usually true. Also,
1073 most quantities are positive, so we can make the appropriate guesses
1074 about signed comparisons against zero. */
1075 switch (GET_CODE (cond))
1076 {
1077 case CONST_INT:
1078 /* Unconditional branch. */
1079 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1080 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1081 break;
1082
1083 case EQ:
1084 case UNEQ:
1085 /* Floating point comparisons appears to behave in a very
1086 unpredictable way because of special role of = tests in
1087 FP code. */
1088 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1089 ;
1090 /* Comparisons with 0 are often used for booleans and there is
1091 nothing useful to predict about them. */
1092 else if (XEXP (cond, 1) == const0_rtx
1093 || XEXP (cond, 0) == const0_rtx)
1094 ;
1095 else
1096 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1097 break;
1098
1099 case NE:
1100 case LTGT:
1101 /* Floating point comparisons appears to behave in a very
1102 unpredictable way because of special role of = tests in
1103 FP code. */
1104 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1105 ;
1106 /* Comparisons with 0 are often used for booleans and there is
1107 nothing useful to predict about them. */
1108 else if (XEXP (cond, 1) == const0_rtx
1109 || XEXP (cond, 0) == const0_rtx)
1110 ;
1111 else
1112 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1113 break;
1114
1115 case ORDERED:
1116 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1117 break;
1118
1119 case UNORDERED:
1120 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1121 break;
1122
1123 case LE:
1124 case LT:
1125 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1126 || XEXP (cond, 1) == constm1_rtx)
1127 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1128 break;
1129
1130 case GE:
1131 case GT:
1132 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1133 || XEXP (cond, 1) == constm1_rtx)
1134 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1135 break;
1136
1137 default:
1138 break;
1139 }
1140 }
1141
1142 /* Set edge->probability for each successor edge of BB. */
1143 void
1144 guess_outgoing_edge_probabilities (basic_block bb)
1145 {
1146 bb_estimate_probability_locally (bb);
1147 combine_predictions_for_insn (BB_END (bb), bb);
1148 }
1149 \f
1150 static tree expr_expected_value (tree, bitmap);
1151
1152 /* Helper function for expr_expected_value. */
1153
1154 static tree
1155 expr_expected_value_1 (tree type, tree op0, enum tree_code code, tree op1, bitmap visited)
1156 {
1157 gimple def;
1158
1159 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1160 {
1161 if (TREE_CONSTANT (op0))
1162 return op0;
1163
1164 if (code != SSA_NAME)
1165 return NULL_TREE;
1166
1167 def = SSA_NAME_DEF_STMT (op0);
1168
1169 /* If we were already here, break the infinite cycle. */
1170 if (bitmap_bit_p (visited, SSA_NAME_VERSION (op0)))
1171 return NULL;
1172 bitmap_set_bit (visited, SSA_NAME_VERSION (op0));
1173
1174 if (gimple_code (def) == GIMPLE_PHI)
1175 {
1176 /* All the arguments of the PHI node must have the same constant
1177 length. */
1178 int i, n = gimple_phi_num_args (def);
1179 tree val = NULL, new_val;
1180
1181 for (i = 0; i < n; i++)
1182 {
1183 tree arg = PHI_ARG_DEF (def, i);
1184
1185 /* If this PHI has itself as an argument, we cannot
1186 determine the string length of this argument. However,
1187 if we can find an expected constant value for the other
1188 PHI args then we can still be sure that this is
1189 likely a constant. So be optimistic and just
1190 continue with the next argument. */
1191 if (arg == PHI_RESULT (def))
1192 continue;
1193
1194 new_val = expr_expected_value (arg, visited);
1195 if (!new_val)
1196 return NULL;
1197 if (!val)
1198 val = new_val;
1199 else if (!operand_equal_p (val, new_val, false))
1200 return NULL;
1201 }
1202 return val;
1203 }
1204 if (is_gimple_assign (def))
1205 {
1206 if (gimple_assign_lhs (def) != op0)
1207 return NULL;
1208
1209 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1210 gimple_assign_rhs1 (def),
1211 gimple_assign_rhs_code (def),
1212 gimple_assign_rhs2 (def),
1213 visited);
1214 }
1215
1216 if (is_gimple_call (def))
1217 {
1218 tree decl = gimple_call_fndecl (def);
1219 if (!decl)
1220 return NULL;
1221 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1222 && DECL_FUNCTION_CODE (decl) == BUILT_IN_EXPECT)
1223 {
1224 tree val;
1225
1226 if (gimple_call_num_args (def) != 2)
1227 return NULL;
1228 val = gimple_call_arg (def, 0);
1229 if (TREE_CONSTANT (val))
1230 return val;
1231 return gimple_call_arg (def, 1);
1232 }
1233 }
1234
1235 return NULL;
1236 }
1237
1238 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1239 {
1240 tree res;
1241 op0 = expr_expected_value (op0, visited);
1242 if (!op0)
1243 return NULL;
1244 op1 = expr_expected_value (op1, visited);
1245 if (!op1)
1246 return NULL;
1247 res = fold_build2 (code, type, op0, op1);
1248 if (TREE_CONSTANT (res))
1249 return res;
1250 return NULL;
1251 }
1252 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1253 {
1254 tree res;
1255 op0 = expr_expected_value (op0, visited);
1256 if (!op0)
1257 return NULL;
1258 res = fold_build1 (code, type, op0);
1259 if (TREE_CONSTANT (res))
1260 return res;
1261 return NULL;
1262 }
1263 return NULL;
1264 }
1265
1266 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1267 The function is used by builtin_expect branch predictor so the evidence
1268 must come from this construct and additional possible constant folding.
1269
1270 We may want to implement more involved value guess (such as value range
1271 propagation based prediction), but such tricks shall go to new
1272 implementation. */
1273
1274 static tree
1275 expr_expected_value (tree expr, bitmap visited)
1276 {
1277 enum tree_code code;
1278 tree op0, op1;
1279
1280 if (TREE_CONSTANT (expr))
1281 return expr;
1282
1283 extract_ops_from_tree (expr, &code, &op0, &op1);
1284 return expr_expected_value_1 (TREE_TYPE (expr),
1285 op0, code, op1, visited);
1286 }
1287
1288 \f
1289 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1290 we no longer need. */
1291 static unsigned int
1292 strip_predict_hints (void)
1293 {
1294 basic_block bb;
1295 gimple ass_stmt;
1296 tree var;
1297
1298 FOR_EACH_BB (bb)
1299 {
1300 gimple_stmt_iterator bi;
1301 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1302 {
1303 gimple stmt = gsi_stmt (bi);
1304
1305 if (gimple_code (stmt) == GIMPLE_PREDICT)
1306 {
1307 gsi_remove (&bi, true);
1308 continue;
1309 }
1310 else if (gimple_code (stmt) == GIMPLE_CALL)
1311 {
1312 tree fndecl = gimple_call_fndecl (stmt);
1313
1314 if (fndecl
1315 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1316 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1317 && gimple_call_num_args (stmt) == 2)
1318 {
1319 var = gimple_call_lhs (stmt);
1320 ass_stmt = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1321
1322 gsi_replace (&bi, ass_stmt, true);
1323 }
1324 }
1325 gsi_next (&bi);
1326 }
1327 }
1328 return 0;
1329 }
1330 \f
1331 /* Predict using opcode of the last statement in basic block. */
1332 static void
1333 tree_predict_by_opcode (basic_block bb)
1334 {
1335 gimple stmt = last_stmt (bb);
1336 edge then_edge;
1337 tree op0, op1;
1338 tree type;
1339 tree val;
1340 enum tree_code cmp;
1341 bitmap visited;
1342 edge_iterator ei;
1343
1344 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1345 return;
1346 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1347 if (then_edge->flags & EDGE_TRUE_VALUE)
1348 break;
1349 op0 = gimple_cond_lhs (stmt);
1350 op1 = gimple_cond_rhs (stmt);
1351 cmp = gimple_cond_code (stmt);
1352 type = TREE_TYPE (op0);
1353 visited = BITMAP_ALLOC (NULL);
1354 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1355 BITMAP_FREE (visited);
1356 if (val)
1357 {
1358 if (integer_zerop (val))
1359 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1360 else
1361 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1362 return;
1363 }
1364 /* Try "pointer heuristic."
1365 A comparison ptr == 0 is predicted as false.
1366 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1367 if (POINTER_TYPE_P (type))
1368 {
1369 if (cmp == EQ_EXPR)
1370 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1371 else if (cmp == NE_EXPR)
1372 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1373 }
1374 else
1375
1376 /* Try "opcode heuristic."
1377 EQ tests are usually false and NE tests are usually true. Also,
1378 most quantities are positive, so we can make the appropriate guesses
1379 about signed comparisons against zero. */
1380 switch (cmp)
1381 {
1382 case EQ_EXPR:
1383 case UNEQ_EXPR:
1384 /* Floating point comparisons appears to behave in a very
1385 unpredictable way because of special role of = tests in
1386 FP code. */
1387 if (FLOAT_TYPE_P (type))
1388 ;
1389 /* Comparisons with 0 are often used for booleans and there is
1390 nothing useful to predict about them. */
1391 else if (integer_zerop (op0) || integer_zerop (op1))
1392 ;
1393 else
1394 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1395 break;
1396
1397 case NE_EXPR:
1398 case LTGT_EXPR:
1399 /* Floating point comparisons appears to behave in a very
1400 unpredictable way because of special role of = tests in
1401 FP code. */
1402 if (FLOAT_TYPE_P (type))
1403 ;
1404 /* Comparisons with 0 are often used for booleans and there is
1405 nothing useful to predict about them. */
1406 else if (integer_zerop (op0)
1407 || integer_zerop (op1))
1408 ;
1409 else
1410 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1411 break;
1412
1413 case ORDERED_EXPR:
1414 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1415 break;
1416
1417 case UNORDERED_EXPR:
1418 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1419 break;
1420
1421 case LE_EXPR:
1422 case LT_EXPR:
1423 if (integer_zerop (op1)
1424 || integer_onep (op1)
1425 || integer_all_onesp (op1)
1426 || real_zerop (op1)
1427 || real_onep (op1)
1428 || real_minus_onep (op1))
1429 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1430 break;
1431
1432 case GE_EXPR:
1433 case GT_EXPR:
1434 if (integer_zerop (op1)
1435 || integer_onep (op1)
1436 || integer_all_onesp (op1)
1437 || real_zerop (op1)
1438 || real_onep (op1)
1439 || real_minus_onep (op1))
1440 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1441 break;
1442
1443 default:
1444 break;
1445 }
1446 }
1447
1448 /* Try to guess whether the value of return means error code. */
1449
1450 static enum br_predictor
1451 return_prediction (tree val, enum prediction *prediction)
1452 {
1453 /* VOID. */
1454 if (!val)
1455 return PRED_NO_PREDICTION;
1456 /* Different heuristics for pointers and scalars. */
1457 if (POINTER_TYPE_P (TREE_TYPE (val)))
1458 {
1459 /* NULL is usually not returned. */
1460 if (integer_zerop (val))
1461 {
1462 *prediction = NOT_TAKEN;
1463 return PRED_NULL_RETURN;
1464 }
1465 }
1466 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1467 {
1468 /* Negative return values are often used to indicate
1469 errors. */
1470 if (TREE_CODE (val) == INTEGER_CST
1471 && tree_int_cst_sgn (val) < 0)
1472 {
1473 *prediction = NOT_TAKEN;
1474 return PRED_NEGATIVE_RETURN;
1475 }
1476 /* Constant return values seems to be commonly taken.
1477 Zero/one often represent booleans so exclude them from the
1478 heuristics. */
1479 if (TREE_CONSTANT (val)
1480 && (!integer_zerop (val) && !integer_onep (val)))
1481 {
1482 *prediction = TAKEN;
1483 return PRED_CONST_RETURN;
1484 }
1485 }
1486 return PRED_NO_PREDICTION;
1487 }
1488
1489 /* Find the basic block with return expression and look up for possible
1490 return value trying to apply RETURN_PREDICTION heuristics. */
1491 static void
1492 apply_return_prediction (void)
1493 {
1494 gimple return_stmt = NULL;
1495 tree return_val;
1496 edge e;
1497 gimple phi;
1498 int phi_num_args, i;
1499 enum br_predictor pred;
1500 enum prediction direction;
1501 edge_iterator ei;
1502
1503 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1504 {
1505 return_stmt = last_stmt (e->src);
1506 if (return_stmt
1507 && gimple_code (return_stmt) == GIMPLE_RETURN)
1508 break;
1509 }
1510 if (!e)
1511 return;
1512 return_val = gimple_return_retval (return_stmt);
1513 if (!return_val)
1514 return;
1515 if (TREE_CODE (return_val) != SSA_NAME
1516 || !SSA_NAME_DEF_STMT (return_val)
1517 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1518 return;
1519 phi = SSA_NAME_DEF_STMT (return_val);
1520 phi_num_args = gimple_phi_num_args (phi);
1521 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1522
1523 /* Avoid the degenerate case where all return values form the function
1524 belongs to same category (ie they are all positive constants)
1525 so we can hardly say something about them. */
1526 for (i = 1; i < phi_num_args; i++)
1527 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1528 break;
1529 if (i != phi_num_args)
1530 for (i = 0; i < phi_num_args; i++)
1531 {
1532 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1533 if (pred != PRED_NO_PREDICTION)
1534 predict_paths_leading_to (gimple_phi_arg_edge (phi, i)->src, pred,
1535 direction);
1536 }
1537 }
1538
1539 /* Look for basic block that contains unlikely to happen events
1540 (such as noreturn calls) and mark all paths leading to execution
1541 of this basic blocks as unlikely. */
1542
1543 static void
1544 tree_bb_level_predictions (void)
1545 {
1546 basic_block bb;
1547 bool has_return_edges = false;
1548 edge e;
1549 edge_iterator ei;
1550
1551 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1552 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
1553 {
1554 has_return_edges = true;
1555 break;
1556 }
1557
1558 apply_return_prediction ();
1559
1560 FOR_EACH_BB (bb)
1561 {
1562 gimple_stmt_iterator gsi;
1563
1564 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1565 {
1566 gimple stmt = gsi_stmt (gsi);
1567 tree decl;
1568
1569 if (is_gimple_call (stmt))
1570 {
1571 if ((gimple_call_flags (stmt) & ECF_NORETURN)
1572 && has_return_edges)
1573 predict_paths_leading_to (bb, PRED_NORETURN,
1574 NOT_TAKEN);
1575 decl = gimple_call_fndecl (stmt);
1576 if (decl
1577 && lookup_attribute ("cold",
1578 DECL_ATTRIBUTES (decl)))
1579 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
1580 NOT_TAKEN);
1581 }
1582 else if (gimple_code (stmt) == GIMPLE_PREDICT)
1583 {
1584 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
1585 gimple_predict_outcome (stmt));
1586 /* Keep GIMPLE_PREDICT around so early inlining will propagate
1587 hints to callers. */
1588 }
1589 }
1590 }
1591 }
1592
1593 #ifdef ENABLE_CHECKING
1594
1595 /* Callback for pointer_map_traverse, asserts that the pointer map is
1596 empty. */
1597
1598 static bool
1599 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
1600 void *data ATTRIBUTE_UNUSED)
1601 {
1602 gcc_assert (!*value);
1603 return false;
1604 }
1605 #endif
1606
1607 /* Predict branch probabilities and estimate profile for basic block BB. */
1608
1609 static void
1610 tree_estimate_probability_bb (basic_block bb)
1611 {
1612 edge e;
1613 edge_iterator ei;
1614 gimple last;
1615
1616 FOR_EACH_EDGE (e, ei, bb->succs)
1617 {
1618 /* Predict early returns to be probable, as we've already taken
1619 care for error returns and other cases are often used for
1620 fast paths through function.
1621
1622 Since we've already removed the return statements, we are
1623 looking for CFG like:
1624
1625 if (conditional)
1626 {
1627 ..
1628 goto return_block
1629 }
1630 some other blocks
1631 return_block:
1632 return_stmt. */
1633 if (e->dest != bb->next_bb
1634 && e->dest != EXIT_BLOCK_PTR
1635 && single_succ_p (e->dest)
1636 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
1637 && (last = last_stmt (e->dest)) != NULL
1638 && gimple_code (last) == GIMPLE_RETURN)
1639 {
1640 edge e1;
1641 edge_iterator ei1;
1642
1643 if (single_succ_p (bb))
1644 {
1645 FOR_EACH_EDGE (e1, ei1, bb->preds)
1646 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
1647 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
1648 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
1649 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1650 }
1651 else
1652 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
1653 && !predicted_by_p (e->src, PRED_CONST_RETURN)
1654 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
1655 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
1656 }
1657
1658 /* Look for block we are guarding (ie we dominate it,
1659 but it doesn't postdominate us). */
1660 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
1661 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
1662 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
1663 {
1664 gimple_stmt_iterator bi;
1665
1666 /* The call heuristic claims that a guarded function call
1667 is improbable. This is because such calls are often used
1668 to signal exceptional situations such as printing error
1669 messages. */
1670 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
1671 gsi_next (&bi))
1672 {
1673 gimple stmt = gsi_stmt (bi);
1674 if (is_gimple_call (stmt)
1675 /* Constant and pure calls are hardly used to signalize
1676 something exceptional. */
1677 && gimple_has_side_effects (stmt))
1678 {
1679 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
1680 break;
1681 }
1682 }
1683 }
1684 }
1685 tree_predict_by_opcode (bb);
1686 }
1687
1688 /* Predict branch probabilities and estimate profile of the tree CFG.
1689 This function can be called from the loop optimizers to recompute
1690 the profile information. */
1691
1692 void
1693 tree_estimate_probability (void)
1694 {
1695 basic_block bb;
1696
1697 add_noreturn_fake_exit_edges ();
1698 connect_infinite_loops_to_exit ();
1699 /* We use loop_niter_by_eval, which requires that the loops have
1700 preheaders. */
1701 create_preheaders (CP_SIMPLE_PREHEADERS);
1702 calculate_dominance_info (CDI_POST_DOMINATORS);
1703
1704 bb_predictions = pointer_map_create ();
1705 tree_bb_level_predictions ();
1706 record_loop_exits ();
1707
1708 if (number_of_loops () > 1)
1709 predict_loops ();
1710
1711 FOR_EACH_BB (bb)
1712 tree_estimate_probability_bb (bb);
1713
1714 FOR_EACH_BB (bb)
1715 combine_predictions_for_bb (bb);
1716
1717 #ifdef ENABLE_CHECKING
1718 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
1719 #endif
1720 pointer_map_destroy (bb_predictions);
1721 bb_predictions = NULL;
1722
1723 estimate_bb_frequencies ();
1724 free_dominance_info (CDI_POST_DOMINATORS);
1725 remove_fake_exit_edges ();
1726 }
1727
1728 /* Predict branch probabilities and estimate profile of the tree CFG.
1729 This is the driver function for PASS_PROFILE. */
1730
1731 static unsigned int
1732 tree_estimate_probability_driver (void)
1733 {
1734 unsigned nb_loops;
1735
1736 loop_optimizer_init (0);
1737 if (dump_file && (dump_flags & TDF_DETAILS))
1738 flow_loops_dump (dump_file, NULL, 0);
1739
1740 mark_irreducible_loops ();
1741
1742 nb_loops = number_of_loops ();
1743 if (nb_loops > 1)
1744 scev_initialize ();
1745
1746 tree_estimate_probability ();
1747
1748 if (nb_loops > 1)
1749 scev_finalize ();
1750
1751 loop_optimizer_finalize ();
1752 if (dump_file && (dump_flags & TDF_DETAILS))
1753 gimple_dump_cfg (dump_file, dump_flags);
1754 if (profile_status == PROFILE_ABSENT)
1755 profile_status = PROFILE_GUESSED;
1756 return 0;
1757 }
1758 \f
1759 /* Predict edges to successors of CUR whose sources are not postdominated by
1760 BB by PRED and recurse to all postdominators. */
1761
1762 static void
1763 predict_paths_for_bb (basic_block cur, basic_block bb,
1764 enum br_predictor pred,
1765 enum prediction taken)
1766 {
1767 edge e;
1768 edge_iterator ei;
1769 basic_block son;
1770
1771 /* We are looking for all edges forming edge cut induced by
1772 set of all blocks postdominated by BB. */
1773 FOR_EACH_EDGE (e, ei, cur->preds)
1774 if (e->src->index >= NUM_FIXED_BLOCKS
1775 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
1776 {
1777 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
1778 predict_edge_def (e, pred, taken);
1779 }
1780 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
1781 son;
1782 son = next_dom_son (CDI_POST_DOMINATORS, son))
1783 predict_paths_for_bb (son, bb, pred, taken);
1784 }
1785
1786 /* Sets branch probabilities according to PREDiction and
1787 FLAGS. */
1788
1789 static void
1790 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
1791 enum prediction taken)
1792 {
1793 predict_paths_for_bb (bb, bb, pred, taken);
1794 }
1795 \f
1796 /* This is used to carry information about basic blocks. It is
1797 attached to the AUX field of the standard CFG block. */
1798
1799 typedef struct block_info_def
1800 {
1801 /* Estimated frequency of execution of basic_block. */
1802 sreal frequency;
1803
1804 /* To keep queue of basic blocks to process. */
1805 basic_block next;
1806
1807 /* Number of predecessors we need to visit first. */
1808 int npredecessors;
1809 } *block_info;
1810
1811 /* Similar information for edges. */
1812 typedef struct edge_info_def
1813 {
1814 /* In case edge is a loopback edge, the probability edge will be reached
1815 in case header is. Estimated number of iterations of the loop can be
1816 then computed as 1 / (1 - back_edge_prob). */
1817 sreal back_edge_prob;
1818 /* True if the edge is a loopback edge in the natural loop. */
1819 unsigned int back_edge:1;
1820 } *edge_info;
1821
1822 #define BLOCK_INFO(B) ((block_info) (B)->aux)
1823 #define EDGE_INFO(E) ((edge_info) (E)->aux)
1824
1825 /* Helper function for estimate_bb_frequencies.
1826 Propagate the frequencies in blocks marked in
1827 TOVISIT, starting in HEAD. */
1828
1829 static void
1830 propagate_freq (basic_block head, bitmap tovisit)
1831 {
1832 basic_block bb;
1833 basic_block last;
1834 unsigned i;
1835 edge e;
1836 basic_block nextbb;
1837 bitmap_iterator bi;
1838
1839 /* For each basic block we need to visit count number of his predecessors
1840 we need to visit first. */
1841 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
1842 {
1843 edge_iterator ei;
1844 int count = 0;
1845
1846 /* The outermost "loop" includes the exit block, which we can not
1847 look up via BASIC_BLOCK. Detect this and use EXIT_BLOCK_PTR
1848 directly. Do the same for the entry block. */
1849 bb = BASIC_BLOCK (i);
1850
1851 FOR_EACH_EDGE (e, ei, bb->preds)
1852 {
1853 bool visit = bitmap_bit_p (tovisit, e->src->index);
1854
1855 if (visit && !(e->flags & EDGE_DFS_BACK))
1856 count++;
1857 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
1858 fprintf (dump_file,
1859 "Irreducible region hit, ignoring edge to %i->%i\n",
1860 e->src->index, bb->index);
1861 }
1862 BLOCK_INFO (bb)->npredecessors = count;
1863 }
1864
1865 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
1866 last = head;
1867 for (bb = head; bb; bb = nextbb)
1868 {
1869 edge_iterator ei;
1870 sreal cyclic_probability, frequency;
1871
1872 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
1873 memcpy (&frequency, &real_zero, sizeof (real_zero));
1874
1875 nextbb = BLOCK_INFO (bb)->next;
1876 BLOCK_INFO (bb)->next = NULL;
1877
1878 /* Compute frequency of basic block. */
1879 if (bb != head)
1880 {
1881 #ifdef ENABLE_CHECKING
1882 FOR_EACH_EDGE (e, ei, bb->preds)
1883 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
1884 || (e->flags & EDGE_DFS_BACK));
1885 #endif
1886
1887 FOR_EACH_EDGE (e, ei, bb->preds)
1888 if (EDGE_INFO (e)->back_edge)
1889 {
1890 sreal_add (&cyclic_probability, &cyclic_probability,
1891 &EDGE_INFO (e)->back_edge_prob);
1892 }
1893 else if (!(e->flags & EDGE_DFS_BACK))
1894 {
1895 sreal tmp;
1896
1897 /* frequency += (e->probability
1898 * BLOCK_INFO (e->src)->frequency /
1899 REG_BR_PROB_BASE); */
1900
1901 sreal_init (&tmp, e->probability, 0);
1902 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
1903 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
1904 sreal_add (&frequency, &frequency, &tmp);
1905 }
1906
1907 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
1908 {
1909 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
1910 sizeof (frequency));
1911 }
1912 else
1913 {
1914 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
1915 {
1916 memcpy (&cyclic_probability, &real_almost_one,
1917 sizeof (real_almost_one));
1918 }
1919
1920 /* BLOCK_INFO (bb)->frequency = frequency
1921 / (1 - cyclic_probability) */
1922
1923 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
1924 sreal_div (&BLOCK_INFO (bb)->frequency,
1925 &frequency, &cyclic_probability);
1926 }
1927 }
1928
1929 bitmap_clear_bit (tovisit, bb->index);
1930
1931 e = find_edge (bb, head);
1932 if (e)
1933 {
1934 sreal tmp;
1935
1936 /* EDGE_INFO (e)->back_edge_prob
1937 = ((e->probability * BLOCK_INFO (bb)->frequency)
1938 / REG_BR_PROB_BASE); */
1939
1940 sreal_init (&tmp, e->probability, 0);
1941 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
1942 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
1943 &tmp, &real_inv_br_prob_base);
1944 }
1945
1946 /* Propagate to successor blocks. */
1947 FOR_EACH_EDGE (e, ei, bb->succs)
1948 if (!(e->flags & EDGE_DFS_BACK)
1949 && BLOCK_INFO (e->dest)->npredecessors)
1950 {
1951 BLOCK_INFO (e->dest)->npredecessors--;
1952 if (!BLOCK_INFO (e->dest)->npredecessors)
1953 {
1954 if (!nextbb)
1955 nextbb = e->dest;
1956 else
1957 BLOCK_INFO (last)->next = e->dest;
1958
1959 last = e->dest;
1960 }
1961 }
1962 }
1963 }
1964
1965 /* Estimate probabilities of loopback edges in loops at same nest level. */
1966
1967 static void
1968 estimate_loops_at_level (struct loop *first_loop)
1969 {
1970 struct loop *loop;
1971
1972 for (loop = first_loop; loop; loop = loop->next)
1973 {
1974 edge e;
1975 basic_block *bbs;
1976 unsigned i;
1977 bitmap tovisit = BITMAP_ALLOC (NULL);
1978
1979 estimate_loops_at_level (loop->inner);
1980
1981 /* Find current loop back edge and mark it. */
1982 e = loop_latch_edge (loop);
1983 EDGE_INFO (e)->back_edge = 1;
1984
1985 bbs = get_loop_body (loop);
1986 for (i = 0; i < loop->num_nodes; i++)
1987 bitmap_set_bit (tovisit, bbs[i]->index);
1988 free (bbs);
1989 propagate_freq (loop->header, tovisit);
1990 BITMAP_FREE (tovisit);
1991 }
1992 }
1993
1994 /* Propagates frequencies through structure of loops. */
1995
1996 static void
1997 estimate_loops (void)
1998 {
1999 bitmap tovisit = BITMAP_ALLOC (NULL);
2000 basic_block bb;
2001
2002 /* Start by estimating the frequencies in the loops. */
2003 if (number_of_loops () > 1)
2004 estimate_loops_at_level (current_loops->tree_root->inner);
2005
2006 /* Now propagate the frequencies through all the blocks. */
2007 FOR_ALL_BB (bb)
2008 {
2009 bitmap_set_bit (tovisit, bb->index);
2010 }
2011 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2012 BITMAP_FREE (tovisit);
2013 }
2014
2015 /* Convert counts measured by profile driven feedback to frequencies.
2016 Return nonzero iff there was any nonzero execution count. */
2017
2018 int
2019 counts_to_freqs (void)
2020 {
2021 gcov_type count_max, true_count_max = 0;
2022 basic_block bb;
2023
2024 FOR_EACH_BB (bb)
2025 true_count_max = MAX (bb->count, true_count_max);
2026
2027 count_max = MAX (true_count_max, 1);
2028 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2029 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2030
2031 return true_count_max;
2032 }
2033
2034 /* Return true if function is likely to be expensive, so there is no point to
2035 optimize performance of prologue, epilogue or do inlining at the expense
2036 of code size growth. THRESHOLD is the limit of number of instructions
2037 function can execute at average to be still considered not expensive. */
2038
2039 bool
2040 expensive_function_p (int threshold)
2041 {
2042 unsigned int sum = 0;
2043 basic_block bb;
2044 unsigned int limit;
2045
2046 /* We can not compute accurately for large thresholds due to scaled
2047 frequencies. */
2048 gcc_assert (threshold <= BB_FREQ_MAX);
2049
2050 /* Frequencies are out of range. This either means that function contains
2051 internal loop executing more than BB_FREQ_MAX times or profile feedback
2052 is available and function has not been executed at all. */
2053 if (ENTRY_BLOCK_PTR->frequency == 0)
2054 return true;
2055
2056 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2057 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2058 FOR_EACH_BB (bb)
2059 {
2060 rtx insn;
2061
2062 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
2063 insn = NEXT_INSN (insn))
2064 if (active_insn_p (insn))
2065 {
2066 sum += bb->frequency;
2067 if (sum > limit)
2068 return true;
2069 }
2070 }
2071
2072 return false;
2073 }
2074
2075 /* Estimate basic blocks frequency by given branch probabilities. */
2076
2077 void
2078 estimate_bb_frequencies (void)
2079 {
2080 basic_block bb;
2081 sreal freq_max;
2082
2083 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2084 {
2085 static int real_values_initialized = 0;
2086
2087 if (!real_values_initialized)
2088 {
2089 real_values_initialized = 1;
2090 sreal_init (&real_zero, 0, 0);
2091 sreal_init (&real_one, 1, 0);
2092 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2093 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2094 sreal_init (&real_one_half, 1, -1);
2095 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2096 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2097 }
2098
2099 mark_dfs_back_edges ();
2100
2101 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2102
2103 /* Set up block info for each basic block. */
2104 alloc_aux_for_blocks (sizeof (struct block_info_def));
2105 alloc_aux_for_edges (sizeof (struct edge_info_def));
2106 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2107 {
2108 edge e;
2109 edge_iterator ei;
2110
2111 FOR_EACH_EDGE (e, ei, bb->succs)
2112 {
2113 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2114 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2115 &EDGE_INFO (e)->back_edge_prob,
2116 &real_inv_br_prob_base);
2117 }
2118 }
2119
2120 /* First compute probabilities locally for each loop from innermost
2121 to outermost to examine probabilities for back edges. */
2122 estimate_loops ();
2123
2124 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2125 FOR_EACH_BB (bb)
2126 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2127 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2128
2129 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2130 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2131 {
2132 sreal tmp;
2133
2134 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2135 sreal_add (&tmp, &tmp, &real_one_half);
2136 bb->frequency = sreal_to_int (&tmp);
2137 }
2138
2139 free_aux_for_blocks ();
2140 free_aux_for_edges ();
2141 }
2142 compute_function_frequency ();
2143 if (flag_reorder_functions)
2144 choose_function_section ();
2145 }
2146
2147 /* Decide whether function is hot, cold or unlikely executed. */
2148 static void
2149 compute_function_frequency (void)
2150 {
2151 basic_block bb;
2152
2153 if (!profile_info || !flag_branch_probabilities)
2154 {
2155 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2156 != NULL)
2157 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
2158 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2159 != NULL)
2160 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2161 return;
2162 }
2163 cfun->function_frequency = FUNCTION_FREQUENCY_UNLIKELY_EXECUTED;
2164 FOR_EACH_BB (bb)
2165 {
2166 if (maybe_hot_bb_p (bb))
2167 {
2168 cfun->function_frequency = FUNCTION_FREQUENCY_HOT;
2169 return;
2170 }
2171 if (!probably_never_executed_bb_p (bb))
2172 cfun->function_frequency = FUNCTION_FREQUENCY_NORMAL;
2173 }
2174 }
2175
2176 /* Choose appropriate section for the function. */
2177 static void
2178 choose_function_section (void)
2179 {
2180 if (DECL_SECTION_NAME (current_function_decl)
2181 || !targetm.have_named_sections
2182 /* Theoretically we can split the gnu.linkonce text section too,
2183 but this requires more work as the frequency needs to match
2184 for all generated objects so we need to merge the frequency
2185 of all instances. For now just never set frequency for these. */
2186 || DECL_ONE_ONLY (current_function_decl))
2187 return;
2188
2189 /* If we are doing the partitioning optimization, let the optimization
2190 choose the correct section into which to put things. */
2191
2192 if (flag_reorder_blocks_and_partition)
2193 return;
2194
2195 if (cfun->function_frequency == FUNCTION_FREQUENCY_HOT)
2196 DECL_SECTION_NAME (current_function_decl) =
2197 build_string (strlen (HOT_TEXT_SECTION_NAME), HOT_TEXT_SECTION_NAME);
2198 if (cfun->function_frequency == FUNCTION_FREQUENCY_UNLIKELY_EXECUTED)
2199 DECL_SECTION_NAME (current_function_decl) =
2200 build_string (strlen (UNLIKELY_EXECUTED_TEXT_SECTION_NAME),
2201 UNLIKELY_EXECUTED_TEXT_SECTION_NAME);
2202 }
2203
2204 static bool
2205 gate_estimate_probability (void)
2206 {
2207 return flag_guess_branch_prob;
2208 }
2209
2210 /* Build PREDICT_EXPR. */
2211 tree
2212 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2213 {
2214 tree t = build1 (PREDICT_EXPR, void_type_node,
2215 build_int_cst (NULL, predictor));
2216 SET_PREDICT_EXPR_OUTCOME (t, taken);
2217 return t;
2218 }
2219
2220 const char *
2221 predictor_name (enum br_predictor predictor)
2222 {
2223 return predictor_info[predictor].name;
2224 }
2225
2226 struct gimple_opt_pass pass_profile =
2227 {
2228 {
2229 GIMPLE_PASS,
2230 "profile", /* name */
2231 gate_estimate_probability, /* gate */
2232 tree_estimate_probability_driver, /* execute */
2233 NULL, /* sub */
2234 NULL, /* next */
2235 0, /* static_pass_number */
2236 TV_BRANCH_PROB, /* tv_id */
2237 PROP_cfg, /* properties_required */
2238 0, /* properties_provided */
2239 0, /* properties_destroyed */
2240 0, /* todo_flags_start */
2241 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2242 }
2243 };
2244
2245 struct gimple_opt_pass pass_strip_predict_hints =
2246 {
2247 {
2248 GIMPLE_PASS,
2249 NULL, /* name */
2250 NULL, /* gate */
2251 strip_predict_hints, /* execute */
2252 NULL, /* sub */
2253 NULL, /* next */
2254 0, /* static_pass_number */
2255 TV_BRANCH_PROB, /* tv_id */
2256 PROP_cfg, /* properties_required */
2257 0, /* properties_provided */
2258 0, /* properties_destroyed */
2259 0, /* todo_flags_start */
2260 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2261 }
2262 };