predict.c (tree_estimate_probability_driver): Normalize the loop when initializing...
[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, 2010
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 "function.h"
44 #include "except.h"
45 #include "diagnostic-core.h"
46 #include "recog.h"
47 #include "expr.h"
48 #include "predict.h"
49 #include "coverage.h"
50 #include "sreal.h"
51 #include "params.h"
52 #include "target.h"
53 #include "cfgloop.h"
54 #include "tree-flow.h"
55 #include "ggc.h"
56 #include "tree-pass.h"
57 #include "tree-scalar-evolution.h"
58 #include "cfgloop.h"
59 #include "pointer-set.h"
60
61 /* real constants: 0, 1, 1-1/REG_BR_PROB_BASE, REG_BR_PROB_BASE,
62 1/REG_BR_PROB_BASE, 0.5, BB_FREQ_MAX. */
63 static sreal real_zero, real_one, real_almost_one, real_br_prob_base,
64 real_inv_br_prob_base, real_one_half, real_bb_freq_max;
65
66 /* Random guesstimation given names.
67 PROV_VERY_UNLIKELY should be small enough so basic block predicted
68 by it gets bellow HOT_BB_FREQUENCY_FRANCTION. */
69 #define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
70 #define PROB_EVEN (REG_BR_PROB_BASE / 2)
71 #define PROB_VERY_LIKELY (REG_BR_PROB_BASE - PROB_VERY_UNLIKELY)
72 #define PROB_ALWAYS (REG_BR_PROB_BASE)
73
74 static void combine_predictions_for_insn (rtx, basic_block);
75 static void dump_prediction (FILE *, enum br_predictor, int, basic_block, int);
76 static void predict_paths_leading_to (basic_block, enum br_predictor, enum prediction);
77 static void predict_paths_leading_to_edge (edge, enum br_predictor, enum prediction);
78 static bool can_predict_insn_p (const_rtx);
79
80 /* Information we hold about each branch predictor.
81 Filled using information from predict.def. */
82
83 struct predictor_info
84 {
85 const char *const name; /* Name used in the debugging dumps. */
86 const int hitrate; /* Expected hitrate used by
87 predict_insn_def call. */
88 const int flags;
89 };
90
91 /* Use given predictor without Dempster-Shaffer theory if it matches
92 using first_match heuristics. */
93 #define PRED_FLAG_FIRST_MATCH 1
94
95 /* Recompute hitrate in percent to our representation. */
96
97 #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
98
99 #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
100 static const struct predictor_info predictor_info[]= {
101 #include "predict.def"
102
103 /* Upper bound on predictors. */
104 {NULL, 0, 0}
105 };
106 #undef DEF_PREDICTOR
107
108 /* Return TRUE if frequency FREQ is considered to be hot. */
109
110 static inline bool
111 maybe_hot_frequency_p (int freq)
112 {
113 struct cgraph_node *node = cgraph_get_node (current_function_decl);
114 if (!profile_info || !flag_branch_probabilities)
115 {
116 if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
117 return false;
118 if (node->frequency == NODE_FREQUENCY_HOT)
119 return true;
120 }
121 if (profile_status == PROFILE_ABSENT)
122 return true;
123 if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
124 && freq < (ENTRY_BLOCK_PTR->frequency * 2 / 3))
125 return false;
126 if (freq < ENTRY_BLOCK_PTR->frequency / 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 /* Make sure CFUN exists, for dump_bb_info. */
152 gcc_assert (cfun);
153 if (profile_status == PROFILE_READ)
154 return maybe_hot_count_p (bb->count);
155 return maybe_hot_frequency_p (bb->frequency);
156 }
157
158 /* Return true if the call can be hot. */
159
160 bool
161 cgraph_maybe_hot_edge_p (struct cgraph_edge *edge)
162 {
163 if (profile_info && flag_branch_probabilities
164 && (edge->count
165 <= profile_info->sum_max / PARAM_VALUE (HOT_BB_COUNT_FRACTION)))
166 return false;
167 if (edge->caller->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED
168 || edge->callee->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
169 return false;
170 if (edge->caller->frequency > NODE_FREQUENCY_UNLIKELY_EXECUTED
171 && edge->callee->frequency <= NODE_FREQUENCY_EXECUTED_ONCE)
172 return false;
173 if (optimize_size)
174 return false;
175 if (edge->caller->frequency == NODE_FREQUENCY_HOT)
176 return true;
177 if (edge->caller->frequency == NODE_FREQUENCY_EXECUTED_ONCE
178 && edge->frequency < CGRAPH_FREQ_BASE * 3 / 2)
179 return false;
180 if (flag_guess_branch_prob
181 && edge->frequency <= (CGRAPH_FREQ_BASE
182 / PARAM_VALUE (HOT_BB_FREQUENCY_FRACTION)))
183 return false;
184 return true;
185 }
186
187 /* Return true in case BB can be CPU intensive and should be optimized
188 for maximal performance. */
189
190 bool
191 maybe_hot_edge_p (edge e)
192 {
193 if (profile_status == PROFILE_READ)
194 return maybe_hot_count_p (e->count);
195 return maybe_hot_frequency_p (EDGE_FREQUENCY (e));
196 }
197
198
199 /* Return true in case BB is probably never executed. */
200
201 bool
202 probably_never_executed_bb_p (const_basic_block bb)
203 {
204 /* Make sure CFUN exists, for dump_bb_info. */
205 gcc_assert (cfun);
206 if (profile_info && flag_branch_probabilities)
207 return ((bb->count + profile_info->runs / 2) / profile_info->runs) == 0;
208 if ((!profile_info || !flag_branch_probabilities)
209 && (cgraph_get_node (current_function_decl)->frequency
210 == NODE_FREQUENCY_UNLIKELY_EXECUTED))
211 return true;
212 return false;
213 }
214
215 /* Return true if NODE should be optimized for size. */
216
217 bool
218 cgraph_optimize_for_size_p (struct cgraph_node *node)
219 {
220 if (optimize_size)
221 return true;
222 if (node && (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED))
223 return true;
224 else
225 return false;
226 }
227
228 /* Return true when current function should always be optimized for size. */
229
230 bool
231 optimize_function_for_size_p (struct function *fun)
232 {
233 if (optimize_size)
234 return true;
235 if (!fun || !fun->decl)
236 return false;
237 return cgraph_optimize_for_size_p (cgraph_get_node (fun->decl));
238 }
239
240 /* Return true when current function should always be optimized for speed. */
241
242 bool
243 optimize_function_for_speed_p (struct function *fun)
244 {
245 return !optimize_function_for_size_p (fun);
246 }
247
248 /* Return TRUE when BB should be optimized for size. */
249
250 bool
251 optimize_bb_for_size_p (const_basic_block bb)
252 {
253 return optimize_function_for_size_p (cfun) || !maybe_hot_bb_p (bb);
254 }
255
256 /* Return TRUE when BB should be optimized for speed. */
257
258 bool
259 optimize_bb_for_speed_p (const_basic_block bb)
260 {
261 return !optimize_bb_for_size_p (bb);
262 }
263
264 /* Return TRUE when BB should be optimized for size. */
265
266 bool
267 optimize_edge_for_size_p (edge e)
268 {
269 return optimize_function_for_size_p (cfun) || !maybe_hot_edge_p (e);
270 }
271
272 /* Return TRUE when BB should be optimized for speed. */
273
274 bool
275 optimize_edge_for_speed_p (edge e)
276 {
277 return !optimize_edge_for_size_p (e);
278 }
279
280 /* Return TRUE when BB should be optimized for size. */
281
282 bool
283 optimize_insn_for_size_p (void)
284 {
285 return optimize_function_for_size_p (cfun) || !crtl->maybe_hot_insn_p;
286 }
287
288 /* Return TRUE when BB should be optimized for speed. */
289
290 bool
291 optimize_insn_for_speed_p (void)
292 {
293 return !optimize_insn_for_size_p ();
294 }
295
296 /* Return TRUE when LOOP should be optimized for size. */
297
298 bool
299 optimize_loop_for_size_p (struct loop *loop)
300 {
301 return optimize_bb_for_size_p (loop->header);
302 }
303
304 /* Return TRUE when LOOP should be optimized for speed. */
305
306 bool
307 optimize_loop_for_speed_p (struct loop *loop)
308 {
309 return optimize_bb_for_speed_p (loop->header);
310 }
311
312 /* Return TRUE when LOOP nest should be optimized for speed. */
313
314 bool
315 optimize_loop_nest_for_speed_p (struct loop *loop)
316 {
317 struct loop *l = loop;
318 if (optimize_loop_for_speed_p (loop))
319 return true;
320 l = loop->inner;
321 while (l && l != loop)
322 {
323 if (optimize_loop_for_speed_p (l))
324 return true;
325 if (l->inner)
326 l = l->inner;
327 else if (l->next)
328 l = l->next;
329 else
330 {
331 while (l != loop && !l->next)
332 l = loop_outer (l);
333 if (l != loop)
334 l = l->next;
335 }
336 }
337 return false;
338 }
339
340 /* Return TRUE when LOOP nest should be optimized for size. */
341
342 bool
343 optimize_loop_nest_for_size_p (struct loop *loop)
344 {
345 return !optimize_loop_nest_for_speed_p (loop);
346 }
347
348 /* Return true when edge E is likely to be well predictable by branch
349 predictor. */
350
351 bool
352 predictable_edge_p (edge e)
353 {
354 if (profile_status == PROFILE_ABSENT)
355 return false;
356 if ((e->probability
357 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100)
358 || (REG_BR_PROB_BASE - e->probability
359 <= PARAM_VALUE (PARAM_PREDICTABLE_BRANCH_OUTCOME) * REG_BR_PROB_BASE / 100))
360 return true;
361 return false;
362 }
363
364
365 /* Set RTL expansion for BB profile. */
366
367 void
368 rtl_profile_for_bb (basic_block bb)
369 {
370 crtl->maybe_hot_insn_p = maybe_hot_bb_p (bb);
371 }
372
373 /* Set RTL expansion for edge profile. */
374
375 void
376 rtl_profile_for_edge (edge e)
377 {
378 crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
379 }
380
381 /* Set RTL expansion to default mode (i.e. when profile info is not known). */
382 void
383 default_rtl_profile (void)
384 {
385 crtl->maybe_hot_insn_p = true;
386 }
387
388 /* Return true if the one of outgoing edges is already predicted by
389 PREDICTOR. */
390
391 bool
392 rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
393 {
394 rtx note;
395 if (!INSN_P (BB_END (bb)))
396 return false;
397 for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
398 if (REG_NOTE_KIND (note) == REG_BR_PRED
399 && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
400 return true;
401 return false;
402 }
403
404 /* This map contains for a basic block the list of predictions for the
405 outgoing edges. */
406
407 static struct pointer_map_t *bb_predictions;
408
409 /* Structure representing predictions in tree level. */
410
411 struct edge_prediction {
412 struct edge_prediction *ep_next;
413 edge ep_edge;
414 enum br_predictor ep_predictor;
415 int ep_probability;
416 };
417
418 /* Return true if the one of outgoing edges is already predicted by
419 PREDICTOR. */
420
421 bool
422 gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
423 {
424 struct edge_prediction *i;
425 void **preds = pointer_map_contains (bb_predictions, bb);
426
427 if (!preds)
428 return false;
429
430 for (i = (struct edge_prediction *) *preds; i; i = i->ep_next)
431 if (i->ep_predictor == predictor)
432 return true;
433 return false;
434 }
435
436 /* Return true when the probability of edge is reliable.
437
438 The profile guessing code is good at predicting branch outcome (ie.
439 taken/not taken), that is predicted right slightly over 75% of time.
440 It is however notoriously poor on predicting the probability itself.
441 In general the profile appear a lot flatter (with probabilities closer
442 to 50%) than the reality so it is bad idea to use it to drive optimization
443 such as those disabling dynamic branch prediction for well predictable
444 branches.
445
446 There are two exceptions - edges leading to noreturn edges and edges
447 predicted by number of iterations heuristics are predicted well. This macro
448 should be able to distinguish those, but at the moment it simply check for
449 noreturn heuristic that is only one giving probability over 99% or bellow
450 1%. In future we might want to propagate reliability information across the
451 CFG if we find this information useful on multiple places. */
452 static bool
453 probability_reliable_p (int prob)
454 {
455 return (profile_status == PROFILE_READ
456 || (profile_status == PROFILE_GUESSED
457 && (prob <= HITRATE (1) || prob >= HITRATE (99))));
458 }
459
460 /* Same predicate as above, working on edges. */
461 bool
462 edge_probability_reliable_p (const_edge e)
463 {
464 return probability_reliable_p (e->probability);
465 }
466
467 /* Same predicate as edge_probability_reliable_p, working on notes. */
468 bool
469 br_prob_note_reliable_p (const_rtx note)
470 {
471 gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
472 return probability_reliable_p (INTVAL (XEXP (note, 0)));
473 }
474
475 static void
476 predict_insn (rtx insn, enum br_predictor predictor, int probability)
477 {
478 gcc_assert (any_condjump_p (insn));
479 if (!flag_guess_branch_prob)
480 return;
481
482 add_reg_note (insn, REG_BR_PRED,
483 gen_rtx_CONCAT (VOIDmode,
484 GEN_INT ((int) predictor),
485 GEN_INT ((int) probability)));
486 }
487
488 /* Predict insn by given predictor. */
489
490 void
491 predict_insn_def (rtx insn, enum br_predictor predictor,
492 enum prediction taken)
493 {
494 int probability = predictor_info[(int) predictor].hitrate;
495
496 if (taken != TAKEN)
497 probability = REG_BR_PROB_BASE - probability;
498
499 predict_insn (insn, predictor, probability);
500 }
501
502 /* Predict edge E with given probability if possible. */
503
504 void
505 rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
506 {
507 rtx last_insn;
508 last_insn = BB_END (e->src);
509
510 /* We can store the branch prediction information only about
511 conditional jumps. */
512 if (!any_condjump_p (last_insn))
513 return;
514
515 /* We always store probability of branching. */
516 if (e->flags & EDGE_FALLTHRU)
517 probability = REG_BR_PROB_BASE - probability;
518
519 predict_insn (last_insn, predictor, probability);
520 }
521
522 /* Predict edge E with the given PROBABILITY. */
523 void
524 gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
525 {
526 gcc_assert (profile_status != PROFILE_GUESSED);
527 if ((e->src != ENTRY_BLOCK_PTR && EDGE_COUNT (e->src->succs) > 1)
528 && flag_guess_branch_prob && optimize)
529 {
530 struct edge_prediction *i = XNEW (struct edge_prediction);
531 void **preds = pointer_map_insert (bb_predictions, e->src);
532
533 i->ep_next = (struct edge_prediction *) *preds;
534 *preds = i;
535 i->ep_probability = probability;
536 i->ep_predictor = predictor;
537 i->ep_edge = e;
538 }
539 }
540
541 /* Remove all predictions on given basic block that are attached
542 to edge E. */
543 void
544 remove_predictions_associated_with_edge (edge e)
545 {
546 void **preds;
547
548 if (!bb_predictions)
549 return;
550
551 preds = pointer_map_contains (bb_predictions, e->src);
552
553 if (preds)
554 {
555 struct edge_prediction **prediction = (struct edge_prediction **) preds;
556 struct edge_prediction *next;
557
558 while (*prediction)
559 {
560 if ((*prediction)->ep_edge == e)
561 {
562 next = (*prediction)->ep_next;
563 free (*prediction);
564 *prediction = next;
565 }
566 else
567 prediction = &((*prediction)->ep_next);
568 }
569 }
570 }
571
572 /* Clears the list of predictions stored for BB. */
573
574 static void
575 clear_bb_predictions (basic_block bb)
576 {
577 void **preds = pointer_map_contains (bb_predictions, bb);
578 struct edge_prediction *pred, *next;
579
580 if (!preds)
581 return;
582
583 for (pred = (struct edge_prediction *) *preds; pred; pred = next)
584 {
585 next = pred->ep_next;
586 free (pred);
587 }
588 *preds = NULL;
589 }
590
591 /* Return true when we can store prediction on insn INSN.
592 At the moment we represent predictions only on conditional
593 jumps, not at computed jump or other complicated cases. */
594 static bool
595 can_predict_insn_p (const_rtx insn)
596 {
597 return (JUMP_P (insn)
598 && any_condjump_p (insn)
599 && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
600 }
601
602 /* Predict edge E by given predictor if possible. */
603
604 void
605 predict_edge_def (edge e, enum br_predictor predictor,
606 enum prediction taken)
607 {
608 int probability = predictor_info[(int) predictor].hitrate;
609
610 if (taken != TAKEN)
611 probability = REG_BR_PROB_BASE - probability;
612
613 predict_edge (e, predictor, probability);
614 }
615
616 /* Invert all branch predictions or probability notes in the INSN. This needs
617 to be done each time we invert the condition used by the jump. */
618
619 void
620 invert_br_probabilities (rtx insn)
621 {
622 rtx note;
623
624 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
625 if (REG_NOTE_KIND (note) == REG_BR_PROB)
626 XEXP (note, 0) = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (note, 0)));
627 else if (REG_NOTE_KIND (note) == REG_BR_PRED)
628 XEXP (XEXP (note, 0), 1)
629 = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
630 }
631
632 /* Dump information about the branch prediction to the output file. */
633
634 static void
635 dump_prediction (FILE *file, enum br_predictor predictor, int probability,
636 basic_block bb, int used)
637 {
638 edge e;
639 edge_iterator ei;
640
641 if (!file)
642 return;
643
644 FOR_EACH_EDGE (e, ei, bb->succs)
645 if (! (e->flags & EDGE_FALLTHRU))
646 break;
647
648 fprintf (file, " %s heuristics%s: %.1f%%",
649 predictor_info[predictor].name,
650 used ? "" : " (ignored)", probability * 100.0 / REG_BR_PROB_BASE);
651
652 if (bb->count)
653 {
654 fprintf (file, " exec ");
655 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, bb->count);
656 if (e)
657 {
658 fprintf (file, " hit ");
659 fprintf (file, HOST_WIDEST_INT_PRINT_DEC, e->count);
660 fprintf (file, " (%.1f%%)", e->count * 100.0 / bb->count);
661 }
662 }
663
664 fprintf (file, "\n");
665 }
666
667 /* We can not predict the probabilities of outgoing edges of bb. Set them
668 evenly and hope for the best. */
669 static void
670 set_even_probabilities (basic_block bb)
671 {
672 int nedges = 0;
673 edge e;
674 edge_iterator ei;
675
676 FOR_EACH_EDGE (e, ei, bb->succs)
677 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
678 nedges ++;
679 FOR_EACH_EDGE (e, ei, bb->succs)
680 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
681 e->probability = (REG_BR_PROB_BASE + nedges / 2) / nedges;
682 else
683 e->probability = 0;
684 }
685
686 /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
687 note if not already present. Remove now useless REG_BR_PRED notes. */
688
689 static void
690 combine_predictions_for_insn (rtx insn, basic_block bb)
691 {
692 rtx prob_note;
693 rtx *pnote;
694 rtx note;
695 int best_probability = PROB_EVEN;
696 enum br_predictor best_predictor = END_PREDICTORS;
697 int combined_probability = REG_BR_PROB_BASE / 2;
698 int d;
699 bool first_match = false;
700 bool found = false;
701
702 if (!can_predict_insn_p (insn))
703 {
704 set_even_probabilities (bb);
705 return;
706 }
707
708 prob_note = find_reg_note (insn, REG_BR_PROB, 0);
709 pnote = &REG_NOTES (insn);
710 if (dump_file)
711 fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
712 bb->index);
713
714 /* We implement "first match" heuristics and use probability guessed
715 by predictor with smallest index. */
716 for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
717 if (REG_NOTE_KIND (note) == REG_BR_PRED)
718 {
719 enum br_predictor predictor = ((enum br_predictor)
720 INTVAL (XEXP (XEXP (note, 0), 0)));
721 int probability = INTVAL (XEXP (XEXP (note, 0), 1));
722
723 found = true;
724 if (best_predictor > predictor)
725 best_probability = probability, best_predictor = predictor;
726
727 d = (combined_probability * probability
728 + (REG_BR_PROB_BASE - combined_probability)
729 * (REG_BR_PROB_BASE - probability));
730
731 /* Use FP math to avoid overflows of 32bit integers. */
732 if (d == 0)
733 /* If one probability is 0% and one 100%, avoid division by zero. */
734 combined_probability = REG_BR_PROB_BASE / 2;
735 else
736 combined_probability = (((double) combined_probability) * probability
737 * REG_BR_PROB_BASE / d + 0.5);
738 }
739
740 /* Decide which heuristic to use. In case we didn't match anything,
741 use no_prediction heuristic, in case we did match, use either
742 first match or Dempster-Shaffer theory depending on the flags. */
743
744 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
745 first_match = true;
746
747 if (!found)
748 dump_prediction (dump_file, PRED_NO_PREDICTION,
749 combined_probability, bb, true);
750 else
751 {
752 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
753 bb, !first_match);
754 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
755 bb, first_match);
756 }
757
758 if (first_match)
759 combined_probability = best_probability;
760 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
761
762 while (*pnote)
763 {
764 if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
765 {
766 enum br_predictor predictor = ((enum br_predictor)
767 INTVAL (XEXP (XEXP (*pnote, 0), 0)));
768 int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
769
770 dump_prediction (dump_file, predictor, probability, bb,
771 !first_match || best_predictor == predictor);
772 *pnote = XEXP (*pnote, 1);
773 }
774 else
775 pnote = &XEXP (*pnote, 1);
776 }
777
778 if (!prob_note)
779 {
780 add_reg_note (insn, REG_BR_PROB, GEN_INT (combined_probability));
781
782 /* Save the prediction into CFG in case we are seeing non-degenerated
783 conditional jump. */
784 if (!single_succ_p (bb))
785 {
786 BRANCH_EDGE (bb)->probability = combined_probability;
787 FALLTHRU_EDGE (bb)->probability
788 = REG_BR_PROB_BASE - combined_probability;
789 }
790 }
791 else if (!single_succ_p (bb))
792 {
793 int prob = INTVAL (XEXP (prob_note, 0));
794
795 BRANCH_EDGE (bb)->probability = prob;
796 FALLTHRU_EDGE (bb)->probability = REG_BR_PROB_BASE - prob;
797 }
798 else
799 single_succ_edge (bb)->probability = REG_BR_PROB_BASE;
800 }
801
802 /* Combine predictions into single probability and store them into CFG.
803 Remove now useless prediction entries. */
804
805 static void
806 combine_predictions_for_bb (basic_block bb)
807 {
808 int best_probability = PROB_EVEN;
809 enum br_predictor best_predictor = END_PREDICTORS;
810 int combined_probability = REG_BR_PROB_BASE / 2;
811 int d;
812 bool first_match = false;
813 bool found = false;
814 struct edge_prediction *pred;
815 int nedges = 0;
816 edge e, first = NULL, second = NULL;
817 edge_iterator ei;
818 void **preds;
819
820 FOR_EACH_EDGE (e, ei, bb->succs)
821 if (!(e->flags & (EDGE_EH | EDGE_FAKE)))
822 {
823 nedges ++;
824 if (first && !second)
825 second = e;
826 if (!first)
827 first = e;
828 }
829
830 /* When there is no successor or only one choice, prediction is easy.
831
832 We are lazy for now and predict only basic blocks with two outgoing
833 edges. It is possible to predict generic case too, but we have to
834 ignore first match heuristics and do more involved combining. Implement
835 this later. */
836 if (nedges != 2)
837 {
838 if (!bb->count)
839 set_even_probabilities (bb);
840 clear_bb_predictions (bb);
841 if (dump_file)
842 fprintf (dump_file, "%i edges in bb %i predicted to even probabilities\n",
843 nedges, bb->index);
844 return;
845 }
846
847 if (dump_file)
848 fprintf (dump_file, "Predictions for bb %i\n", bb->index);
849
850 preds = pointer_map_contains (bb_predictions, bb);
851 if (preds)
852 {
853 /* We implement "first match" heuristics and use probability guessed
854 by predictor with smallest index. */
855 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
856 {
857 enum br_predictor predictor = pred->ep_predictor;
858 int probability = pred->ep_probability;
859
860 if (pred->ep_edge != first)
861 probability = REG_BR_PROB_BASE - probability;
862
863 found = true;
864 /* First match heuristics would be widly confused if we predicted
865 both directions. */
866 if (best_predictor > predictor)
867 {
868 struct edge_prediction *pred2;
869 int prob = probability;
870
871 for (pred2 = (struct edge_prediction *) *preds; pred2; pred2 = pred2->ep_next)
872 if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
873 {
874 int probability2 = pred->ep_probability;
875
876 if (pred2->ep_edge != first)
877 probability2 = REG_BR_PROB_BASE - probability2;
878
879 if ((probability < REG_BR_PROB_BASE / 2) !=
880 (probability2 < REG_BR_PROB_BASE / 2))
881 break;
882
883 /* If the same predictor later gave better result, go for it! */
884 if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
885 || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
886 prob = probability2;
887 }
888 if (!pred2)
889 best_probability = prob, best_predictor = predictor;
890 }
891
892 d = (combined_probability * probability
893 + (REG_BR_PROB_BASE - combined_probability)
894 * (REG_BR_PROB_BASE - probability));
895
896 /* Use FP math to avoid overflows of 32bit integers. */
897 if (d == 0)
898 /* If one probability is 0% and one 100%, avoid division by zero. */
899 combined_probability = REG_BR_PROB_BASE / 2;
900 else
901 combined_probability = (((double) combined_probability)
902 * probability
903 * REG_BR_PROB_BASE / d + 0.5);
904 }
905 }
906
907 /* Decide which heuristic to use. In case we didn't match anything,
908 use no_prediction heuristic, in case we did match, use either
909 first match or Dempster-Shaffer theory depending on the flags. */
910
911 if (predictor_info [best_predictor].flags & PRED_FLAG_FIRST_MATCH)
912 first_match = true;
913
914 if (!found)
915 dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb, true);
916 else
917 {
918 dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
919 !first_match);
920 dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
921 first_match);
922 }
923
924 if (first_match)
925 combined_probability = best_probability;
926 dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb, true);
927
928 if (preds)
929 {
930 for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
931 {
932 enum br_predictor predictor = pred->ep_predictor;
933 int probability = pred->ep_probability;
934
935 if (pred->ep_edge != EDGE_SUCC (bb, 0))
936 probability = REG_BR_PROB_BASE - probability;
937 dump_prediction (dump_file, predictor, probability, bb,
938 !first_match || best_predictor == predictor);
939 }
940 }
941 clear_bb_predictions (bb);
942
943 if (!bb->count)
944 {
945 first->probability = combined_probability;
946 second->probability = REG_BR_PROB_BASE - combined_probability;
947 }
948 }
949
950 /* Check if T1 and T2 satisfy the IV_COMPARE condition.
951 Return the SSA_NAME if the condition satisfies, NULL otherwise.
952
953 T1 and T2 should be one of the following cases:
954 1. T1 is SSA_NAME, T2 is NULL
955 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
956 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
957
958 static tree
959 strips_small_constant (tree t1, tree t2)
960 {
961 tree ret = NULL;
962 int value = 0;
963
964 if (!t1)
965 return NULL;
966 else if (TREE_CODE (t1) == SSA_NAME)
967 ret = t1;
968 else if (host_integerp (t1, 0))
969 value = tree_low_cst (t1, 0);
970 else
971 return NULL;
972
973 if (!t2)
974 return ret;
975 else if (host_integerp (t2, 0))
976 value = tree_low_cst (t2, 0);
977 else if (TREE_CODE (t2) == SSA_NAME)
978 {
979 if (ret)
980 return NULL;
981 else
982 ret = t2;
983 }
984
985 if (value <= 4 && value >= -4)
986 return ret;
987 else
988 return NULL;
989 }
990
991 /* Return the SSA_NAME in T or T's operands.
992 Return NULL if SSA_NAME cannot be found. */
993
994 static tree
995 get_base_value (tree t)
996 {
997 if (TREE_CODE (t) == SSA_NAME)
998 return t;
999
1000 if (!BINARY_CLASS_P (t))
1001 return NULL;
1002
1003 switch (TREE_OPERAND_LENGTH (t))
1004 {
1005 case 1:
1006 return strips_small_constant (TREE_OPERAND (t, 0), NULL);
1007 case 2:
1008 return strips_small_constant (TREE_OPERAND (t, 0),
1009 TREE_OPERAND (t, 1));
1010 default:
1011 return NULL;
1012 }
1013 }
1014
1015 /* Check the compare STMT in LOOP. If it compares an induction
1016 variable to a loop invariant, return true, and save
1017 LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1018 Otherwise return false and set LOOP_INVAIANT to NULL. */
1019
1020 static bool
1021 is_comparison_with_loop_invariant_p (gimple stmt, struct loop *loop,
1022 tree *loop_invariant,
1023 enum tree_code *compare_code,
1024 int *loop_step,
1025 tree *loop_iv_base)
1026 {
1027 tree op0, op1, bound, base;
1028 affine_iv iv0, iv1;
1029 enum tree_code code;
1030 int step;
1031
1032 code = gimple_cond_code (stmt);
1033 *loop_invariant = NULL;
1034
1035 switch (code)
1036 {
1037 case GT_EXPR:
1038 case GE_EXPR:
1039 case NE_EXPR:
1040 case LT_EXPR:
1041 case LE_EXPR:
1042 case EQ_EXPR:
1043 break;
1044
1045 default:
1046 return false;
1047 }
1048
1049 op0 = gimple_cond_lhs (stmt);
1050 op1 = gimple_cond_rhs (stmt);
1051
1052 if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1053 || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1054 return false;
1055 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1056 return false;
1057 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1058 return false;
1059 if (TREE_CODE (iv0.step) != INTEGER_CST
1060 || TREE_CODE (iv1.step) != INTEGER_CST)
1061 return false;
1062 if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1063 || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1064 return false;
1065
1066 if (integer_zerop (iv0.step))
1067 {
1068 if (code != NE_EXPR && code != EQ_EXPR)
1069 code = invert_tree_comparison (code, false);
1070 bound = iv0.base;
1071 base = iv1.base;
1072 if (host_integerp (iv1.step, 0))
1073 step = tree_low_cst (iv1.step, 0);
1074 else
1075 return false;
1076 }
1077 else
1078 {
1079 bound = iv1.base;
1080 base = iv0.base;
1081 if (host_integerp (iv0.step, 0))
1082 step = tree_low_cst (iv0.step, 0);
1083 else
1084 return false;
1085 }
1086
1087 if (TREE_CODE (bound) != INTEGER_CST)
1088 bound = get_base_value (bound);
1089 if (!bound)
1090 return false;
1091 if (TREE_CODE (base) != INTEGER_CST)
1092 base = get_base_value (base);
1093 if (!base)
1094 return false;
1095
1096 *loop_invariant = bound;
1097 *compare_code = code;
1098 *loop_step = step;
1099 *loop_iv_base = base;
1100 return true;
1101 }
1102
1103 /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1104
1105 static bool
1106 expr_coherent_p (tree t1, tree t2)
1107 {
1108 gimple stmt;
1109 tree ssa_name_1 = NULL;
1110 tree ssa_name_2 = NULL;
1111
1112 gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1113 gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1114
1115 if (t1 == t2)
1116 return true;
1117
1118 if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1119 return true;
1120 if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1121 return false;
1122
1123 /* Check to see if t1 is expressed/defined with t2. */
1124 stmt = SSA_NAME_DEF_STMT (t1);
1125 gcc_assert (stmt != NULL);
1126 if (is_gimple_assign (stmt))
1127 {
1128 ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1129 if (ssa_name_1 && ssa_name_1 == t2)
1130 return true;
1131 }
1132
1133 /* Check to see if t2 is expressed/defined with t1. */
1134 stmt = SSA_NAME_DEF_STMT (t2);
1135 gcc_assert (stmt != NULL);
1136 if (is_gimple_assign (stmt))
1137 {
1138 ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1139 if (ssa_name_2 && ssa_name_2 == t1)
1140 return true;
1141 }
1142
1143 /* Compare if t1 and t2's def_stmts are identical. */
1144 if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1145 return true;
1146 else
1147 return false;
1148 }
1149
1150 /* Predict branch probability of BB when BB contains a branch that compares
1151 an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1152 loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1153
1154 E.g.
1155 for (int i = 0; i < bound; i++) {
1156 if (i < bound - 2)
1157 computation_1();
1158 else
1159 computation_2();
1160 }
1161
1162 In this loop, we will predict the branch inside the loop to be taken. */
1163
1164 static void
1165 predict_iv_comparison (struct loop *loop, basic_block bb,
1166 tree loop_bound_var,
1167 tree loop_iv_base_var,
1168 enum tree_code loop_bound_code,
1169 int loop_bound_step)
1170 {
1171 gimple stmt;
1172 tree compare_var, compare_base;
1173 enum tree_code compare_code;
1174 int compare_step;
1175 edge then_edge;
1176 edge_iterator ei;
1177
1178 if (predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1179 || predicted_by_p (bb, PRED_LOOP_ITERATIONS)
1180 || predicted_by_p (bb, PRED_LOOP_EXIT))
1181 return;
1182
1183 stmt = last_stmt (bb);
1184 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1185 return;
1186 if (!is_comparison_with_loop_invariant_p (stmt, loop, &compare_var,
1187 &compare_code,
1188 &compare_step,
1189 &compare_base))
1190 return;
1191
1192 /* Find the taken edge. */
1193 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1194 if (then_edge->flags & EDGE_TRUE_VALUE)
1195 break;
1196
1197 /* When comparing an IV to a loop invariant, NE is more likely to be
1198 taken while EQ is more likely to be not-taken. */
1199 if (compare_code == NE_EXPR)
1200 {
1201 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1202 return;
1203 }
1204 else if (compare_code == EQ_EXPR)
1205 {
1206 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1207 return;
1208 }
1209
1210 if (!expr_coherent_p (loop_iv_base_var, compare_base))
1211 return;
1212
1213 /* If loop bound, base and compare bound are all constants, we can
1214 calculate the probability directly. */
1215 if (host_integerp (loop_bound_var, 0)
1216 && host_integerp (compare_var, 0)
1217 && host_integerp (compare_base, 0))
1218 {
1219 int probability;
1220 HOST_WIDE_INT compare_count;
1221 HOST_WIDE_INT loop_bound = tree_low_cst (loop_bound_var, 0);
1222 HOST_WIDE_INT compare_bound = tree_low_cst (compare_var, 0);
1223 HOST_WIDE_INT base = tree_low_cst (compare_base, 0);
1224 HOST_WIDE_INT loop_count = (loop_bound - base) / compare_step;
1225
1226 if ((compare_step > 0)
1227 ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1228 compare_count = (loop_bound - compare_bound) / compare_step;
1229 else
1230 compare_count = (compare_bound - base) / compare_step;
1231
1232 if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1233 compare_count ++;
1234 if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1235 loop_count ++;
1236 if (compare_count < 0)
1237 compare_count = 0;
1238 if (loop_count < 0)
1239 loop_count = 0;
1240
1241 if (loop_count == 0)
1242 probability = 0;
1243 else if (compare_count > loop_count)
1244 probability = REG_BR_PROB_BASE;
1245 else
1246 probability = (double) REG_BR_PROB_BASE * compare_count / loop_count;
1247 predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1248 return;
1249 }
1250
1251 if (expr_coherent_p (loop_bound_var, compare_var))
1252 {
1253 if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1254 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1255 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1256 else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1257 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1258 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1259 else if (loop_bound_code == NE_EXPR)
1260 {
1261 /* If the loop backedge condition is "(i != bound)", we do
1262 the comparison based on the step of IV:
1263 * step < 0 : backedge condition is like (i > bound)
1264 * step > 0 : backedge condition is like (i < bound) */
1265 gcc_assert (loop_bound_step != 0);
1266 if (loop_bound_step > 0
1267 && (compare_code == LT_EXPR
1268 || compare_code == LE_EXPR))
1269 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1270 else if (loop_bound_step < 0
1271 && (compare_code == GT_EXPR
1272 || compare_code == GE_EXPR))
1273 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1274 else
1275 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1276 }
1277 else
1278 /* The branch is predicted not-taken if loop_bound_code is
1279 opposite with compare_code. */
1280 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1281 }
1282 else if (expr_coherent_p (loop_iv_base_var, compare_var))
1283 {
1284 /* For cases like:
1285 for (i = s; i < h; i++)
1286 if (i > s + 2) ....
1287 The branch should be predicted taken. */
1288 if (loop_bound_step > 0
1289 && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1290 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1291 else if (loop_bound_step < 0
1292 && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1293 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1294 else
1295 predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1296 }
1297 }
1298
1299 /* Predict edge probabilities by exploiting loop structure. */
1300
1301 static void
1302 predict_loops (void)
1303 {
1304 loop_iterator li;
1305 struct loop *loop;
1306
1307 /* Try to predict out blocks in a loop that are not part of a
1308 natural loop. */
1309 FOR_EACH_LOOP (li, loop, 0)
1310 {
1311 basic_block bb, *bbs;
1312 unsigned j, n_exits;
1313 VEC (edge, heap) *exits;
1314 struct tree_niter_desc niter_desc;
1315 edge ex;
1316 struct nb_iter_bound *nb_iter;
1317 enum tree_code loop_bound_code = ERROR_MARK;
1318 int loop_bound_step = 0;
1319 tree loop_bound_var = NULL;
1320 tree loop_iv_base = NULL;
1321 gimple stmt = NULL;
1322
1323 exits = get_loop_exit_edges (loop);
1324 n_exits = VEC_length (edge, exits);
1325
1326 FOR_EACH_VEC_ELT (edge, exits, j, ex)
1327 {
1328 tree niter = NULL;
1329 HOST_WIDE_INT nitercst;
1330 int max = PARAM_VALUE (PARAM_MAX_PREDICTED_ITERATIONS);
1331 int probability;
1332 enum br_predictor predictor;
1333
1334 if (number_of_iterations_exit (loop, ex, &niter_desc, false))
1335 niter = niter_desc.niter;
1336 if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
1337 niter = loop_niter_by_eval (loop, ex);
1338
1339 if (TREE_CODE (niter) == INTEGER_CST)
1340 {
1341 if (host_integerp (niter, 1)
1342 && compare_tree_int (niter, max-1) == -1)
1343 nitercst = tree_low_cst (niter, 1) + 1;
1344 else
1345 nitercst = max;
1346 predictor = PRED_LOOP_ITERATIONS;
1347 }
1348 /* If we have just one exit and we can derive some information about
1349 the number of iterations of the loop from the statements inside
1350 the loop, use it to predict this exit. */
1351 else if (n_exits == 1)
1352 {
1353 nitercst = estimated_stmt_executions_int (loop);
1354 if (nitercst < 0)
1355 continue;
1356 if (nitercst > max)
1357 nitercst = max;
1358
1359 predictor = PRED_LOOP_ITERATIONS_GUESSED;
1360 }
1361 else
1362 continue;
1363
1364 probability = ((REG_BR_PROB_BASE + nitercst / 2) / nitercst);
1365 predict_edge (ex, predictor, probability);
1366 }
1367 VEC_free (edge, heap, exits);
1368
1369 /* Find information about loop bound variables. */
1370 for (nb_iter = loop->bounds; nb_iter;
1371 nb_iter = nb_iter->next)
1372 if (nb_iter->stmt
1373 && gimple_code (nb_iter->stmt) == GIMPLE_COND)
1374 {
1375 stmt = nb_iter->stmt;
1376 break;
1377 }
1378 if (!stmt && last_stmt (loop->header)
1379 && gimple_code (last_stmt (loop->header)) == GIMPLE_COND)
1380 stmt = last_stmt (loop->header);
1381 if (stmt)
1382 is_comparison_with_loop_invariant_p (stmt, loop,
1383 &loop_bound_var,
1384 &loop_bound_code,
1385 &loop_bound_step,
1386 &loop_iv_base);
1387
1388 bbs = get_loop_body (loop);
1389
1390 for (j = 0; j < loop->num_nodes; j++)
1391 {
1392 int header_found = 0;
1393 edge e;
1394 edge_iterator ei;
1395
1396 bb = bbs[j];
1397
1398 /* Bypass loop heuristics on continue statement. These
1399 statements construct loops via "non-loop" constructs
1400 in the source language and are better to be handled
1401 separately. */
1402 if (predicted_by_p (bb, PRED_CONTINUE))
1403 continue;
1404
1405 /* Loop branch heuristics - predict an edge back to a
1406 loop's head as taken. */
1407 if (bb == loop->latch)
1408 {
1409 e = find_edge (loop->latch, loop->header);
1410 if (e)
1411 {
1412 header_found = 1;
1413 predict_edge_def (e, PRED_LOOP_BRANCH, TAKEN);
1414 }
1415 }
1416
1417 /* Loop exit heuristics - predict an edge exiting the loop if the
1418 conditional has no loop header successors as not taken. */
1419 if (!header_found
1420 /* If we already used more reliable loop exit predictors, do not
1421 bother with PRED_LOOP_EXIT. */
1422 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS_GUESSED)
1423 && !predicted_by_p (bb, PRED_LOOP_ITERATIONS))
1424 {
1425 /* For loop with many exits we don't want to predict all exits
1426 with the pretty large probability, because if all exits are
1427 considered in row, the loop would be predicted to iterate
1428 almost never. The code to divide probability by number of
1429 exits is very rough. It should compute the number of exits
1430 taken in each patch through function (not the overall number
1431 of exits that might be a lot higher for loops with wide switch
1432 statements in them) and compute n-th square root.
1433
1434 We limit the minimal probability by 2% to avoid
1435 EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
1436 as this was causing regression in perl benchmark containing such
1437 a wide loop. */
1438
1439 int probability = ((REG_BR_PROB_BASE
1440 - predictor_info [(int) PRED_LOOP_EXIT].hitrate)
1441 / n_exits);
1442 if (probability < HITRATE (2))
1443 probability = HITRATE (2);
1444 FOR_EACH_EDGE (e, ei, bb->succs)
1445 if (e->dest->index < NUM_FIXED_BLOCKS
1446 || !flow_bb_inside_loop_p (loop, e->dest))
1447 predict_edge (e, PRED_LOOP_EXIT, probability);
1448 }
1449 if (loop_bound_var)
1450 predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
1451 loop_bound_code,
1452 loop_bound_step);
1453 }
1454
1455 /* Free basic blocks from get_loop_body. */
1456 free (bbs);
1457 }
1458 }
1459
1460 /* Attempt to predict probabilities of BB outgoing edges using local
1461 properties. */
1462 static void
1463 bb_estimate_probability_locally (basic_block bb)
1464 {
1465 rtx last_insn = BB_END (bb);
1466 rtx cond;
1467
1468 if (! can_predict_insn_p (last_insn))
1469 return;
1470 cond = get_condition (last_insn, NULL, false, false);
1471 if (! cond)
1472 return;
1473
1474 /* Try "pointer heuristic."
1475 A comparison ptr == 0 is predicted as false.
1476 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1477 if (COMPARISON_P (cond)
1478 && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
1479 || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
1480 {
1481 if (GET_CODE (cond) == EQ)
1482 predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
1483 else if (GET_CODE (cond) == NE)
1484 predict_insn_def (last_insn, PRED_POINTER, TAKEN);
1485 }
1486 else
1487
1488 /* Try "opcode heuristic."
1489 EQ tests are usually false and NE tests are usually true. Also,
1490 most quantities are positive, so we can make the appropriate guesses
1491 about signed comparisons against zero. */
1492 switch (GET_CODE (cond))
1493 {
1494 case CONST_INT:
1495 /* Unconditional branch. */
1496 predict_insn_def (last_insn, PRED_UNCONDITIONAL,
1497 cond == const0_rtx ? NOT_TAKEN : TAKEN);
1498 break;
1499
1500 case EQ:
1501 case UNEQ:
1502 /* Floating point comparisons appears to behave in a very
1503 unpredictable way because of special role of = tests in
1504 FP code. */
1505 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1506 ;
1507 /* Comparisons with 0 are often used for booleans and there is
1508 nothing useful to predict about them. */
1509 else if (XEXP (cond, 1) == const0_rtx
1510 || XEXP (cond, 0) == const0_rtx)
1511 ;
1512 else
1513 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
1514 break;
1515
1516 case NE:
1517 case LTGT:
1518 /* Floating point comparisons appears to behave in a very
1519 unpredictable way because of special role of = tests in
1520 FP code. */
1521 if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
1522 ;
1523 /* Comparisons with 0 are often used for booleans and there is
1524 nothing useful to predict about them. */
1525 else if (XEXP (cond, 1) == const0_rtx
1526 || XEXP (cond, 0) == const0_rtx)
1527 ;
1528 else
1529 predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
1530 break;
1531
1532 case ORDERED:
1533 predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
1534 break;
1535
1536 case UNORDERED:
1537 predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
1538 break;
1539
1540 case LE:
1541 case LT:
1542 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1543 || XEXP (cond, 1) == constm1_rtx)
1544 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
1545 break;
1546
1547 case GE:
1548 case GT:
1549 if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
1550 || XEXP (cond, 1) == constm1_rtx)
1551 predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
1552 break;
1553
1554 default:
1555 break;
1556 }
1557 }
1558
1559 /* Set edge->probability for each successor edge of BB. */
1560 void
1561 guess_outgoing_edge_probabilities (basic_block bb)
1562 {
1563 bb_estimate_probability_locally (bb);
1564 combine_predictions_for_insn (BB_END (bb), bb);
1565 }
1566 \f
1567 static tree expr_expected_value (tree, bitmap);
1568
1569 /* Helper function for expr_expected_value. */
1570
1571 static tree
1572 expr_expected_value_1 (tree type, tree op0, enum tree_code code,
1573 tree op1, bitmap visited)
1574 {
1575 gimple def;
1576
1577 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1578 {
1579 if (TREE_CONSTANT (op0))
1580 return op0;
1581
1582 if (code != SSA_NAME)
1583 return NULL_TREE;
1584
1585 def = SSA_NAME_DEF_STMT (op0);
1586
1587 /* If we were already here, break the infinite cycle. */
1588 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (op0)))
1589 return NULL;
1590
1591 if (gimple_code (def) == GIMPLE_PHI)
1592 {
1593 /* All the arguments of the PHI node must have the same constant
1594 length. */
1595 int i, n = gimple_phi_num_args (def);
1596 tree val = NULL, new_val;
1597
1598 for (i = 0; i < n; i++)
1599 {
1600 tree arg = PHI_ARG_DEF (def, i);
1601
1602 /* If this PHI has itself as an argument, we cannot
1603 determine the string length of this argument. However,
1604 if we can find an expected constant value for the other
1605 PHI args then we can still be sure that this is
1606 likely a constant. So be optimistic and just
1607 continue with the next argument. */
1608 if (arg == PHI_RESULT (def))
1609 continue;
1610
1611 new_val = expr_expected_value (arg, visited);
1612 if (!new_val)
1613 return NULL;
1614 if (!val)
1615 val = new_val;
1616 else if (!operand_equal_p (val, new_val, false))
1617 return NULL;
1618 }
1619 return val;
1620 }
1621 if (is_gimple_assign (def))
1622 {
1623 if (gimple_assign_lhs (def) != op0)
1624 return NULL;
1625
1626 return expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (def)),
1627 gimple_assign_rhs1 (def),
1628 gimple_assign_rhs_code (def),
1629 gimple_assign_rhs2 (def),
1630 visited);
1631 }
1632
1633 if (is_gimple_call (def))
1634 {
1635 tree decl = gimple_call_fndecl (def);
1636 if (!decl)
1637 return NULL;
1638 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
1639 switch (DECL_FUNCTION_CODE (decl))
1640 {
1641 case BUILT_IN_EXPECT:
1642 {
1643 tree val;
1644 if (gimple_call_num_args (def) != 2)
1645 return NULL;
1646 val = gimple_call_arg (def, 0);
1647 if (TREE_CONSTANT (val))
1648 return val;
1649 return gimple_call_arg (def, 1);
1650 }
1651
1652 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
1653 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
1654 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
1655 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
1656 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
1657 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
1658 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
1659 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
1660 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
1661 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
1662 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
1663 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
1664 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
1665 /* Assume that any given atomic operation has low contention,
1666 and thus the compare-and-swap operation succeeds. */
1667 return boolean_true_node;
1668 }
1669 }
1670
1671 return NULL;
1672 }
1673
1674 if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
1675 {
1676 tree res;
1677 op0 = expr_expected_value (op0, visited);
1678 if (!op0)
1679 return NULL;
1680 op1 = expr_expected_value (op1, visited);
1681 if (!op1)
1682 return NULL;
1683 res = fold_build2 (code, type, op0, op1);
1684 if (TREE_CONSTANT (res))
1685 return res;
1686 return NULL;
1687 }
1688 if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
1689 {
1690 tree res;
1691 op0 = expr_expected_value (op0, visited);
1692 if (!op0)
1693 return NULL;
1694 res = fold_build1 (code, type, op0);
1695 if (TREE_CONSTANT (res))
1696 return res;
1697 return NULL;
1698 }
1699 return NULL;
1700 }
1701
1702 /* Return constant EXPR will likely have at execution time, NULL if unknown.
1703 The function is used by builtin_expect branch predictor so the evidence
1704 must come from this construct and additional possible constant folding.
1705
1706 We may want to implement more involved value guess (such as value range
1707 propagation based prediction), but such tricks shall go to new
1708 implementation. */
1709
1710 static tree
1711 expr_expected_value (tree expr, bitmap visited)
1712 {
1713 enum tree_code code;
1714 tree op0, op1;
1715
1716 if (TREE_CONSTANT (expr))
1717 return expr;
1718
1719 extract_ops_from_tree (expr, &code, &op0, &op1);
1720 return expr_expected_value_1 (TREE_TYPE (expr),
1721 op0, code, op1, visited);
1722 }
1723
1724 \f
1725 /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
1726 we no longer need. */
1727 static unsigned int
1728 strip_predict_hints (void)
1729 {
1730 basic_block bb;
1731 gimple ass_stmt;
1732 tree var;
1733
1734 FOR_EACH_BB (bb)
1735 {
1736 gimple_stmt_iterator bi;
1737 for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
1738 {
1739 gimple stmt = gsi_stmt (bi);
1740
1741 if (gimple_code (stmt) == GIMPLE_PREDICT)
1742 {
1743 gsi_remove (&bi, true);
1744 continue;
1745 }
1746 else if (gimple_code (stmt) == GIMPLE_CALL)
1747 {
1748 tree fndecl = gimple_call_fndecl (stmt);
1749
1750 if (fndecl
1751 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1752 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_EXPECT
1753 && gimple_call_num_args (stmt) == 2)
1754 {
1755 var = gimple_call_lhs (stmt);
1756 if (var)
1757 {
1758 ass_stmt
1759 = gimple_build_assign (var, gimple_call_arg (stmt, 0));
1760 gsi_replace (&bi, ass_stmt, true);
1761 }
1762 else
1763 {
1764 gsi_remove (&bi, true);
1765 continue;
1766 }
1767 }
1768 }
1769 gsi_next (&bi);
1770 }
1771 }
1772 return 0;
1773 }
1774 \f
1775 /* Predict using opcode of the last statement in basic block. */
1776 static void
1777 tree_predict_by_opcode (basic_block bb)
1778 {
1779 gimple stmt = last_stmt (bb);
1780 edge then_edge;
1781 tree op0, op1;
1782 tree type;
1783 tree val;
1784 enum tree_code cmp;
1785 bitmap visited;
1786 edge_iterator ei;
1787
1788 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1789 return;
1790 FOR_EACH_EDGE (then_edge, ei, bb->succs)
1791 if (then_edge->flags & EDGE_TRUE_VALUE)
1792 break;
1793 op0 = gimple_cond_lhs (stmt);
1794 op1 = gimple_cond_rhs (stmt);
1795 cmp = gimple_cond_code (stmt);
1796 type = TREE_TYPE (op0);
1797 visited = BITMAP_ALLOC (NULL);
1798 val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1, visited);
1799 BITMAP_FREE (visited);
1800 if (val)
1801 {
1802 if (integer_zerop (val))
1803 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, NOT_TAKEN);
1804 else
1805 predict_edge_def (then_edge, PRED_BUILTIN_EXPECT, TAKEN);
1806 return;
1807 }
1808 /* Try "pointer heuristic."
1809 A comparison ptr == 0 is predicted as false.
1810 Similarly, a comparison ptr1 == ptr2 is predicted as false. */
1811 if (POINTER_TYPE_P (type))
1812 {
1813 if (cmp == EQ_EXPR)
1814 predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
1815 else if (cmp == NE_EXPR)
1816 predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
1817 }
1818 else
1819
1820 /* Try "opcode heuristic."
1821 EQ tests are usually false and NE tests are usually true. Also,
1822 most quantities are positive, so we can make the appropriate guesses
1823 about signed comparisons against zero. */
1824 switch (cmp)
1825 {
1826 case EQ_EXPR:
1827 case UNEQ_EXPR:
1828 /* Floating point comparisons appears to behave in a very
1829 unpredictable way because of special role of = tests in
1830 FP code. */
1831 if (FLOAT_TYPE_P (type))
1832 ;
1833 /* Comparisons with 0 are often used for booleans and there is
1834 nothing useful to predict about them. */
1835 else if (integer_zerop (op0) || integer_zerop (op1))
1836 ;
1837 else
1838 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
1839 break;
1840
1841 case NE_EXPR:
1842 case LTGT_EXPR:
1843 /* Floating point comparisons appears to behave in a very
1844 unpredictable way because of special role of = tests in
1845 FP code. */
1846 if (FLOAT_TYPE_P (type))
1847 ;
1848 /* Comparisons with 0 are often used for booleans and there is
1849 nothing useful to predict about them. */
1850 else if (integer_zerop (op0)
1851 || integer_zerop (op1))
1852 ;
1853 else
1854 predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
1855 break;
1856
1857 case ORDERED_EXPR:
1858 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
1859 break;
1860
1861 case UNORDERED_EXPR:
1862 predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
1863 break;
1864
1865 case LE_EXPR:
1866 case LT_EXPR:
1867 if (integer_zerop (op1)
1868 || integer_onep (op1)
1869 || integer_all_onesp (op1)
1870 || real_zerop (op1)
1871 || real_onep (op1)
1872 || real_minus_onep (op1))
1873 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
1874 break;
1875
1876 case GE_EXPR:
1877 case GT_EXPR:
1878 if (integer_zerop (op1)
1879 || integer_onep (op1)
1880 || integer_all_onesp (op1)
1881 || real_zerop (op1)
1882 || real_onep (op1)
1883 || real_minus_onep (op1))
1884 predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
1885 break;
1886
1887 default:
1888 break;
1889 }
1890 }
1891
1892 /* Try to guess whether the value of return means error code. */
1893
1894 static enum br_predictor
1895 return_prediction (tree val, enum prediction *prediction)
1896 {
1897 /* VOID. */
1898 if (!val)
1899 return PRED_NO_PREDICTION;
1900 /* Different heuristics for pointers and scalars. */
1901 if (POINTER_TYPE_P (TREE_TYPE (val)))
1902 {
1903 /* NULL is usually not returned. */
1904 if (integer_zerop (val))
1905 {
1906 *prediction = NOT_TAKEN;
1907 return PRED_NULL_RETURN;
1908 }
1909 }
1910 else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
1911 {
1912 /* Negative return values are often used to indicate
1913 errors. */
1914 if (TREE_CODE (val) == INTEGER_CST
1915 && tree_int_cst_sgn (val) < 0)
1916 {
1917 *prediction = NOT_TAKEN;
1918 return PRED_NEGATIVE_RETURN;
1919 }
1920 /* Constant return values seems to be commonly taken.
1921 Zero/one often represent booleans so exclude them from the
1922 heuristics. */
1923 if (TREE_CONSTANT (val)
1924 && (!integer_zerop (val) && !integer_onep (val)))
1925 {
1926 *prediction = TAKEN;
1927 return PRED_CONST_RETURN;
1928 }
1929 }
1930 return PRED_NO_PREDICTION;
1931 }
1932
1933 /* Find the basic block with return expression and look up for possible
1934 return value trying to apply RETURN_PREDICTION heuristics. */
1935 static void
1936 apply_return_prediction (void)
1937 {
1938 gimple return_stmt = NULL;
1939 tree return_val;
1940 edge e;
1941 gimple phi;
1942 int phi_num_args, i;
1943 enum br_predictor pred;
1944 enum prediction direction;
1945 edge_iterator ei;
1946
1947 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1948 {
1949 return_stmt = last_stmt (e->src);
1950 if (return_stmt
1951 && gimple_code (return_stmt) == GIMPLE_RETURN)
1952 break;
1953 }
1954 if (!e)
1955 return;
1956 return_val = gimple_return_retval (return_stmt);
1957 if (!return_val)
1958 return;
1959 if (TREE_CODE (return_val) != SSA_NAME
1960 || !SSA_NAME_DEF_STMT (return_val)
1961 || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
1962 return;
1963 phi = SSA_NAME_DEF_STMT (return_val);
1964 phi_num_args = gimple_phi_num_args (phi);
1965 pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
1966
1967 /* Avoid the degenerate case where all return values form the function
1968 belongs to same category (ie they are all positive constants)
1969 so we can hardly say something about them. */
1970 for (i = 1; i < phi_num_args; i++)
1971 if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
1972 break;
1973 if (i != phi_num_args)
1974 for (i = 0; i < phi_num_args; i++)
1975 {
1976 pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
1977 if (pred != PRED_NO_PREDICTION)
1978 predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
1979 direction);
1980 }
1981 }
1982
1983 /* Look for basic block that contains unlikely to happen events
1984 (such as noreturn calls) and mark all paths leading to execution
1985 of this basic blocks as unlikely. */
1986
1987 static void
1988 tree_bb_level_predictions (void)
1989 {
1990 basic_block bb;
1991 bool has_return_edges = false;
1992 edge e;
1993 edge_iterator ei;
1994
1995 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
1996 if (!(e->flags & (EDGE_ABNORMAL | EDGE_FAKE | EDGE_EH)))
1997 {
1998 has_return_edges = true;
1999 break;
2000 }
2001
2002 apply_return_prediction ();
2003
2004 FOR_EACH_BB (bb)
2005 {
2006 gimple_stmt_iterator gsi;
2007
2008 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2009 {
2010 gimple stmt = gsi_stmt (gsi);
2011 tree decl;
2012
2013 if (is_gimple_call (stmt))
2014 {
2015 if ((gimple_call_flags (stmt) & ECF_NORETURN)
2016 && has_return_edges)
2017 predict_paths_leading_to (bb, PRED_NORETURN,
2018 NOT_TAKEN);
2019 decl = gimple_call_fndecl (stmt);
2020 if (decl
2021 && lookup_attribute ("cold",
2022 DECL_ATTRIBUTES (decl)))
2023 predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
2024 NOT_TAKEN);
2025 }
2026 else if (gimple_code (stmt) == GIMPLE_PREDICT)
2027 {
2028 predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
2029 gimple_predict_outcome (stmt));
2030 /* Keep GIMPLE_PREDICT around so early inlining will propagate
2031 hints to callers. */
2032 }
2033 }
2034 }
2035 }
2036
2037 #ifdef ENABLE_CHECKING
2038
2039 /* Callback for pointer_map_traverse, asserts that the pointer map is
2040 empty. */
2041
2042 static bool
2043 assert_is_empty (const void *key ATTRIBUTE_UNUSED, void **value,
2044 void *data ATTRIBUTE_UNUSED)
2045 {
2046 gcc_assert (!*value);
2047 return false;
2048 }
2049 #endif
2050
2051 /* Predict branch probabilities and estimate profile for basic block BB. */
2052
2053 static void
2054 tree_estimate_probability_bb (basic_block bb)
2055 {
2056 edge e;
2057 edge_iterator ei;
2058 gimple last;
2059
2060 FOR_EACH_EDGE (e, ei, bb->succs)
2061 {
2062 /* Predict edges to user labels with attributes. */
2063 if (e->dest != EXIT_BLOCK_PTR)
2064 {
2065 gimple_stmt_iterator gi;
2066 for (gi = gsi_start_bb (e->dest); !gsi_end_p (gi); gsi_next (&gi))
2067 {
2068 gimple stmt = gsi_stmt (gi);
2069 tree decl;
2070
2071 if (gimple_code (stmt) != GIMPLE_LABEL)
2072 break;
2073 decl = gimple_label_label (stmt);
2074 if (DECL_ARTIFICIAL (decl))
2075 continue;
2076
2077 /* Finally, we have a user-defined label. */
2078 if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl)))
2079 predict_edge_def (e, PRED_COLD_LABEL, NOT_TAKEN);
2080 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (decl)))
2081 predict_edge_def (e, PRED_HOT_LABEL, TAKEN);
2082 }
2083 }
2084
2085 /* Predict early returns to be probable, as we've already taken
2086 care for error returns and other cases are often used for
2087 fast paths through function.
2088
2089 Since we've already removed the return statements, we are
2090 looking for CFG like:
2091
2092 if (conditional)
2093 {
2094 ..
2095 goto return_block
2096 }
2097 some other blocks
2098 return_block:
2099 return_stmt. */
2100 if (e->dest != bb->next_bb
2101 && e->dest != EXIT_BLOCK_PTR
2102 && single_succ_p (e->dest)
2103 && single_succ_edge (e->dest)->dest == EXIT_BLOCK_PTR
2104 && (last = last_stmt (e->dest)) != NULL
2105 && gimple_code (last) == GIMPLE_RETURN)
2106 {
2107 edge e1;
2108 edge_iterator ei1;
2109
2110 if (single_succ_p (bb))
2111 {
2112 FOR_EACH_EDGE (e1, ei1, bb->preds)
2113 if (!predicted_by_p (e1->src, PRED_NULL_RETURN)
2114 && !predicted_by_p (e1->src, PRED_CONST_RETURN)
2115 && !predicted_by_p (e1->src, PRED_NEGATIVE_RETURN))
2116 predict_edge_def (e1, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2117 }
2118 else
2119 if (!predicted_by_p (e->src, PRED_NULL_RETURN)
2120 && !predicted_by_p (e->src, PRED_CONST_RETURN)
2121 && !predicted_by_p (e->src, PRED_NEGATIVE_RETURN))
2122 predict_edge_def (e, PRED_TREE_EARLY_RETURN, NOT_TAKEN);
2123 }
2124
2125 /* Look for block we are guarding (ie we dominate it,
2126 but it doesn't postdominate us). */
2127 if (e->dest != EXIT_BLOCK_PTR && e->dest != bb
2128 && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
2129 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
2130 {
2131 gimple_stmt_iterator bi;
2132
2133 /* The call heuristic claims that a guarded function call
2134 is improbable. This is because such calls are often used
2135 to signal exceptional situations such as printing error
2136 messages. */
2137 for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
2138 gsi_next (&bi))
2139 {
2140 gimple stmt = gsi_stmt (bi);
2141 if (is_gimple_call (stmt)
2142 /* Constant and pure calls are hardly used to signalize
2143 something exceptional. */
2144 && gimple_has_side_effects (stmt))
2145 {
2146 predict_edge_def (e, PRED_CALL, NOT_TAKEN);
2147 break;
2148 }
2149 }
2150 }
2151 }
2152 tree_predict_by_opcode (bb);
2153 }
2154
2155 /* Predict branch probabilities and estimate profile of the tree CFG.
2156 This function can be called from the loop optimizers to recompute
2157 the profile information. */
2158
2159 void
2160 tree_estimate_probability (void)
2161 {
2162 basic_block bb;
2163
2164 add_noreturn_fake_exit_edges ();
2165 connect_infinite_loops_to_exit ();
2166 /* We use loop_niter_by_eval, which requires that the loops have
2167 preheaders. */
2168 create_preheaders (CP_SIMPLE_PREHEADERS);
2169 calculate_dominance_info (CDI_POST_DOMINATORS);
2170
2171 bb_predictions = pointer_map_create ();
2172 tree_bb_level_predictions ();
2173 record_loop_exits ();
2174
2175 if (number_of_loops () > 1)
2176 predict_loops ();
2177
2178 FOR_EACH_BB (bb)
2179 tree_estimate_probability_bb (bb);
2180
2181 FOR_EACH_BB (bb)
2182 combine_predictions_for_bb (bb);
2183
2184 #ifdef ENABLE_CHECKING
2185 pointer_map_traverse (bb_predictions, assert_is_empty, NULL);
2186 #endif
2187 pointer_map_destroy (bb_predictions);
2188 bb_predictions = NULL;
2189
2190 estimate_bb_frequencies ();
2191 free_dominance_info (CDI_POST_DOMINATORS);
2192 remove_fake_exit_edges ();
2193 }
2194
2195 /* Predict branch probabilities and estimate profile of the tree CFG.
2196 This is the driver function for PASS_PROFILE. */
2197
2198 static unsigned int
2199 tree_estimate_probability_driver (void)
2200 {
2201 unsigned nb_loops;
2202
2203 loop_optimizer_init (LOOPS_NORMAL);
2204 if (dump_file && (dump_flags & TDF_DETAILS))
2205 flow_loops_dump (dump_file, NULL, 0);
2206
2207 mark_irreducible_loops ();
2208
2209 nb_loops = number_of_loops ();
2210 if (nb_loops > 1)
2211 scev_initialize ();
2212
2213 tree_estimate_probability ();
2214
2215 if (nb_loops > 1)
2216 scev_finalize ();
2217
2218 loop_optimizer_finalize ();
2219 if (dump_file && (dump_flags & TDF_DETAILS))
2220 gimple_dump_cfg (dump_file, dump_flags);
2221 if (profile_status == PROFILE_ABSENT)
2222 profile_status = PROFILE_GUESSED;
2223 return 0;
2224 }
2225 \f
2226 /* Predict edges to successors of CUR whose sources are not postdominated by
2227 BB by PRED and recurse to all postdominators. */
2228
2229 static void
2230 predict_paths_for_bb (basic_block cur, basic_block bb,
2231 enum br_predictor pred,
2232 enum prediction taken,
2233 bitmap visited)
2234 {
2235 edge e;
2236 edge_iterator ei;
2237 basic_block son;
2238
2239 /* We are looking for all edges forming edge cut induced by
2240 set of all blocks postdominated by BB. */
2241 FOR_EACH_EDGE (e, ei, cur->preds)
2242 if (e->src->index >= NUM_FIXED_BLOCKS
2243 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
2244 {
2245 edge e2;
2246 edge_iterator ei2;
2247 bool found = false;
2248
2249 /* Ignore fake edges and eh, we predict them as not taken anyway. */
2250 if (e->flags & (EDGE_EH | EDGE_FAKE))
2251 continue;
2252 gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
2253
2254 /* See if there is an edge from e->src that is not abnormal
2255 and does not lead to BB. */
2256 FOR_EACH_EDGE (e2, ei2, e->src->succs)
2257 if (e2 != e
2258 && !(e2->flags & (EDGE_EH | EDGE_FAKE))
2259 && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb))
2260 {
2261 found = true;
2262 break;
2263 }
2264
2265 /* If there is non-abnormal path leaving e->src, predict edge
2266 using predictor. Otherwise we need to look for paths
2267 leading to e->src.
2268
2269 The second may lead to infinite loop in the case we are predicitng
2270 regions that are only reachable by abnormal edges. We simply
2271 prevent visiting given BB twice. */
2272 if (found)
2273 predict_edge_def (e, pred, taken);
2274 else if (bitmap_set_bit (visited, e->src->index))
2275 predict_paths_for_bb (e->src, e->src, pred, taken, visited);
2276 }
2277 for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
2278 son;
2279 son = next_dom_son (CDI_POST_DOMINATORS, son))
2280 predict_paths_for_bb (son, bb, pred, taken, visited);
2281 }
2282
2283 /* Sets branch probabilities according to PREDiction and
2284 FLAGS. */
2285
2286 static void
2287 predict_paths_leading_to (basic_block bb, enum br_predictor pred,
2288 enum prediction taken)
2289 {
2290 bitmap visited = BITMAP_ALLOC (NULL);
2291 predict_paths_for_bb (bb, bb, pred, taken, visited);
2292 BITMAP_FREE (visited);
2293 }
2294
2295 /* Like predict_paths_leading_to but take edge instead of basic block. */
2296
2297 static void
2298 predict_paths_leading_to_edge (edge e, enum br_predictor pred,
2299 enum prediction taken)
2300 {
2301 bool has_nonloop_edge = false;
2302 edge_iterator ei;
2303 edge e2;
2304
2305 basic_block bb = e->src;
2306 FOR_EACH_EDGE (e2, ei, bb->succs)
2307 if (e2->dest != e->src && e2->dest != e->dest
2308 && !(e->flags & (EDGE_EH | EDGE_FAKE))
2309 && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
2310 {
2311 has_nonloop_edge = true;
2312 break;
2313 }
2314 if (!has_nonloop_edge)
2315 {
2316 bitmap visited = BITMAP_ALLOC (NULL);
2317 predict_paths_for_bb (bb, bb, pred, taken, visited);
2318 BITMAP_FREE (visited);
2319 }
2320 else
2321 predict_edge_def (e, pred, taken);
2322 }
2323 \f
2324 /* This is used to carry information about basic blocks. It is
2325 attached to the AUX field of the standard CFG block. */
2326
2327 typedef struct block_info_def
2328 {
2329 /* Estimated frequency of execution of basic_block. */
2330 sreal frequency;
2331
2332 /* To keep queue of basic blocks to process. */
2333 basic_block next;
2334
2335 /* Number of predecessors we need to visit first. */
2336 int npredecessors;
2337 } *block_info;
2338
2339 /* Similar information for edges. */
2340 typedef struct edge_info_def
2341 {
2342 /* In case edge is a loopback edge, the probability edge will be reached
2343 in case header is. Estimated number of iterations of the loop can be
2344 then computed as 1 / (1 - back_edge_prob). */
2345 sreal back_edge_prob;
2346 /* True if the edge is a loopback edge in the natural loop. */
2347 unsigned int back_edge:1;
2348 } *edge_info;
2349
2350 #define BLOCK_INFO(B) ((block_info) (B)->aux)
2351 #define EDGE_INFO(E) ((edge_info) (E)->aux)
2352
2353 /* Helper function for estimate_bb_frequencies.
2354 Propagate the frequencies in blocks marked in
2355 TOVISIT, starting in HEAD. */
2356
2357 static void
2358 propagate_freq (basic_block head, bitmap tovisit)
2359 {
2360 basic_block bb;
2361 basic_block last;
2362 unsigned i;
2363 edge e;
2364 basic_block nextbb;
2365 bitmap_iterator bi;
2366
2367 /* For each basic block we need to visit count number of his predecessors
2368 we need to visit first. */
2369 EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
2370 {
2371 edge_iterator ei;
2372 int count = 0;
2373
2374 bb = BASIC_BLOCK (i);
2375
2376 FOR_EACH_EDGE (e, ei, bb->preds)
2377 {
2378 bool visit = bitmap_bit_p (tovisit, e->src->index);
2379
2380 if (visit && !(e->flags & EDGE_DFS_BACK))
2381 count++;
2382 else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
2383 fprintf (dump_file,
2384 "Irreducible region hit, ignoring edge to %i->%i\n",
2385 e->src->index, bb->index);
2386 }
2387 BLOCK_INFO (bb)->npredecessors = count;
2388 /* When function never returns, we will never process exit block. */
2389 if (!count && bb == EXIT_BLOCK_PTR)
2390 bb->count = bb->frequency = 0;
2391 }
2392
2393 memcpy (&BLOCK_INFO (head)->frequency, &real_one, sizeof (real_one));
2394 last = head;
2395 for (bb = head; bb; bb = nextbb)
2396 {
2397 edge_iterator ei;
2398 sreal cyclic_probability, frequency;
2399
2400 memcpy (&cyclic_probability, &real_zero, sizeof (real_zero));
2401 memcpy (&frequency, &real_zero, sizeof (real_zero));
2402
2403 nextbb = BLOCK_INFO (bb)->next;
2404 BLOCK_INFO (bb)->next = NULL;
2405
2406 /* Compute frequency of basic block. */
2407 if (bb != head)
2408 {
2409 #ifdef ENABLE_CHECKING
2410 FOR_EACH_EDGE (e, ei, bb->preds)
2411 gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
2412 || (e->flags & EDGE_DFS_BACK));
2413 #endif
2414
2415 FOR_EACH_EDGE (e, ei, bb->preds)
2416 if (EDGE_INFO (e)->back_edge)
2417 {
2418 sreal_add (&cyclic_probability, &cyclic_probability,
2419 &EDGE_INFO (e)->back_edge_prob);
2420 }
2421 else if (!(e->flags & EDGE_DFS_BACK))
2422 {
2423 sreal tmp;
2424
2425 /* frequency += (e->probability
2426 * BLOCK_INFO (e->src)->frequency /
2427 REG_BR_PROB_BASE); */
2428
2429 sreal_init (&tmp, e->probability, 0);
2430 sreal_mul (&tmp, &tmp, &BLOCK_INFO (e->src)->frequency);
2431 sreal_mul (&tmp, &tmp, &real_inv_br_prob_base);
2432 sreal_add (&frequency, &frequency, &tmp);
2433 }
2434
2435 if (sreal_compare (&cyclic_probability, &real_zero) == 0)
2436 {
2437 memcpy (&BLOCK_INFO (bb)->frequency, &frequency,
2438 sizeof (frequency));
2439 }
2440 else
2441 {
2442 if (sreal_compare (&cyclic_probability, &real_almost_one) > 0)
2443 {
2444 memcpy (&cyclic_probability, &real_almost_one,
2445 sizeof (real_almost_one));
2446 }
2447
2448 /* BLOCK_INFO (bb)->frequency = frequency
2449 / (1 - cyclic_probability) */
2450
2451 sreal_sub (&cyclic_probability, &real_one, &cyclic_probability);
2452 sreal_div (&BLOCK_INFO (bb)->frequency,
2453 &frequency, &cyclic_probability);
2454 }
2455 }
2456
2457 bitmap_clear_bit (tovisit, bb->index);
2458
2459 e = find_edge (bb, head);
2460 if (e)
2461 {
2462 sreal tmp;
2463
2464 /* EDGE_INFO (e)->back_edge_prob
2465 = ((e->probability * BLOCK_INFO (bb)->frequency)
2466 / REG_BR_PROB_BASE); */
2467
2468 sreal_init (&tmp, e->probability, 0);
2469 sreal_mul (&tmp, &tmp, &BLOCK_INFO (bb)->frequency);
2470 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2471 &tmp, &real_inv_br_prob_base);
2472 }
2473
2474 /* Propagate to successor blocks. */
2475 FOR_EACH_EDGE (e, ei, bb->succs)
2476 if (!(e->flags & EDGE_DFS_BACK)
2477 && BLOCK_INFO (e->dest)->npredecessors)
2478 {
2479 BLOCK_INFO (e->dest)->npredecessors--;
2480 if (!BLOCK_INFO (e->dest)->npredecessors)
2481 {
2482 if (!nextbb)
2483 nextbb = e->dest;
2484 else
2485 BLOCK_INFO (last)->next = e->dest;
2486
2487 last = e->dest;
2488 }
2489 }
2490 }
2491 }
2492
2493 /* Estimate probabilities of loopback edges in loops at same nest level. */
2494
2495 static void
2496 estimate_loops_at_level (struct loop *first_loop)
2497 {
2498 struct loop *loop;
2499
2500 for (loop = first_loop; loop; loop = loop->next)
2501 {
2502 edge e;
2503 basic_block *bbs;
2504 unsigned i;
2505 bitmap tovisit = BITMAP_ALLOC (NULL);
2506
2507 estimate_loops_at_level (loop->inner);
2508
2509 /* Find current loop back edge and mark it. */
2510 e = loop_latch_edge (loop);
2511 EDGE_INFO (e)->back_edge = 1;
2512
2513 bbs = get_loop_body (loop);
2514 for (i = 0; i < loop->num_nodes; i++)
2515 bitmap_set_bit (tovisit, bbs[i]->index);
2516 free (bbs);
2517 propagate_freq (loop->header, tovisit);
2518 BITMAP_FREE (tovisit);
2519 }
2520 }
2521
2522 /* Propagates frequencies through structure of loops. */
2523
2524 static void
2525 estimate_loops (void)
2526 {
2527 bitmap tovisit = BITMAP_ALLOC (NULL);
2528 basic_block bb;
2529
2530 /* Start by estimating the frequencies in the loops. */
2531 if (number_of_loops () > 1)
2532 estimate_loops_at_level (current_loops->tree_root->inner);
2533
2534 /* Now propagate the frequencies through all the blocks. */
2535 FOR_ALL_BB (bb)
2536 {
2537 bitmap_set_bit (tovisit, bb->index);
2538 }
2539 propagate_freq (ENTRY_BLOCK_PTR, tovisit);
2540 BITMAP_FREE (tovisit);
2541 }
2542
2543 /* Convert counts measured by profile driven feedback to frequencies.
2544 Return nonzero iff there was any nonzero execution count. */
2545
2546 int
2547 counts_to_freqs (void)
2548 {
2549 gcov_type count_max, true_count_max = 0;
2550 basic_block bb;
2551
2552 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2553 true_count_max = MAX (bb->count, true_count_max);
2554
2555 count_max = MAX (true_count_max, 1);
2556 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2557 bb->frequency = (bb->count * BB_FREQ_MAX + count_max / 2) / count_max;
2558
2559 return true_count_max;
2560 }
2561
2562 /* Return true if function is likely to be expensive, so there is no point to
2563 optimize performance of prologue, epilogue or do inlining at the expense
2564 of code size growth. THRESHOLD is the limit of number of instructions
2565 function can execute at average to be still considered not expensive. */
2566
2567 bool
2568 expensive_function_p (int threshold)
2569 {
2570 unsigned int sum = 0;
2571 basic_block bb;
2572 unsigned int limit;
2573
2574 /* We can not compute accurately for large thresholds due to scaled
2575 frequencies. */
2576 gcc_assert (threshold <= BB_FREQ_MAX);
2577
2578 /* Frequencies are out of range. This either means that function contains
2579 internal loop executing more than BB_FREQ_MAX times or profile feedback
2580 is available and function has not been executed at all. */
2581 if (ENTRY_BLOCK_PTR->frequency == 0)
2582 return true;
2583
2584 /* Maximally BB_FREQ_MAX^2 so overflow won't happen. */
2585 limit = ENTRY_BLOCK_PTR->frequency * threshold;
2586 FOR_EACH_BB (bb)
2587 {
2588 rtx insn;
2589
2590 for (insn = BB_HEAD (bb); insn != NEXT_INSN (BB_END (bb));
2591 insn = NEXT_INSN (insn))
2592 if (active_insn_p (insn))
2593 {
2594 sum += bb->frequency;
2595 if (sum > limit)
2596 return true;
2597 }
2598 }
2599
2600 return false;
2601 }
2602
2603 /* Estimate basic blocks frequency by given branch probabilities. */
2604
2605 void
2606 estimate_bb_frequencies (void)
2607 {
2608 basic_block bb;
2609 sreal freq_max;
2610
2611 if (profile_status != PROFILE_READ || !counts_to_freqs ())
2612 {
2613 static int real_values_initialized = 0;
2614
2615 if (!real_values_initialized)
2616 {
2617 real_values_initialized = 1;
2618 sreal_init (&real_zero, 0, 0);
2619 sreal_init (&real_one, 1, 0);
2620 sreal_init (&real_br_prob_base, REG_BR_PROB_BASE, 0);
2621 sreal_init (&real_bb_freq_max, BB_FREQ_MAX, 0);
2622 sreal_init (&real_one_half, 1, -1);
2623 sreal_div (&real_inv_br_prob_base, &real_one, &real_br_prob_base);
2624 sreal_sub (&real_almost_one, &real_one, &real_inv_br_prob_base);
2625 }
2626
2627 mark_dfs_back_edges ();
2628
2629 single_succ_edge (ENTRY_BLOCK_PTR)->probability = REG_BR_PROB_BASE;
2630
2631 /* Set up block info for each basic block. */
2632 alloc_aux_for_blocks (sizeof (struct block_info_def));
2633 alloc_aux_for_edges (sizeof (struct edge_info_def));
2634 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2635 {
2636 edge e;
2637 edge_iterator ei;
2638
2639 FOR_EACH_EDGE (e, ei, bb->succs)
2640 {
2641 sreal_init (&EDGE_INFO (e)->back_edge_prob, e->probability, 0);
2642 sreal_mul (&EDGE_INFO (e)->back_edge_prob,
2643 &EDGE_INFO (e)->back_edge_prob,
2644 &real_inv_br_prob_base);
2645 }
2646 }
2647
2648 /* First compute probabilities locally for each loop from innermost
2649 to outermost to examine probabilities for back edges. */
2650 estimate_loops ();
2651
2652 memcpy (&freq_max, &real_zero, sizeof (real_zero));
2653 FOR_EACH_BB (bb)
2654 if (sreal_compare (&freq_max, &BLOCK_INFO (bb)->frequency) < 0)
2655 memcpy (&freq_max, &BLOCK_INFO (bb)->frequency, sizeof (freq_max));
2656
2657 sreal_div (&freq_max, &real_bb_freq_max, &freq_max);
2658 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
2659 {
2660 sreal tmp;
2661
2662 sreal_mul (&tmp, &BLOCK_INFO (bb)->frequency, &freq_max);
2663 sreal_add (&tmp, &tmp, &real_one_half);
2664 bb->frequency = sreal_to_int (&tmp);
2665 }
2666
2667 free_aux_for_blocks ();
2668 free_aux_for_edges ();
2669 }
2670 compute_function_frequency ();
2671 }
2672
2673 /* Decide whether function is hot, cold or unlikely executed. */
2674 void
2675 compute_function_frequency (void)
2676 {
2677 basic_block bb;
2678 struct cgraph_node *node = cgraph_get_node (current_function_decl);
2679 if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2680 || MAIN_NAME_P (DECL_NAME (current_function_decl)))
2681 node->only_called_at_startup = true;
2682 if (DECL_STATIC_DESTRUCTOR (current_function_decl))
2683 node->only_called_at_exit = true;
2684
2685 if (!profile_info || !flag_branch_probabilities)
2686 {
2687 int flags = flags_from_decl_or_type (current_function_decl);
2688 if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
2689 != NULL)
2690 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2691 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
2692 != NULL)
2693 node->frequency = NODE_FREQUENCY_HOT;
2694 else if (flags & ECF_NORETURN)
2695 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2696 else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
2697 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2698 else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
2699 || DECL_STATIC_DESTRUCTOR (current_function_decl))
2700 node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
2701 return;
2702 }
2703 node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
2704 FOR_EACH_BB (bb)
2705 {
2706 if (maybe_hot_bb_p (bb))
2707 {
2708 node->frequency = NODE_FREQUENCY_HOT;
2709 return;
2710 }
2711 if (!probably_never_executed_bb_p (bb))
2712 node->frequency = NODE_FREQUENCY_NORMAL;
2713 }
2714 }
2715
2716 static bool
2717 gate_estimate_probability (void)
2718 {
2719 return flag_guess_branch_prob;
2720 }
2721
2722 /* Build PREDICT_EXPR. */
2723 tree
2724 build_predict_expr (enum br_predictor predictor, enum prediction taken)
2725 {
2726 tree t = build1 (PREDICT_EXPR, void_type_node,
2727 build_int_cst (integer_type_node, predictor));
2728 SET_PREDICT_EXPR_OUTCOME (t, taken);
2729 return t;
2730 }
2731
2732 const char *
2733 predictor_name (enum br_predictor predictor)
2734 {
2735 return predictor_info[predictor].name;
2736 }
2737
2738 struct gimple_opt_pass pass_profile =
2739 {
2740 {
2741 GIMPLE_PASS,
2742 "profile_estimate", /* name */
2743 gate_estimate_probability, /* gate */
2744 tree_estimate_probability_driver, /* execute */
2745 NULL, /* sub */
2746 NULL, /* next */
2747 0, /* static_pass_number */
2748 TV_BRANCH_PROB, /* tv_id */
2749 PROP_cfg, /* properties_required */
2750 0, /* properties_provided */
2751 0, /* properties_destroyed */
2752 0, /* todo_flags_start */
2753 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2754 }
2755 };
2756
2757 struct gimple_opt_pass pass_strip_predict_hints =
2758 {
2759 {
2760 GIMPLE_PASS,
2761 "*strip_predict_hints", /* name */
2762 NULL, /* gate */
2763 strip_predict_hints, /* execute */
2764 NULL, /* sub */
2765 NULL, /* next */
2766 0, /* static_pass_number */
2767 TV_BRANCH_PROB, /* tv_id */
2768 PROP_cfg, /* properties_required */
2769 0, /* properties_provided */
2770 0, /* properties_destroyed */
2771 0, /* todo_flags_start */
2772 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
2773 }
2774 };
2775
2776 /* Rebuild function frequencies. Passes are in general expected to
2777 maintain profile by hand, however in some cases this is not possible:
2778 for example when inlining several functions with loops freuqencies might run
2779 out of scale and thus needs to be recomputed. */
2780
2781 void
2782 rebuild_frequencies (void)
2783 {
2784 timevar_push (TV_REBUILD_FREQUENCIES);
2785 if (profile_status == PROFILE_GUESSED)
2786 {
2787 loop_optimizer_init (0);
2788 add_noreturn_fake_exit_edges ();
2789 mark_irreducible_loops ();
2790 connect_infinite_loops_to_exit ();
2791 estimate_bb_frequencies ();
2792 remove_fake_exit_edges ();
2793 loop_optimizer_finalize ();
2794 }
2795 else if (profile_status == PROFILE_READ)
2796 counts_to_freqs ();
2797 else
2798 gcc_unreachable ();
2799 timevar_pop (TV_REBUILD_FREQUENCIES);
2800 }