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