OSDN Git Service

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