OSDN Git Service

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