Line data Source code
1 : /* Branch prediction routines for the GNU compiler.
2 : Copyright (C) 2000-2026 Free Software Foundation, Inc.
3 :
4 : This file is part of GCC.
5 :
6 : GCC is free software; you can redistribute it and/or modify it under
7 : the terms of the GNU General Public License as published by the Free
8 : Software Foundation; either version 3, or (at your option) any later
9 : version.
10 :
11 : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 : WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 : for more details.
15 :
16 : You should have received a copy of the GNU General Public License
17 : along with GCC; see the file COPYING3. If not see
18 : <http://www.gnu.org/licenses/>. */
19 :
20 : /* References:
21 :
22 : [1] "Branch Prediction for Free"
23 : Ball and Larus; PLDI '93.
24 : [2] "Static Branch Frequency and Program Profile Analysis"
25 : Wu and Larus; MICRO-27.
26 : [3] "Corpus-based Static Branch Prediction"
27 : Calder, Grunwald, Lindsay, Martin, Mozer, and Zorn; PLDI '95. */
28 :
29 : #include "config.h"
30 : #include "system.h"
31 : #include "coretypes.h"
32 : #include "backend.h"
33 : #include "rtl.h"
34 : #include "tree.h"
35 : #include "gimple.h"
36 : #include "cfghooks.h"
37 : #include "tree-pass.h"
38 : #include "ssa.h"
39 : #include "memmodel.h"
40 : #include "emit-rtl.h"
41 : #include "cgraph.h"
42 : #include "coverage.h"
43 : #include "diagnostic-core.h"
44 : #include "gimple-predict.h"
45 : #include "fold-const.h"
46 : #include "calls.h"
47 : #include "cfganal.h"
48 : #include "profile.h"
49 : #include "sreal.h"
50 : #include "cfgloop.h"
51 : #include "gimple-iterator.h"
52 : #include "tree-cfg.h"
53 : #include "tree-ssa-loop-niter.h"
54 : #include "tree-ssa-loop.h"
55 : #include "tree-scalar-evolution.h"
56 : #include "ipa-utils.h"
57 : #include "gimple-pretty-print.h"
58 : #include "selftest.h"
59 : #include "cfgrtl.h"
60 : #include "stringpool.h"
61 : #include "attribs.h"
62 :
63 : /* Enum with reasons why a predictor is ignored. */
64 :
65 : enum predictor_reason
66 : {
67 : REASON_NONE,
68 : REASON_IGNORED,
69 : REASON_SINGLE_EDGE_DUPLICATE,
70 : REASON_EDGE_PAIR_DUPLICATE
71 : };
72 :
73 : /* String messages for the aforementioned enum. */
74 :
75 : static const char *reason_messages[] = {"", " (ignored)",
76 : " (single edge duplicate)", " (edge pair duplicate)"};
77 :
78 :
79 : static void combine_predictions_for_insn (rtx_insn *, basic_block);
80 : static void dump_prediction (FILE *, enum br_predictor, int, basic_block,
81 : enum predictor_reason, edge);
82 : static void predict_paths_leading_to (basic_block, enum br_predictor,
83 : enum prediction,
84 : class loop *in_loop = NULL);
85 : static void predict_paths_leading_to_edge (edge, enum br_predictor,
86 : enum prediction,
87 : class loop *in_loop = NULL);
88 : static bool can_predict_insn_p (const rtx_insn *);
89 : static HOST_WIDE_INT get_predictor_value (br_predictor, HOST_WIDE_INT);
90 : static void determine_unlikely_bbs ();
91 : static void estimate_bb_frequencies ();
92 :
93 : /* Information we hold about each branch predictor.
94 : Filled using information from predict.def. */
95 :
96 : struct predictor_info
97 : {
98 : const char *const name; /* Name used in the debugging dumps. */
99 : const int hitrate; /* Expected hitrate used by
100 : predict_insn_def call. */
101 : const int flags;
102 : };
103 :
104 : /* Use given predictor without Dempster-Shaffer theory if it matches
105 : using first_match heuristics. */
106 : #define PRED_FLAG_FIRST_MATCH 1
107 :
108 : /* Recompute hitrate in percent to our representation. */
109 :
110 : #define HITRATE(VAL) ((int) ((VAL) * REG_BR_PROB_BASE + 50) / 100)
111 :
112 : #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) {NAME, HITRATE, FLAGS},
113 : static const struct predictor_info predictor_info[]= {
114 : #include "predict.def"
115 :
116 : /* Upper bound on predictors. */
117 : {NULL, 0, 0}
118 : };
119 : #undef DEF_PREDICTOR
120 :
121 : static gcov_type min_count = -1;
122 :
123 : /* Determine the threshold for hot BB counts. */
124 :
125 : gcov_type
126 59758 : get_hot_bb_threshold ()
127 : {
128 59758 : if (min_count == -1)
129 : {
130 102 : const int hot_frac = param_hot_bb_count_fraction;
131 204 : const gcov_type min_hot_count
132 : = hot_frac
133 102 : ? profile_info->sum_max / hot_frac
134 : : (gcov_type)profile_count::max_count;
135 102 : set_hot_bb_threshold (min_hot_count);
136 102 : if (dump_file)
137 22 : fprintf (dump_file, "Setting hotness threshold to %" PRId64 ".\n",
138 : min_hot_count);
139 : }
140 59758 : return min_count;
141 : }
142 :
143 : /* Set the threshold for hot BB counts. */
144 :
145 : void
146 542 : set_hot_bb_threshold (gcov_type min)
147 : {
148 542 : min_count = min;
149 542 : }
150 :
151 : /* Return TRUE if COUNT is considered to be hot in function FUN. */
152 :
153 : bool
154 1023142953 : maybe_hot_count_p (struct function *fun, profile_count count)
155 : {
156 1023142953 : if (!count.initialized_p ())
157 : return true;
158 928959636 : if (count.ipa () == profile_count::zero ())
159 4890154 : return false;
160 924069482 : if (!count.ipa_p ())
161 : {
162 923971864 : struct cgraph_node *node = cgraph_node::get (fun->decl);
163 923971864 : if (!profile_info || profile_status_for_fn (fun) != PROFILE_READ)
164 : {
165 923971864 : if (node->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED)
166 : return false;
167 923916404 : if (node->frequency == NODE_FREQUENCY_HOT)
168 : return true;
169 : }
170 923912486 : if (profile_status_for_fn (fun) == PROFILE_ABSENT)
171 : return true;
172 923697059 : if (node->frequency == NODE_FREQUENCY_EXECUTED_ONCE
173 923697059 : && count < (ENTRY_BLOCK_PTR_FOR_FN (fun)->count.apply_scale (2, 3)))
174 22883393 : return false;
175 900813666 : if (count * param_hot_bb_frequency_fraction
176 900813666 : < ENTRY_BLOCK_PTR_FOR_FN (fun)->count)
177 : return false;
178 840408462 : return true;
179 : }
180 : /* Code executed at most once is not hot. */
181 97618 : if (count <= MAX (profile_info ? profile_info->runs : 1, 1))
182 : return false;
183 59510 : return (count >= get_hot_bb_threshold ());
184 : }
185 :
186 : /* Return true if basic block BB of function FUN can be CPU intensive
187 : and should thus be optimized for maximum performance. */
188 :
189 : bool
190 1011491884 : maybe_hot_bb_p (struct function *fun, const_basic_block bb)
191 : {
192 1011491884 : gcc_checking_assert (fun);
193 1011491884 : return maybe_hot_count_p (fun, bb->count);
194 : }
195 :
196 : /* Return true if edge E can be CPU intensive and should thus be optimized
197 : for maximum performance. */
198 :
199 : bool
200 10859931 : maybe_hot_edge_p (edge e)
201 : {
202 10859931 : return maybe_hot_count_p (cfun, e->count ());
203 : }
204 :
205 : /* Return true if COUNT is considered to be never executed in function FUN
206 : or if function FUN is considered so in the static profile. */
207 :
208 : static bool
209 60801606 : probably_never_executed (struct function *fun, profile_count count)
210 : {
211 60801606 : gcc_checking_assert (fun);
212 60801606 : if (count.ipa () == profile_count::zero ())
213 1626322 : return true;
214 : /* Do not trust adjusted counts. This will make us to drop int cold section
215 : code with low execution count as a result of inlining. These low counts
216 : are not safe even with read profile and may lead us to dropping
217 : code which actually gets executed into cold section of binary that is not
218 : desirable. */
219 59175284 : if (count.precise_p () && profile_status_for_fn (fun) == PROFILE_READ)
220 : {
221 3560 : const int unlikely_frac = param_unlikely_bb_count_fraction;
222 3560 : if (count * unlikely_frac >= profile_info->runs)
223 : return false;
224 0 : return true;
225 : }
226 3733 : if ((!profile_info || profile_status_for_fn (fun) != PROFILE_READ)
227 59171830 : && (cgraph_node::get (fun->decl)->frequency
228 59168097 : == NODE_FREQUENCY_UNLIKELY_EXECUTED))
229 22263 : return true;
230 : return false;
231 : }
232 :
233 : /* Return true if basic block BB of function FUN is probably never executed. */
234 :
235 : bool
236 18021731 : probably_never_executed_bb_p (struct function *fun, const_basic_block bb)
237 : {
238 18021731 : return probably_never_executed (fun, bb->count);
239 : }
240 :
241 : /* Return true if edge E is unlikely executed for obvious reasons. */
242 :
243 : static bool
244 129076471 : unlikely_executed_edge_p (edge e)
245 : {
246 131056629 : return (e->src->count == profile_count::zero ()
247 126790291 : || e->probability == profile_probability::never ())
248 121724085 : || (e->flags & EDGE_FAKE)
249 : /* If we read profile and know EH edge is executed, trust it.
250 : Otherwise we consider EH edges never executed. */
251 121145084 : || ((e->flags & EDGE_EH) && !e->probability.reliable_p ());
252 : }
253 :
254 : /* Return true if edge E of function FUN is probably never executed. */
255 :
256 : bool
257 44997898 : probably_never_executed_edge_p (struct function *fun, edge e)
258 : {
259 44997898 : if (unlikely_executed_edge_p (e))
260 : return true;
261 42779875 : return probably_never_executed (fun, e->count ());
262 : }
263 :
264 : /* Return true if function FUN should always be optimized for size. */
265 :
266 : optimize_size_level
267 2687267718 : optimize_function_for_size_p (struct function *fun)
268 : {
269 2687267718 : if (!fun || !fun->decl)
270 107457574 : return optimize_size ? OPTIMIZE_SIZE_MAX : OPTIMIZE_SIZE_NO;
271 2579810144 : cgraph_node *n = cgraph_node::get (fun->decl);
272 2579810144 : if (n)
273 2533061851 : return n->optimize_for_size_p ();
274 : return OPTIMIZE_SIZE_NO;
275 : }
276 :
277 : /* Return true if function FUN should always be optimized for speed. */
278 :
279 : bool
280 243192419 : optimize_function_for_speed_p (struct function *fun)
281 : {
282 243192419 : return !optimize_function_for_size_p (fun);
283 : }
284 :
285 : /* Return the optimization type that should be used for function FUN. */
286 :
287 : optimization_type
288 0 : function_optimization_type (struct function *fun)
289 : {
290 0 : return (optimize_function_for_speed_p (fun)
291 0 : ? OPTIMIZE_FOR_SPEED
292 0 : : OPTIMIZE_FOR_SIZE);
293 : }
294 :
295 : /* Return TRUE if basic block BB should be optimized for size. */
296 :
297 : optimize_size_level
298 995299994 : optimize_bb_for_size_p (const_basic_block bb)
299 : {
300 995299994 : enum optimize_size_level ret = optimize_function_for_size_p (cfun);
301 :
302 1976847337 : if (bb && ret < OPTIMIZE_SIZE_MAX && bb->count == profile_count::zero ())
303 29039164 : ret = OPTIMIZE_SIZE_MAX;
304 995299994 : if (bb && ret < OPTIMIZE_SIZE_BALANCED && !maybe_hot_bb_p (cfun, bb))
305 : ret = OPTIMIZE_SIZE_BALANCED;
306 995299994 : return ret;
307 : }
308 :
309 : /* Return TRUE if basic block BB should be optimized for speed. */
310 :
311 : bool
312 949584653 : optimize_bb_for_speed_p (const_basic_block bb)
313 : {
314 949584653 : return !optimize_bb_for_size_p (bb);
315 : }
316 :
317 : /* Return the optimization type that should be used for basic block BB. */
318 :
319 : optimization_type
320 5629299 : bb_optimization_type (const_basic_block bb)
321 : {
322 5629299 : return (optimize_bb_for_speed_p (bb)
323 5629299 : ? OPTIMIZE_FOR_SPEED
324 5629299 : : OPTIMIZE_FOR_SIZE);
325 : }
326 :
327 : /* Return TRUE if edge E should be optimized for size. */
328 :
329 : optimize_size_level
330 11359880 : optimize_edge_for_size_p (edge e)
331 : {
332 11359880 : enum optimize_size_level ret = optimize_function_for_size_p (cfun);
333 :
334 11359880 : if (ret < OPTIMIZE_SIZE_MAX && unlikely_executed_edge_p (e))
335 : ret = OPTIMIZE_SIZE_MAX;
336 11150556 : if (ret < OPTIMIZE_SIZE_BALANCED && !maybe_hot_edge_p (e))
337 : ret = OPTIMIZE_SIZE_BALANCED;
338 11359880 : return ret;
339 : }
340 :
341 : /* Return TRUE if edge E should be optimized for speed. */
342 :
343 : bool
344 5503630 : optimize_edge_for_speed_p (edge e)
345 : {
346 5503630 : return !optimize_edge_for_size_p (e);
347 : }
348 :
349 : /* Return TRUE if the current function is optimized for size. */
350 :
351 : optimize_size_level
352 237144008 : optimize_insn_for_size_p (void)
353 : {
354 237144008 : enum optimize_size_level ret = optimize_function_for_size_p (cfun);
355 237144008 : if (ret < OPTIMIZE_SIZE_BALANCED && !crtl->maybe_hot_insn_p)
356 237144008 : ret = OPTIMIZE_SIZE_BALANCED;
357 237144008 : return ret;
358 : }
359 :
360 : /* Return TRUE if the current function is optimized for speed. */
361 :
362 : bool
363 92209560 : optimize_insn_for_speed_p (void)
364 : {
365 92209560 : return !optimize_insn_for_size_p ();
366 : }
367 :
368 : /* Return the optimization type that should be used for the current
369 : instruction. */
370 :
371 : optimization_type
372 6770 : insn_optimization_type ()
373 : {
374 6770 : return (optimize_insn_for_speed_p ()
375 6770 : ? OPTIMIZE_FOR_SPEED
376 6770 : : OPTIMIZE_FOR_SIZE);
377 : }
378 :
379 : /* Return TRUE if LOOP should be optimized for size. */
380 :
381 : optimize_size_level
382 824879 : optimize_loop_for_size_p (class loop *loop)
383 : {
384 824879 : return optimize_bb_for_size_p (loop->header);
385 : }
386 :
387 : /* Return TRUE if LOOP should be optimized for speed. */
388 :
389 : bool
390 15954249 : optimize_loop_for_speed_p (class loop *loop)
391 : {
392 15954249 : return optimize_bb_for_speed_p (loop->header);
393 : }
394 :
395 : /* Return TRUE if nest rooted at LOOP should be optimized for speed. */
396 :
397 : bool
398 1380573 : optimize_loop_nest_for_speed_p (class loop *loop)
399 : {
400 1380573 : class loop *l = loop;
401 1380573 : if (optimize_loop_for_speed_p (loop))
402 : return true;
403 37125 : l = loop->inner;
404 49804 : while (l && l != loop)
405 : {
406 14245 : if (optimize_loop_for_speed_p (l))
407 : return true;
408 12679 : if (l->inner)
409 : l = l->inner;
410 8547 : else if (l->next)
411 : l = l->next;
412 : else
413 : {
414 19937 : while (l != loop && !l->next)
415 11842 : l = loop_outer (l);
416 8095 : if (l != loop)
417 50 : l = l->next;
418 : }
419 : }
420 : return false;
421 : }
422 :
423 : /* Return TRUE if nest rooted at LOOP should be optimized for size. */
424 :
425 : optimize_size_level
426 18062 : optimize_loop_nest_for_size_p (class loop *loop)
427 : {
428 18062 : enum optimize_size_level ret = optimize_loop_for_size_p (loop);
429 18062 : class loop *l = loop;
430 :
431 18062 : l = loop->inner;
432 18373 : while (l && l != loop)
433 : {
434 17589 : if (ret == OPTIMIZE_SIZE_NO)
435 : break;
436 311 : ret = MIN (optimize_loop_for_size_p (l), ret);
437 311 : if (l->inner)
438 : l = l->inner;
439 305 : else if (l->next)
440 : l = l->next;
441 : else
442 : {
443 393 : while (l != loop && !l->next)
444 199 : l = loop_outer (l);
445 194 : if (l != loop)
446 1 : l = l->next;
447 : }
448 : }
449 18062 : return ret;
450 : }
451 :
452 : /* Return true if edge E is likely to be well predictable by branch
453 : predictor. */
454 :
455 : bool
456 5939177 : predictable_edge_p (edge e)
457 : {
458 5939177 : if (!e->probability.initialized_p ())
459 : return false;
460 5938259 : if ((e->probability.to_reg_br_prob_base ()
461 5938259 : <= param_predictable_branch_outcome * REG_BR_PROB_BASE / 100)
462 5938259 : || (REG_BR_PROB_BASE - e->probability.to_reg_br_prob_base ()
463 : <= param_predictable_branch_outcome * REG_BR_PROB_BASE / 100))
464 626062 : return true;
465 : return false;
466 : }
467 :
468 :
469 : /* Set RTL expansion for BB profile. */
470 :
471 : void
472 81506761 : rtl_profile_for_bb (basic_block bb)
473 : {
474 81506761 : crtl->maybe_hot_insn_p = maybe_hot_bb_p (cfun, bb);
475 81506761 : }
476 :
477 : /* Set RTL expansion for edge profile. */
478 :
479 : void
480 10998 : rtl_profile_for_edge (edge e)
481 : {
482 10998 : crtl->maybe_hot_insn_p = maybe_hot_edge_p (e);
483 10998 : }
484 :
485 : /* Set RTL expansion to default mode (i.e. when profile info is not known). */
486 : void
487 14759160 : default_rtl_profile (void)
488 : {
489 14759160 : crtl->maybe_hot_insn_p = true;
490 14759160 : }
491 :
492 : /* Return true if the one of outgoing edges is already predicted by
493 : PREDICTOR. */
494 :
495 : bool
496 0 : rtl_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
497 : {
498 0 : rtx note;
499 0 : if (!INSN_P (BB_END (bb)))
500 : return false;
501 0 : for (note = REG_NOTES (BB_END (bb)); note; note = XEXP (note, 1))
502 0 : if (REG_NOTE_KIND (note) == REG_BR_PRED
503 0 : && INTVAL (XEXP (XEXP (note, 0), 0)) == (int)predictor)
504 : return true;
505 : return false;
506 : }
507 :
508 : /* Structure representing predictions in tree level. */
509 :
510 : struct edge_prediction {
511 : struct edge_prediction *ep_next;
512 : edge ep_edge;
513 : enum br_predictor ep_predictor;
514 : int ep_probability;
515 : };
516 :
517 : /* This map contains for a basic block the list of predictions for the
518 : outgoing edges. */
519 :
520 : static hash_map<const_basic_block, edge_prediction *> *bb_predictions;
521 :
522 : /* Global cache for expr_expected_value. */
523 :
524 : struct expected_value
525 : {
526 : tree val;
527 : enum br_predictor predictor;
528 : HOST_WIDE_INT probability;
529 : };
530 : static hash_map<int_hash<unsigned, 0>, expected_value> *ssa_expected_value;
531 :
532 : /* Return true if the one of outgoing edges is already predicted by
533 : PREDICTOR. */
534 :
535 : bool
536 3301800 : gimple_predicted_by_p (const_basic_block bb, enum br_predictor predictor)
537 : {
538 3301800 : struct edge_prediction *i;
539 3301800 : edge_prediction **preds = bb_predictions->get (bb);
540 :
541 3301800 : if (!preds)
542 : return false;
543 :
544 1643901 : for (i = *preds; i; i = i->ep_next)
545 855287 : if (i->ep_predictor == predictor)
546 : return true;
547 : return false;
548 : }
549 :
550 : /* Return true if the one of outgoing edges is already predicted by
551 : PREDICTOR for edge E predicted as TAKEN. */
552 :
553 : bool
554 1140797 : edge_predicted_by_p (edge e, enum br_predictor predictor, bool taken)
555 : {
556 1140797 : struct edge_prediction *i;
557 1140797 : basic_block bb = e->src;
558 1140797 : edge_prediction **preds = bb_predictions->get (bb);
559 1140797 : if (!preds)
560 : return false;
561 :
562 150432 : int probability = predictor_info[(int) predictor].hitrate;
563 :
564 150432 : if (taken != TAKEN)
565 150242 : probability = REG_BR_PROB_BASE - probability;
566 :
567 4883108 : for (i = *preds; i; i = i->ep_next)
568 4737030 : if (i->ep_predictor == predictor
569 4595342 : && i->ep_edge == e
570 4354 : && i->ep_probability == probability)
571 : return true;
572 : return false;
573 : }
574 :
575 : /* Same predicate as above, working on edges. */
576 : bool
577 0 : edge_probability_reliable_p (const_edge e)
578 : {
579 0 : return e->probability.probably_reliable_p ();
580 : }
581 :
582 : /* Same predicate as edge_probability_reliable_p, working on notes. */
583 : bool
584 0 : br_prob_note_reliable_p (const_rtx note)
585 : {
586 0 : gcc_assert (REG_NOTE_KIND (note) == REG_BR_PROB);
587 0 : return profile_probability::from_reg_br_prob_note
588 0 : (XINT (note, 0)).probably_reliable_p ();
589 : }
590 :
591 : static void
592 89577 : predict_insn (rtx_insn *insn, enum br_predictor predictor, int probability)
593 : {
594 89577 : gcc_assert (any_condjump_p (insn));
595 89577 : if (!flag_guess_branch_prob)
596 : return;
597 :
598 179040 : add_reg_note (insn, REG_BR_PRED,
599 89520 : gen_rtx_CONCAT (VOIDmode,
600 : GEN_INT ((int) predictor),
601 : GEN_INT ((int) probability)));
602 : }
603 :
604 : /* Predict insn by given predictor. */
605 :
606 : void
607 89577 : predict_insn_def (rtx_insn *insn, enum br_predictor predictor,
608 : enum prediction taken)
609 : {
610 89577 : int probability = predictor_info[(int) predictor].hitrate;
611 89577 : gcc_assert (probability != PROB_UNINITIALIZED);
612 :
613 89577 : if (taken != TAKEN)
614 7065 : probability = REG_BR_PROB_BASE - probability;
615 :
616 89577 : predict_insn (insn, predictor, probability);
617 89577 : }
618 :
619 : /* Predict edge E with given probability if possible. */
620 :
621 : void
622 0 : rtl_predict_edge (edge e, enum br_predictor predictor, int probability)
623 : {
624 0 : rtx_insn *last_insn;
625 0 : last_insn = BB_END (e->src);
626 :
627 : /* We can store the branch prediction information only about
628 : conditional jumps. */
629 0 : if (!any_condjump_p (last_insn))
630 : return;
631 :
632 : /* We always store probability of branching. */
633 0 : if (e->flags & EDGE_FALLTHRU)
634 0 : probability = REG_BR_PROB_BASE - probability;
635 :
636 0 : predict_insn (last_insn, predictor, probability);
637 : }
638 :
639 : /* Predict edge E with the given PROBABILITY. */
640 : void
641 6455050 : gimple_predict_edge (edge e, enum br_predictor predictor, int probability)
642 : {
643 6455050 : if (e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun)
644 6455050 : && EDGE_COUNT (e->src->succs) > 1
645 6455050 : && flag_guess_branch_prob
646 12910100 : && optimize)
647 : {
648 6455050 : struct edge_prediction *i = XNEW (struct edge_prediction);
649 6455050 : edge_prediction *&preds = bb_predictions->get_or_insert (e->src);
650 :
651 6455050 : i->ep_next = preds;
652 6455050 : preds = i;
653 6455050 : i->ep_probability = probability;
654 6455050 : i->ep_predictor = predictor;
655 6455050 : i->ep_edge = e;
656 : }
657 6455050 : }
658 :
659 : /* Filter edge predictions PREDS by a function FILTER: if FILTER return false
660 : the prediction is removed.
661 : DATA are passed to the filter function. */
662 :
663 : static void
664 2953830 : filter_predictions (edge_prediction **preds,
665 : bool (*filter) (edge_prediction *, void *), void *data)
666 : {
667 2953830 : if (!bb_predictions)
668 : return;
669 :
670 2953830 : if (preds)
671 : {
672 : struct edge_prediction **prediction = preds;
673 : struct edge_prediction *next;
674 :
675 8186591 : while (*prediction)
676 : {
677 5232761 : if ((*filter) (*prediction, data))
678 4686950 : prediction = &((*prediction)->ep_next);
679 : else
680 : {
681 545811 : next = (*prediction)->ep_next;
682 545811 : free (*prediction);
683 545811 : *prediction = next;
684 : }
685 : }
686 : }
687 : }
688 :
689 : /* Filter function predicate that returns true for a edge predicate P
690 : if its edge is equal to DATA. */
691 :
692 : static bool
693 0 : not_equal_edge_p (edge_prediction *p, void *data)
694 : {
695 0 : return p->ep_edge != (edge)data;
696 : }
697 :
698 : /* Remove all predictions on given basic block that are attached
699 : to edge E. */
700 : void
701 88627179 : remove_predictions_associated_with_edge (edge e)
702 : {
703 88627179 : if (!bb_predictions)
704 : return;
705 :
706 0 : edge_prediction **preds = bb_predictions->get (e->src);
707 0 : filter_predictions (preds, not_equal_edge_p, e);
708 : }
709 :
710 : /* Clears the list of predictions stored for BB. */
711 :
712 : static void
713 11906230 : clear_bb_predictions (basic_block bb)
714 : {
715 11906230 : edge_prediction **preds = bb_predictions->get (bb);
716 11906230 : struct edge_prediction *pred, *next;
717 :
718 11906230 : if (!preds)
719 : return;
720 :
721 9649460 : for (pred = *preds; pred; pred = next)
722 : {
723 5909239 : next = pred->ep_next;
724 5909239 : free (pred);
725 : }
726 3740221 : *preds = NULL;
727 : }
728 :
729 : /* Return true when we can store prediction on insn INSN.
730 : At the moment we represent predictions only on conditional
731 : jumps, not at computed jump or other complicated cases. */
732 : static bool
733 1210936 : can_predict_insn_p (const rtx_insn *insn)
734 : {
735 1210936 : return (JUMP_P (insn)
736 377186 : && any_condjump_p (insn)
737 1587410 : && EDGE_COUNT (BLOCK_FOR_INSN (insn)->succs) >= 2);
738 : }
739 :
740 : /* Predict edge E by given predictor if possible. */
741 :
742 : void
743 5279261 : predict_edge_def (edge e, enum br_predictor predictor,
744 : enum prediction taken)
745 : {
746 5279261 : int probability = predictor_info[(int) predictor].hitrate;
747 :
748 5279261 : if (taken != TAKEN)
749 4252104 : probability = REG_BR_PROB_BASE - probability;
750 :
751 5279261 : predict_edge (e, predictor, probability);
752 5279261 : }
753 :
754 : /* Invert all branch predictions or probability notes in the INSN. This needs
755 : to be done each time we invert the condition used by the jump. */
756 :
757 : void
758 13042844 : invert_br_probabilities (rtx_insn *insn)
759 : {
760 13042844 : rtx note;
761 :
762 38576299 : for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
763 25533455 : if (REG_NOTE_KIND (note) == REG_BR_PROB)
764 25933220 : XINT (note, 0) = profile_probability::from_reg_br_prob_note
765 12966610 : (XINT (note, 0)).invert ().to_reg_br_prob_note ();
766 12566845 : else if (REG_NOTE_KIND (note) == REG_BR_PRED)
767 0 : XEXP (XEXP (note, 0), 1)
768 0 : = GEN_INT (REG_BR_PROB_BASE - INTVAL (XEXP (XEXP (note, 0), 1)));
769 13042844 : }
770 :
771 : /* Dump information about the branch prediction to the output file. */
772 :
773 : static void
774 12622051 : dump_prediction (FILE *file, enum br_predictor predictor, int probability,
775 : basic_block bb, enum predictor_reason reason = REASON_NONE,
776 : edge ep_edge = NULL)
777 : {
778 12622051 : edge e = ep_edge;
779 12622051 : edge_iterator ei;
780 :
781 12622051 : if (!file)
782 12620184 : return;
783 :
784 1867 : if (e == NULL)
785 1247 : FOR_EACH_EDGE (e, ei, bb->succs)
786 1247 : if (! (e->flags & EDGE_FALLTHRU))
787 : break;
788 :
789 1867 : char edge_info_str[128];
790 1867 : if (ep_edge)
791 620 : sprintf (edge_info_str, " of edge %d->%d", ep_edge->src->index,
792 620 : ep_edge->dest->index);
793 : else
794 1247 : edge_info_str[0] = '\0';
795 :
796 1867 : fprintf (file, " %s heuristics%s%s: %.2f%%",
797 1867 : predictor_info[predictor].name,
798 1867 : edge_info_str, reason_messages[reason],
799 1867 : probability * 100.0 / REG_BR_PROB_BASE);
800 :
801 1867 : if (bb->count.initialized_p ())
802 : {
803 264 : fprintf (file, " exec ");
804 264 : bb->count.dump (file);
805 264 : if (e && e->count ().initialized_p () && bb->count.to_gcov_type ())
806 : {
807 183 : fprintf (file, " hit ");
808 183 : e->count ().dump (file);
809 366 : fprintf (file, " (%.1f%%)", e->count ().to_gcov_type() * 100.0
810 183 : / bb->count.to_gcov_type ());
811 : }
812 : }
813 :
814 1867 : fprintf (file, "\n");
815 :
816 : /* Print output that be easily read by analyze_brprob.py script. We are
817 : interested only in counts that are read from GCDA files. */
818 1867 : if (dump_file && (dump_flags & TDF_DETAILS)
819 1116 : && bb->count.precise_p ()
820 1890 : && reason == REASON_NONE)
821 : {
822 15 : fprintf (file, ";;heuristics;%s;%" PRId64 ";%" PRId64 ";%.1f;\n",
823 : predictor_info[predictor].name,
824 30 : bb->count.to_gcov_type (), e->count ().to_gcov_type (),
825 : probability * 100.0 / REG_BR_PROB_BASE);
826 : }
827 : }
828 :
829 : /* Return true if STMT is known to be unlikely executed. */
830 :
831 : static bool
832 189350025 : unlikely_executed_stmt_p (gimple *stmt)
833 : {
834 189350025 : if (!is_gimple_call (stmt))
835 : return false;
836 :
837 : /* Those calls are inserted by optimizers when code is known to be
838 : unreachable or undefined. */
839 12790293 : if (gimple_call_builtin_p (stmt, BUILT_IN_UNREACHABLE)
840 12742789 : || gimple_call_builtin_p (stmt, BUILT_IN_UNREACHABLE_TRAP)
841 25533076 : || gimple_call_builtin_p (stmt, BUILT_IN_TRAP))
842 : return true;
843 :
844 : /* Checks below do not need to be fully reliable. Cold attribute may be
845 : misplaced by user and in the presence of comdat we may result in call to
846 : function with 0 profile having non-zero profile.
847 :
848 : We later detect that profile is lost and will drop the profile of the
849 : comdat.
850 :
851 : So if we think profile count is reliable, do not try to apply these
852 : heuristics. */
853 12709463 : if (gimple_bb (stmt)->count.reliable_p ()
854 12709463 : && gimple_bb (stmt)->count.nonzero_p ())
855 : return false;
856 : /* NORETURN attribute alone is not strong enough: exit() may be quite
857 : likely executed once during program run. */
858 12709172 : if (gimple_call_fntype (stmt)
859 12168915 : && lookup_attribute ("cold",
860 12168915 : TYPE_ATTRIBUTES (gimple_call_fntype (stmt)))
861 12709172 : && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl)))
862 : return true;
863 12709172 : tree decl = gimple_call_fndecl (stmt);
864 12709172 : if (!decl)
865 : return false;
866 11924635 : if (lookup_attribute ("cold", DECL_ATTRIBUTES (decl))
867 11924635 : && !lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl)))
868 : return true;
869 :
870 11604850 : cgraph_node *n = cgraph_node::get (decl);
871 11604850 : if (!n)
872 : return false;
873 :
874 11598533 : availability avail;
875 11598533 : n = n->ultimate_alias_target (&avail);
876 11598533 : if (avail < AVAIL_AVAILABLE)
877 : return false;
878 3423663 : if (!n->analyzed
879 3423625 : || n->decl == current_function_decl)
880 : return false;
881 3403535 : return n->frequency == NODE_FREQUENCY_UNLIKELY_EXECUTED;
882 : }
883 :
884 : /* Return true if BB is unlikely executed. */
885 :
886 : static bool
887 33825372 : unlikely_executed_bb_p (basic_block bb)
888 : {
889 33825372 : if (bb->count == profile_count::zero ())
890 0 : return true;
891 33825372 : if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun) || bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
892 : return false;
893 67650744 : for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
894 213188251 : !gsi_end_p (gsi); gsi_next (&gsi))
895 : {
896 189350025 : if (unlikely_executed_stmt_p (gsi_stmt (gsi)))
897 : return true;
898 188935557 : if (stmt_can_terminate_bb_p (gsi_stmt (gsi)))
899 : return false;
900 : }
901 : return false;
902 : }
903 :
904 : /* We cannot predict the probabilities of outgoing edges of bb. Set them
905 : evenly and hope for the best. If UNLIKELY_EDGES is not null, distribute
906 : even probability for all edges not mentioned in the set. These edges
907 : are given PROB_VERY_UNLIKELY probability. Similarly for LIKELY_EDGES,
908 : if we have exactly one likely edge, make the other edges predicted
909 : as not probable. */
910 :
911 : static void
912 8861786 : set_even_probabilities (basic_block bb,
913 : hash_set<edge> *unlikely_edges = NULL,
914 : hash_set<edge_prediction *> *likely_edges = NULL)
915 : {
916 8861786 : unsigned nedges = 0, unlikely_count = 0;
917 8861786 : edge e = NULL;
918 8861786 : edge_iterator ei;
919 8861786 : profile_probability all = profile_probability::always ();
920 :
921 19455493 : FOR_EACH_EDGE (e, ei, bb->succs)
922 10593707 : if (e->probability.initialized_p ())
923 9526688 : all -= e->probability;
924 1067019 : else if (!unlikely_executed_edge_p (e))
925 : {
926 639158 : nedges++;
927 639158 : if (unlikely_edges != NULL && unlikely_edges->contains (e))
928 : {
929 5117 : all -= profile_probability::very_unlikely ();
930 5117 : unlikely_count++;
931 : }
932 : }
933 :
934 : /* Make the distribution even if all edges are unlikely. */
935 8861786 : unsigned likely_count = likely_edges ? likely_edges->elements () : 0;
936 8861786 : if (unlikely_count == nedges)
937 : {
938 8341637 : unlikely_edges = NULL;
939 8341637 : unlikely_count = 0;
940 : }
941 :
942 : /* If we have one likely edge, then use its probability and distribute
943 : remaining probabilities as even. */
944 8861786 : if (likely_count == 1)
945 : {
946 23352 : FOR_EACH_EDGE (e, ei, bb->succs)
947 15572 : if (e->probability.initialized_p ())
948 : ;
949 24 : else if (!unlikely_executed_edge_p (e))
950 : {
951 24 : edge_prediction *prediction = *likely_edges->begin ();
952 24 : int p = prediction->ep_probability;
953 24 : profile_probability prob
954 24 : = profile_probability::from_reg_br_prob_base (p);
955 :
956 24 : if (prediction->ep_edge == e)
957 6 : e->probability = prob;
958 18 : else if (unlikely_edges != NULL && unlikely_edges->contains (e))
959 1 : e->probability = profile_probability::very_unlikely ();
960 : else
961 : {
962 17 : profile_probability remainder = prob.invert ();
963 17 : remainder -= (profile_probability::very_unlikely ()
964 34 : * unlikely_count);
965 17 : int count = nedges - unlikely_count - 1;
966 17 : gcc_assert (count >= 0);
967 :
968 17 : e->probability = remainder / count;
969 : }
970 : }
971 : else
972 0 : e->probability = profile_probability::never ();
973 : }
974 : else
975 : {
976 : /* Make all unlikely edges unlikely and the rest will have even
977 : probability. */
978 8854006 : unsigned scale = nedges - unlikely_count;
979 19432141 : FOR_EACH_EDGE (e, ei, bb->succs)
980 10578135 : if (e->probability.initialized_p ())
981 : ;
982 1066995 : else if (!unlikely_executed_edge_p (e))
983 : {
984 639134 : if (unlikely_edges != NULL && unlikely_edges->contains (e))
985 5116 : e->probability = profile_probability::very_unlikely ();
986 : else
987 634018 : e->probability = (all / scale).guessed ();
988 : }
989 : else
990 427861 : e->probability = profile_probability::never ();
991 : }
992 8861786 : }
993 :
994 : /* Add REG_BR_PROB note to JUMP with PROB. */
995 :
996 : void
997 5385956 : add_reg_br_prob_note (rtx_insn *jump, profile_probability prob)
998 : {
999 5385956 : gcc_checking_assert (JUMP_P (jump) && !find_reg_note (jump, REG_BR_PROB, 0));
1000 5385956 : add_int_reg_note (jump, REG_BR_PROB, prob.to_reg_br_prob_note ());
1001 5385956 : }
1002 :
1003 : /* Combine all REG_BR_PRED notes into single probability and attach REG_BR_PROB
1004 : note if not already present. Remove now useless REG_BR_PRED notes. */
1005 :
1006 : static void
1007 605468 : combine_predictions_for_insn (rtx_insn *insn, basic_block bb)
1008 : {
1009 605468 : rtx prob_note;
1010 605468 : rtx *pnote;
1011 605468 : rtx note;
1012 605468 : int best_probability = PROB_EVEN;
1013 605468 : enum br_predictor best_predictor = END_PREDICTORS;
1014 605468 : int combined_probability = REG_BR_PROB_BASE / 2;
1015 605468 : int d;
1016 605468 : bool first_match = false;
1017 605468 : bool found = false;
1018 :
1019 605468 : if (!can_predict_insn_p (insn))
1020 : {
1021 417231 : set_even_probabilities (bb);
1022 417231 : return;
1023 : }
1024 :
1025 188237 : prob_note = find_reg_note (insn, REG_BR_PROB, 0);
1026 188237 : pnote = ®_NOTES (insn);
1027 188237 : if (dump_file)
1028 36 : fprintf (dump_file, "Predictions for insn %i bb %i\n", INSN_UID (insn),
1029 : bb->index);
1030 :
1031 : /* We implement "first match" heuristics and use probability guessed
1032 : by predictor with smallest index. */
1033 277757 : for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
1034 89520 : if (REG_NOTE_KIND (note) == REG_BR_PRED)
1035 : {
1036 89520 : enum br_predictor predictor = ((enum br_predictor)
1037 89520 : INTVAL (XEXP (XEXP (note, 0), 0)));
1038 89520 : int probability = INTVAL (XEXP (XEXP (note, 0), 1));
1039 :
1040 89520 : found = true;
1041 89520 : if (best_predictor > predictor
1042 89520 : && predictor_info[predictor].flags & PRED_FLAG_FIRST_MATCH)
1043 89520 : best_probability = probability, best_predictor = predictor;
1044 :
1045 89520 : d = (combined_probability * probability
1046 89520 : + (REG_BR_PROB_BASE - combined_probability)
1047 89520 : * (REG_BR_PROB_BASE - probability));
1048 :
1049 : /* Use int64_t math to avoid overflows of 32bit integers. */
1050 89520 : if (d == 0)
1051 : /* If one probability is 0% and one 100%, avoid division by zero. */
1052 : combined_probability = REG_BR_PROB_BASE / 2;
1053 : else
1054 89520 : combined_probability = ((((int64_t) combined_probability)
1055 89520 : * probability
1056 89520 : * REG_BR_PROB_BASE + (d / 2)) / d);
1057 : }
1058 :
1059 : /* Decide which heuristic to use. In case we didn't match anything,
1060 : use no_prediction heuristic, in case we did match, use either
1061 : first match or Dempster-Shaffer theory depending on the flags. */
1062 :
1063 188237 : if (best_predictor != END_PREDICTORS)
1064 284 : first_match = true;
1065 :
1066 188237 : if (!found)
1067 98717 : dump_prediction (dump_file, PRED_NO_PREDICTION,
1068 : combined_probability, bb);
1069 : else
1070 : {
1071 89520 : if (!first_match)
1072 89236 : dump_prediction (dump_file, PRED_DS_THEORY, combined_probability,
1073 : bb, !first_match ? REASON_NONE : REASON_IGNORED);
1074 : else
1075 284 : dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability,
1076 : bb, first_match ? REASON_NONE : REASON_IGNORED);
1077 : }
1078 :
1079 188237 : if (first_match)
1080 284 : combined_probability = best_probability;
1081 188237 : dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb);
1082 :
1083 465994 : while (*pnote)
1084 : {
1085 89520 : if (REG_NOTE_KIND (*pnote) == REG_BR_PRED)
1086 : {
1087 89520 : enum br_predictor predictor = ((enum br_predictor)
1088 89520 : INTVAL (XEXP (XEXP (*pnote, 0), 0)));
1089 89520 : int probability = INTVAL (XEXP (XEXP (*pnote, 0), 1));
1090 :
1091 89520 : dump_prediction (dump_file, predictor, probability, bb,
1092 89520 : (!first_match || best_predictor == predictor)
1093 89520 : ? REASON_NONE : REASON_IGNORED);
1094 89520 : *pnote = XEXP (*pnote, 1);
1095 : }
1096 : else
1097 0 : pnote = &XEXP (*pnote, 1);
1098 : }
1099 :
1100 188237 : if (!prob_note)
1101 : {
1102 188237 : profile_probability p
1103 188237 : = profile_probability::from_reg_br_prob_base (combined_probability);
1104 188237 : add_reg_br_prob_note (insn, p);
1105 :
1106 : /* Save the prediction into CFG in case we are seeing non-degenerated
1107 : conditional jump. */
1108 188237 : if (!single_succ_p (bb))
1109 : {
1110 188237 : BRANCH_EDGE (bb)->probability = p;
1111 188237 : FALLTHRU_EDGE (bb)->probability
1112 376474 : = BRANCH_EDGE (bb)->probability.invert ();
1113 : }
1114 : }
1115 0 : else if (!single_succ_p (bb))
1116 : {
1117 0 : profile_probability prob = profile_probability::from_reg_br_prob_note
1118 0 : (XINT (prob_note, 0));
1119 :
1120 0 : BRANCH_EDGE (bb)->probability = prob;
1121 0 : FALLTHRU_EDGE (bb)->probability = prob.invert ();
1122 : }
1123 : else
1124 0 : single_succ_edge (bb)->probability = profile_probability::always ();
1125 : }
1126 :
1127 : /* Edge prediction hash traits. */
1128 :
1129 : struct predictor_hash: pointer_hash <edge_prediction>
1130 : {
1131 :
1132 : static inline hashval_t hash (const edge_prediction *);
1133 : static inline bool equal (const edge_prediction *, const edge_prediction *);
1134 : };
1135 :
1136 : /* Calculate hash value of an edge prediction P based on predictor and
1137 : normalized probability. */
1138 :
1139 : inline hashval_t
1140 13301068 : predictor_hash::hash (const edge_prediction *p)
1141 : {
1142 13301068 : inchash::hash hstate;
1143 13301068 : hstate.add_int (p->ep_predictor);
1144 :
1145 13301068 : int prob = p->ep_probability;
1146 13301068 : if (prob > REG_BR_PROB_BASE / 2)
1147 1745578 : prob = REG_BR_PROB_BASE - prob;
1148 :
1149 13301068 : hstate.add_int (prob);
1150 :
1151 13301068 : return hstate.end ();
1152 : }
1153 :
1154 : /* Return true whether edge predictions P1 and P2 use the same predictor and
1155 : have equal (or opposed probability). */
1156 :
1157 : inline bool
1158 3064316 : predictor_hash::equal (const edge_prediction *p1, const edge_prediction *p2)
1159 : {
1160 3064316 : return (p1->ep_predictor == p2->ep_predictor
1161 3064316 : && (p1->ep_probability == p2->ep_probability
1162 0 : || p1->ep_probability == REG_BR_PROB_BASE - p2->ep_probability));
1163 : }
1164 :
1165 : struct predictor_hash_traits: predictor_hash,
1166 : typed_noop_remove <edge_prediction *> {};
1167 :
1168 : /* Return true if edge prediction P is not in DATA hash set. */
1169 :
1170 : static bool
1171 5232753 : not_removed_prediction_p (edge_prediction *p, void *data)
1172 : {
1173 5232753 : hash_set<edge_prediction *> *remove = (hash_set<edge_prediction *> *) data;
1174 5232753 : return !remove->contains (p);
1175 : }
1176 :
1177 : /* Prune predictions for a basic block BB. Currently we do following
1178 : clean-up steps:
1179 :
1180 : 1) remove duplicate prediction that is guessed with the same probability
1181 : (different than 1/2) to both edge
1182 : 2) remove duplicates for a prediction that belongs with the same probability
1183 : to a single edge
1184 :
1185 : */
1186 :
1187 : static void
1188 3461619 : prune_predictions_for_bb (basic_block bb)
1189 : {
1190 3461619 : edge_prediction **preds = bb_predictions->get (bb);
1191 :
1192 3461619 : if (preds)
1193 : {
1194 2953826 : hash_table <predictor_hash_traits> s (13);
1195 2953826 : hash_set <edge_prediction *> remove;
1196 :
1197 : /* Step 1: identify predictors that should be removed. */
1198 8186579 : for (edge_prediction *pred = *preds; pred; pred = pred->ep_next)
1199 : {
1200 5232753 : edge_prediction *existing = s.find (pred);
1201 5232753 : if (existing)
1202 : {
1203 275345 : if (pred->ep_edge == existing->ep_edge
1204 0 : && pred->ep_probability == existing->ep_probability)
1205 : {
1206 : /* Remove a duplicate predictor. */
1207 0 : dump_prediction (dump_file, pred->ep_predictor,
1208 : pred->ep_probability, bb,
1209 : REASON_SINGLE_EDGE_DUPLICATE, pred->ep_edge);
1210 :
1211 0 : remove.add (pred);
1212 : }
1213 275345 : else if (pred->ep_edge != existing->ep_edge
1214 275345 : && pred->ep_probability == existing->ep_probability
1215 275345 : && pred->ep_probability != REG_BR_PROB_BASE / 2)
1216 : {
1217 : /* Remove both predictors as they predict the same
1218 : for both edges. */
1219 272934 : dump_prediction (dump_file, existing->ep_predictor,
1220 : pred->ep_probability, bb,
1221 : REASON_EDGE_PAIR_DUPLICATE,
1222 : existing->ep_edge);
1223 272934 : dump_prediction (dump_file, pred->ep_predictor,
1224 : pred->ep_probability, bb,
1225 : REASON_EDGE_PAIR_DUPLICATE,
1226 : pred->ep_edge);
1227 :
1228 272934 : remove.add (existing);
1229 272934 : remove.add (pred);
1230 : }
1231 : }
1232 :
1233 5232753 : edge_prediction **slot2 = s.find_slot (pred, INSERT);
1234 5232753 : *slot2 = pred;
1235 : }
1236 :
1237 : /* Step 2: Remove predictors. */
1238 2953826 : filter_predictions (preds, not_removed_prediction_p, &remove);
1239 2953826 : }
1240 3461619 : }
1241 :
1242 : /* Combine predictions into single probability and store them into CFG.
1243 : Remove now useless prediction entries.
1244 : If DRY_RUN is set, only produce dumps and do not modify profile. */
1245 :
1246 : static void
1247 11906230 : combine_predictions_for_bb (basic_block bb, bool dry_run)
1248 : {
1249 11906230 : int best_probability = PROB_EVEN;
1250 11906230 : enum br_predictor best_predictor = END_PREDICTORS;
1251 11906230 : int combined_probability = REG_BR_PROB_BASE / 2;
1252 11906230 : int d;
1253 11906230 : bool first_match = false;
1254 11906230 : bool found = false;
1255 11906230 : struct edge_prediction *pred;
1256 11906230 : int nedges = 0;
1257 11906230 : edge e, first = NULL, second = NULL;
1258 11906230 : edge_iterator ei;
1259 11906230 : int nzero = 0;
1260 11906230 : int nunknown = 0;
1261 :
1262 28588659 : FOR_EACH_EDGE (e, ei, bb->succs)
1263 : {
1264 16682429 : if (!unlikely_executed_edge_p (e))
1265 : {
1266 14196792 : nedges ++;
1267 14196792 : if (first && !second)
1268 : second = e;
1269 10710247 : if (!first)
1270 10605157 : first = e;
1271 : }
1272 2485637 : else if (!e->probability.initialized_p ())
1273 33170 : e->probability = profile_probability::never ();
1274 16682429 : if (!e->probability.initialized_p ())
1275 6303245 : nunknown++;
1276 10379184 : else if (e->probability == profile_probability::never ())
1277 2354736 : nzero++;
1278 : }
1279 :
1280 : /* When there is no successor or only one choice, prediction is easy.
1281 :
1282 : When we have a basic block with more than 2 successors, the situation
1283 : is more complicated as DS theory cannot be used literally.
1284 : More precisely, let's assume we predicted edge e1 with probability p1,
1285 : thus: m1({b1}) = p1. As we're going to combine more than 2 edges, we
1286 : need to find probability of e.g. m1({b2}), which we don't know.
1287 : The only approximation is to equally distribute 1-p1 to all edges
1288 : different from b1.
1289 :
1290 : According to numbers we've got from SPEC2006 benchark, there's only
1291 : one interesting reliable predictor (noreturn call), which can be
1292 : handled with a bit easier approach. */
1293 11906230 : if (nedges != 2)
1294 : {
1295 8444611 : hash_set<edge> unlikely_edges (4);
1296 8444611 : hash_set<edge_prediction *> likely_edges (4);
1297 :
1298 : /* Identify all edges that have a probability close to very unlikely.
1299 : Doing the approach for very unlikely doesn't worth for doing as
1300 : there's no such probability in SPEC2006 benchmark. */
1301 8444611 : edge_prediction **preds = bb_predictions->get (bb);
1302 8444611 : if (preds)
1303 2008692 : for (pred = *preds; pred; pred = pred->ep_next)
1304 : {
1305 1222297 : if (pred->ep_probability <= PROB_VERY_UNLIKELY
1306 1213658 : || pred->ep_predictor == PRED_COLD_LABEL)
1307 8706 : unlikely_edges.add (pred->ep_edge);
1308 1213591 : else if (pred->ep_probability >= PROB_VERY_LIKELY
1309 1212935 : || pred->ep_predictor == PRED_BUILTIN_EXPECT
1310 1205813 : || pred->ep_predictor == PRED_HOT_LABEL)
1311 7781 : likely_edges.add (pred);
1312 : }
1313 :
1314 : /* It can happen that an edge is both in likely_edges and unlikely_edges.
1315 : Clear both sets in that situation. */
1316 8452391 : for (hash_set<edge_prediction *>::iterator it = likely_edges.begin ();
1317 16897002 : it != likely_edges.end (); ++it)
1318 7781 : if (unlikely_edges.contains ((*it)->ep_edge))
1319 : {
1320 1 : likely_edges.empty ();
1321 1 : unlikely_edges.empty ();
1322 : break;
1323 : }
1324 :
1325 8444611 : if (!dry_run)
1326 8444555 : set_even_probabilities (bb, &unlikely_edges, &likely_edges);
1327 8444611 : clear_bb_predictions (bb);
1328 8444611 : if (dump_file)
1329 : {
1330 1234 : fprintf (dump_file, "Predictions for bb %i\n", bb->index);
1331 1234 : if (unlikely_edges.is_empty ())
1332 1232 : fprintf (dump_file,
1333 : "%i edges in bb %i predicted to even probabilities\n",
1334 : nedges, bb->index);
1335 : else
1336 : {
1337 2 : fprintf (dump_file,
1338 : "%i edges in bb %i predicted with some unlikely edges\n",
1339 : nedges, bb->index);
1340 11 : FOR_EACH_EDGE (e, ei, bb->succs)
1341 9 : if (!unlikely_executed_edge_p (e))
1342 9 : dump_prediction (dump_file, PRED_COMBINED,
1343 : e->probability.to_reg_br_prob_base (), bb, REASON_NONE, e);
1344 : }
1345 : }
1346 8444611 : return;
1347 8444611 : }
1348 :
1349 3461619 : if (dump_file)
1350 583 : fprintf (dump_file, "Predictions for bb %i\n", bb->index);
1351 :
1352 3461619 : prune_predictions_for_bb (bb);
1353 :
1354 3461619 : edge_prediction **preds = bb_predictions->get (bb);
1355 :
1356 3461619 : if (preds)
1357 : {
1358 : /* We implement "first match" heuristics and use probability guessed
1359 : by predictor with smallest index. */
1360 7640768 : for (pred = *preds; pred; pred = pred->ep_next)
1361 : {
1362 4686942 : enum br_predictor predictor = pred->ep_predictor;
1363 4686942 : int probability = pred->ep_probability;
1364 :
1365 4686942 : if (pred->ep_edge != first)
1366 1238415 : probability = REG_BR_PROB_BASE - probability;
1367 :
1368 4686942 : found = true;
1369 : /* First match heuristics would be widly confused if we predicted
1370 : both directions. */
1371 4686942 : if (best_predictor > predictor
1372 4480379 : && predictor_info[predictor].flags & PRED_FLAG_FIRST_MATCH)
1373 : {
1374 : struct edge_prediction *pred2;
1375 : int prob = probability;
1376 :
1377 3008313 : for (pred2 = (struct edge_prediction *) *preds;
1378 4448585 : pred2; pred2 = pred2->ep_next)
1379 3008313 : if (pred2 != pred && pred2->ep_predictor == pred->ep_predictor)
1380 : {
1381 0 : int probability2 = pred2->ep_probability;
1382 :
1383 0 : if (pred2->ep_edge != first)
1384 0 : probability2 = REG_BR_PROB_BASE - probability2;
1385 :
1386 0 : if ((probability < REG_BR_PROB_BASE / 2) !=
1387 0 : (probability2 < REG_BR_PROB_BASE / 2))
1388 : break;
1389 :
1390 : /* If the same predictor later gave better result, go for it! */
1391 0 : if ((probability >= REG_BR_PROB_BASE / 2 && (probability2 > probability))
1392 0 : || (probability <= REG_BR_PROB_BASE / 2 && (probability2 < probability)))
1393 3008313 : prob = probability2;
1394 : }
1395 1440272 : if (!pred2)
1396 4686942 : best_probability = prob, best_predictor = predictor;
1397 : }
1398 :
1399 4686942 : d = (combined_probability * probability
1400 4686942 : + (REG_BR_PROB_BASE - combined_probability)
1401 4686942 : * (REG_BR_PROB_BASE - probability));
1402 :
1403 : /* Use int64_t math to avoid overflows of 32bit integers. */
1404 4686942 : if (d == 0)
1405 : /* If one probability is 0% and one 100%, avoid division by zero. */
1406 : combined_probability = REG_BR_PROB_BASE / 2;
1407 : else
1408 4686942 : combined_probability = ((((int64_t) combined_probability)
1409 4686942 : * probability
1410 4686942 : * REG_BR_PROB_BASE + (d / 2)) / d);
1411 : }
1412 : }
1413 :
1414 : /* Decide which heuristic to use. In case we didn't match anything,
1415 : use no_prediction heuristic, in case we did match, use either
1416 : first match or Dempster-Shaffer theory depending on the flags. */
1417 :
1418 2953826 : if (best_predictor != END_PREDICTORS)
1419 1340874 : first_match = true;
1420 :
1421 3461619 : if (!found)
1422 586214 : dump_prediction (dump_file, PRED_NO_PREDICTION, combined_probability, bb);
1423 : else
1424 : {
1425 2875405 : if (!first_match)
1426 1534531 : dump_prediction (dump_file, PRED_DS_THEORY, combined_probability, bb,
1427 : !first_match ? REASON_NONE : REASON_IGNORED);
1428 : else
1429 1340874 : dump_prediction (dump_file, PRED_FIRST_MATCH, best_probability, bb,
1430 : first_match ? REASON_NONE : REASON_IGNORED);
1431 : }
1432 :
1433 3461619 : if (first_match)
1434 1340874 : combined_probability = best_probability;
1435 3461619 : dump_prediction (dump_file, PRED_COMBINED, combined_probability, bb);
1436 :
1437 3461619 : if (preds)
1438 : {
1439 7640768 : for (pred = (struct edge_prediction *) *preds; pred; pred = pred->ep_next)
1440 : {
1441 4686942 : enum br_predictor predictor = pred->ep_predictor;
1442 4686942 : int probability = pred->ep_probability;
1443 :
1444 4686942 : dump_prediction (dump_file, predictor, probability, bb,
1445 4686942 : (!first_match || best_predictor == predictor)
1446 4686942 : ? REASON_NONE : REASON_IGNORED, pred->ep_edge);
1447 : }
1448 : }
1449 3461619 : clear_bb_predictions (bb);
1450 :
1451 :
1452 : /* If we have only one successor which is unknown, we can compute missing
1453 : probability. */
1454 3461619 : if (nunknown == 1)
1455 : {
1456 1259 : profile_probability prob = profile_probability::always ();
1457 1259 : edge missing = NULL;
1458 :
1459 3777 : FOR_EACH_EDGE (e, ei, bb->succs)
1460 2518 : if (e->probability.initialized_p ())
1461 1259 : prob -= e->probability;
1462 1259 : else if (missing == NULL)
1463 : missing = e;
1464 : else
1465 0 : gcc_unreachable ();
1466 1259 : missing->probability = prob;
1467 : }
1468 : /* If nothing is unknown, we have nothing to update. */
1469 3894840 : else if (!nunknown && nzero != (int)EDGE_COUNT (bb->succs))
1470 : ;
1471 3025880 : else if (!dry_run)
1472 : {
1473 3025880 : first->probability
1474 3025880 : = profile_probability::from_reg_br_prob_base (combined_probability);
1475 3025880 : second->probability = first->probability.invert ();
1476 : }
1477 : }
1478 :
1479 : /* Check if T1 and T2 satisfy the IV_COMPARE condition.
1480 : Return the SSA_NAME if the condition satisfies, NULL otherwise.
1481 :
1482 : T1 and T2 should be one of the following cases:
1483 : 1. T1 is SSA_NAME, T2 is NULL
1484 : 2. T1 is SSA_NAME, T2 is INTEGER_CST between [-4, 4]
1485 : 3. T2 is SSA_NAME, T1 is INTEGER_CST between [-4, 4] */
1486 :
1487 : static tree
1488 10304 : strips_small_constant (tree t1, tree t2)
1489 : {
1490 10304 : tree ret = NULL;
1491 10304 : int value = 0;
1492 :
1493 10304 : if (!t1)
1494 : return NULL;
1495 10304 : else if (TREE_CODE (t1) == SSA_NAME)
1496 : ret = t1;
1497 1274 : else if (tree_fits_shwi_p (t1))
1498 93 : value = tree_to_shwi (t1);
1499 : else
1500 : return NULL;
1501 :
1502 9123 : if (!t2)
1503 : return ret;
1504 9123 : else if (tree_fits_shwi_p (t2))
1505 8563 : value = tree_to_shwi (t2);
1506 560 : else if (TREE_CODE (t2) == SSA_NAME)
1507 : {
1508 381 : if (ret)
1509 : return NULL;
1510 : else
1511 : ret = t2;
1512 : }
1513 :
1514 8835 : if (value <= 4 && value >= -4)
1515 : return ret;
1516 : else
1517 739 : return NULL;
1518 : }
1519 :
1520 : /* Return the SSA_NAME in T or T's operands.
1521 : Return NULL if SSA_NAME cannot be found. */
1522 :
1523 : static tree
1524 245285 : get_base_value (tree t)
1525 : {
1526 245285 : if (TREE_CODE (t) == SSA_NAME)
1527 : return t;
1528 :
1529 12091 : if (!BINARY_CLASS_P (t))
1530 : return NULL;
1531 :
1532 10304 : switch (TREE_OPERAND_LENGTH (t))
1533 : {
1534 0 : case 1:
1535 0 : return strips_small_constant (TREE_OPERAND (t, 0), NULL);
1536 10304 : case 2:
1537 10304 : return strips_small_constant (TREE_OPERAND (t, 0),
1538 20608 : TREE_OPERAND (t, 1));
1539 : default:
1540 : return NULL;
1541 : }
1542 : }
1543 :
1544 : /* Check the compare STMT in LOOP. If it compares an induction
1545 : variable to a loop invariant, return true, and save
1546 : LOOP_INVARIANT, COMPARE_CODE and LOOP_STEP.
1547 : Otherwise return false and set LOOP_INVAIANT to NULL. */
1548 :
1549 : static bool
1550 897638 : is_comparison_with_loop_invariant_p (gcond *stmt, class loop *loop,
1551 : tree *loop_invariant,
1552 : enum tree_code *compare_code,
1553 : tree *loop_step,
1554 : tree *loop_iv_base)
1555 : {
1556 897638 : tree op0, op1, bound, base;
1557 897638 : affine_iv iv0, iv1;
1558 897638 : enum tree_code code;
1559 897638 : tree step;
1560 :
1561 897638 : code = gimple_cond_code (stmt);
1562 897638 : *loop_invariant = NULL;
1563 :
1564 897638 : switch (code)
1565 : {
1566 896764 : case GT_EXPR:
1567 896764 : case GE_EXPR:
1568 896764 : case NE_EXPR:
1569 896764 : case LT_EXPR:
1570 896764 : case LE_EXPR:
1571 896764 : case EQ_EXPR:
1572 896764 : break;
1573 :
1574 : default:
1575 : return false;
1576 : }
1577 :
1578 896764 : op0 = gimple_cond_lhs (stmt);
1579 896764 : op1 = gimple_cond_rhs (stmt);
1580 :
1581 896764 : if ((TREE_CODE (op0) != SSA_NAME && TREE_CODE (op0) != INTEGER_CST)
1582 896745 : || (TREE_CODE (op1) != SSA_NAME && TREE_CODE (op1) != INTEGER_CST))
1583 : return false;
1584 1765262 : if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, true))
1585 : return false;
1586 1056346 : if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, true))
1587 : return false;
1588 508782 : if (TREE_CODE (iv0.step) != INTEGER_CST
1589 505986 : || TREE_CODE (iv1.step) != INTEGER_CST)
1590 : return false;
1591 577761 : if ((integer_zerop (iv0.step) && integer_zerop (iv1.step))
1592 560322 : || (!integer_zerop (iv0.step) && !integer_zerop (iv1.step)))
1593 : return false;
1594 :
1595 481770 : if (integer_zerop (iv0.step))
1596 : {
1597 60909 : if (code != NE_EXPR && code != EQ_EXPR)
1598 44652 : code = invert_tree_comparison (code, false);
1599 60909 : bound = iv0.base;
1600 60909 : base = iv1.base;
1601 60909 : if (tree_fits_shwi_p (iv1.step))
1602 : step = iv1.step;
1603 : else
1604 : return false;
1605 : }
1606 : else
1607 : {
1608 420861 : bound = iv1.base;
1609 420861 : base = iv0.base;
1610 420861 : if (tree_fits_shwi_p (iv0.step))
1611 : step = iv0.step;
1612 : else
1613 : return false;
1614 : }
1615 :
1616 474819 : if (TREE_CODE (bound) != INTEGER_CST)
1617 166366 : bound = get_base_value (bound);
1618 166366 : if (!bound)
1619 : return false;
1620 473051 : if (TREE_CODE (base) != INTEGER_CST)
1621 78919 : base = get_base_value (base);
1622 78919 : if (!base)
1623 : return false;
1624 :
1625 470824 : *loop_invariant = bound;
1626 470824 : *compare_code = code;
1627 470824 : *loop_step = step;
1628 470824 : *loop_iv_base = base;
1629 470824 : return true;
1630 : }
1631 :
1632 : /* Compare two SSA_NAMEs: returns TRUE if T1 and T2 are value coherent. */
1633 :
1634 : static bool
1635 7295 : expr_coherent_p (tree t1, tree t2)
1636 : {
1637 7295 : gimple *stmt;
1638 7295 : tree ssa_name_1 = NULL;
1639 7295 : tree ssa_name_2 = NULL;
1640 :
1641 7295 : gcc_assert (TREE_CODE (t1) == SSA_NAME || TREE_CODE (t1) == INTEGER_CST);
1642 7295 : gcc_assert (TREE_CODE (t2) == SSA_NAME || TREE_CODE (t2) == INTEGER_CST);
1643 :
1644 7295 : if (t1 == t2)
1645 : return true;
1646 :
1647 3147 : if (TREE_CODE (t1) == INTEGER_CST && TREE_CODE (t2) == INTEGER_CST)
1648 : return true;
1649 1765 : if (TREE_CODE (t1) == INTEGER_CST || TREE_CODE (t2) == INTEGER_CST)
1650 : return false;
1651 :
1652 : /* Check to see if t1 is expressed/defined with t2. */
1653 315 : stmt = SSA_NAME_DEF_STMT (t1);
1654 315 : gcc_assert (stmt != NULL);
1655 315 : if (is_gimple_assign (stmt))
1656 : {
1657 192 : ssa_name_1 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1658 192 : if (ssa_name_1 && ssa_name_1 == t2)
1659 : return true;
1660 : }
1661 :
1662 : /* Check to see if t2 is expressed/defined with t1. */
1663 315 : stmt = SSA_NAME_DEF_STMT (t2);
1664 315 : gcc_assert (stmt != NULL);
1665 315 : if (is_gimple_assign (stmt))
1666 : {
1667 194 : ssa_name_2 = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1668 194 : if (ssa_name_2 && ssa_name_2 == t1)
1669 : return true;
1670 : }
1671 :
1672 : /* Compare if t1 and t2's def_stmts are identical. */
1673 315 : if (ssa_name_2 != NULL && ssa_name_1 == ssa_name_2)
1674 : return true;
1675 : else
1676 : return false;
1677 : }
1678 :
1679 : /* Return true if E is predicted by one of loop heuristics. */
1680 :
1681 : static bool
1682 6299792 : predicted_by_loop_heuristics_p (basic_block bb)
1683 : {
1684 6299792 : struct edge_prediction *i;
1685 6299792 : edge_prediction **preds = bb_predictions->get (bb);
1686 :
1687 6299792 : if (!preds)
1688 : return false;
1689 :
1690 2207089 : for (i = *preds; i; i = i->ep_next)
1691 1881329 : if (i->ep_predictor == PRED_LOOP_ITERATIONS_GUESSED
1692 1881329 : || i->ep_predictor == PRED_LOOP_ITERATIONS_MAX
1693 : || i->ep_predictor == PRED_LOOP_ITERATIONS
1694 : || i->ep_predictor == PRED_LOOP_EXIT
1695 : || i->ep_predictor == PRED_LOOP_EXIT_WITH_RECURSION
1696 : || i->ep_predictor == PRED_LOOP_EXTRA_EXIT)
1697 : return true;
1698 : return false;
1699 : }
1700 :
1701 : /* Predict branch probability of BB when BB contains a branch that compares
1702 : an induction variable in LOOP with LOOP_IV_BASE_VAR to LOOP_BOUND_VAR. The
1703 : loop exit is compared using LOOP_BOUND_CODE, with step of LOOP_BOUND_STEP.
1704 :
1705 : E.g.
1706 : for (int i = 0; i < bound; i++) {
1707 : if (i < bound - 2)
1708 : computation_1();
1709 : else
1710 : computation_2();
1711 : }
1712 :
1713 : In this loop, we will predict the branch inside the loop to be taken. */
1714 :
1715 : static void
1716 2086357 : predict_iv_comparison (class loop *loop, basic_block bb,
1717 : tree loop_bound_var,
1718 : tree loop_iv_base_var,
1719 : enum tree_code loop_bound_code,
1720 : int loop_bound_step)
1721 : {
1722 2086357 : tree compare_var, compare_base;
1723 2086357 : enum tree_code compare_code;
1724 2086357 : tree compare_step_var;
1725 2086357 : edge then_edge;
1726 2086357 : edge_iterator ei;
1727 :
1728 2086357 : if (predicted_by_loop_heuristics_p (bb))
1729 2084758 : return;
1730 :
1731 4421468 : gcond *stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (bb));
1732 263221 : if (!stmt)
1733 : return;
1734 263221 : if (!is_comparison_with_loop_invariant_p (stmt,
1735 : loop, &compare_var,
1736 : &compare_code,
1737 : &compare_step_var,
1738 : &compare_base))
1739 : return;
1740 :
1741 : /* Find the taken edge. */
1742 12013 : FOR_EACH_EDGE (then_edge, ei, bb->succs)
1743 12013 : if (then_edge->flags & EDGE_TRUE_VALUE)
1744 : break;
1745 :
1746 : /* When comparing an IV to a loop invariant, NE is more likely to be
1747 : taken while EQ is more likely to be not-taken. */
1748 11912 : if (compare_code == NE_EXPR)
1749 : {
1750 1892 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1751 1892 : return;
1752 : }
1753 10020 : else if (compare_code == EQ_EXPR)
1754 : {
1755 4999 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1756 4999 : return;
1757 : }
1758 :
1759 5021 : if (!expr_coherent_p (loop_iv_base_var, compare_base))
1760 : return;
1761 :
1762 : /* If loop bound, base and compare bound are all constants, we can
1763 : calculate the probability directly. */
1764 4443 : if (tree_fits_shwi_p (loop_bound_var)
1765 3038 : && tree_fits_shwi_p (compare_var)
1766 2896 : && tree_fits_shwi_p (compare_base))
1767 : {
1768 2844 : int probability;
1769 2844 : wi::overflow_type overflow;
1770 2844 : bool overall_overflow = false;
1771 2844 : widest_int compare_count, tem;
1772 :
1773 : /* (loop_bound - base) / compare_step */
1774 2844 : tem = wi::sub (wi::to_widest (loop_bound_var),
1775 5688 : wi::to_widest (compare_base), SIGNED, &overflow);
1776 2844 : overall_overflow |= overflow;
1777 2844 : widest_int loop_count = wi::div_trunc (tem,
1778 2844 : wi::to_widest (compare_step_var),
1779 2844 : SIGNED, &overflow);
1780 2844 : overall_overflow |= overflow;
1781 :
1782 2844 : if (!wi::neg_p (wi::to_widest (compare_step_var))
1783 2844 : ^ (compare_code == LT_EXPR || compare_code == LE_EXPR))
1784 : {
1785 : /* (loop_bound - compare_bound) / compare_step */
1786 404 : tem = wi::sub (wi::to_widest (loop_bound_var),
1787 808 : wi::to_widest (compare_var), SIGNED, &overflow);
1788 404 : overall_overflow |= overflow;
1789 404 : compare_count = wi::div_trunc (tem, wi::to_widest (compare_step_var),
1790 404 : SIGNED, &overflow);
1791 404 : overall_overflow |= overflow;
1792 : }
1793 : else
1794 : {
1795 : /* (compare_bound - base) / compare_step */
1796 2440 : tem = wi::sub (wi::to_widest (compare_var),
1797 4880 : wi::to_widest (compare_base), SIGNED, &overflow);
1798 2440 : overall_overflow |= overflow;
1799 2440 : compare_count = wi::div_trunc (tem, wi::to_widest (compare_step_var),
1800 2440 : SIGNED, &overflow);
1801 2440 : overall_overflow |= overflow;
1802 : }
1803 2844 : if (compare_code == LE_EXPR || compare_code == GE_EXPR)
1804 2390 : ++compare_count;
1805 2844 : if (loop_bound_code == LE_EXPR || loop_bound_code == GE_EXPR)
1806 191 : ++loop_count;
1807 2844 : if (wi::neg_p (compare_count))
1808 773 : compare_count = 0;
1809 2844 : if (wi::neg_p (loop_count))
1810 805 : loop_count = 0;
1811 2844 : if (loop_count == 0)
1812 : probability = 0;
1813 2020 : else if (wi::cmps (compare_count, loop_count) == 1)
1814 : probability = REG_BR_PROB_BASE;
1815 : else
1816 : {
1817 1972 : tem = compare_count * REG_BR_PROB_BASE;
1818 1972 : tem = wi::udiv_trunc (tem, loop_count);
1819 1972 : probability = tem.to_uhwi ();
1820 : }
1821 :
1822 : /* FIXME: The branch prediction seems broken. It has only 20% hitrate. */
1823 2844 : if (!overall_overflow)
1824 2844 : predict_edge (then_edge, PRED_LOOP_IV_COMPARE, probability);
1825 :
1826 2844 : return;
1827 2844 : }
1828 :
1829 1599 : if (expr_coherent_p (loop_bound_var, compare_var))
1830 : {
1831 924 : if ((loop_bound_code == LT_EXPR || loop_bound_code == LE_EXPR)
1832 813 : && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1833 805 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1834 119 : else if ((loop_bound_code == GT_EXPR || loop_bound_code == GE_EXPR)
1835 101 : && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1836 86 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1837 33 : else if (loop_bound_code == NE_EXPR)
1838 : {
1839 : /* If the loop backedge condition is "(i != bound)", we do
1840 : the comparison based on the step of IV:
1841 : * step < 0 : backedge condition is like (i > bound)
1842 : * step > 0 : backedge condition is like (i < bound) */
1843 8 : gcc_assert (loop_bound_step != 0);
1844 8 : if (loop_bound_step > 0
1845 8 : && (compare_code == LT_EXPR
1846 8 : || compare_code == LE_EXPR))
1847 7 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1848 1 : else if (loop_bound_step < 0
1849 0 : && (compare_code == GT_EXPR
1850 0 : || compare_code == GE_EXPR))
1851 0 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1852 : else
1853 1 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1854 : }
1855 : else
1856 : /* The branch is predicted not-taken if loop_bound_code is
1857 : opposite with compare_code. */
1858 25 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1859 : }
1860 675 : else if (expr_coherent_p (loop_iv_base_var, compare_var))
1861 : {
1862 : /* For cases like:
1863 : for (i = s; i < h; i++)
1864 : if (i > s + 2) ....
1865 : The branch should be predicted taken. */
1866 163 : if (loop_bound_step > 0
1867 153 : && (compare_code == GT_EXPR || compare_code == GE_EXPR))
1868 62 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1869 101 : else if (loop_bound_step < 0
1870 10 : && (compare_code == LT_EXPR || compare_code == LE_EXPR))
1871 10 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, TAKEN);
1872 : else
1873 91 : predict_edge_def (then_edge, PRED_LOOP_IV_COMPARE_GUESS, NOT_TAKEN);
1874 : }
1875 : }
1876 :
1877 : /* Predict for extra loop exits that will lead to EXIT_EDGE. The extra loop
1878 : exits are resulted from short-circuit conditions that will generate an
1879 : if_tmp. E.g.:
1880 :
1881 : if (foo() || global > 10)
1882 : break;
1883 :
1884 : This will be translated into:
1885 :
1886 : BB3:
1887 : loop header...
1888 : BB4:
1889 : if foo() goto BB6 else goto BB5
1890 : BB5:
1891 : if global > 10 goto BB6 else goto BB7
1892 : BB6:
1893 : goto BB7
1894 : BB7:
1895 : iftmp = (PHI 0(BB5), 1(BB6))
1896 : if iftmp == 1 goto BB8 else goto BB3
1897 : BB8:
1898 : outside of the loop...
1899 :
1900 : The edge BB7->BB8 is loop exit because BB8 is outside of the loop.
1901 : From the dataflow, we can infer that BB4->BB6 and BB5->BB6 are also loop
1902 : exits. This function takes BB7->BB8 as input, and finds out the extra loop
1903 : exits to predict them using PRED_LOOP_EXTRA_EXIT. */
1904 :
1905 : static void
1906 871477 : predict_extra_loop_exits (class loop *loop, edge exit_edge)
1907 : {
1908 871477 : unsigned i;
1909 871477 : bool check_value_one;
1910 871477 : gimple *lhs_def_stmt;
1911 871477 : gphi *phi_stmt;
1912 871477 : tree cmp_rhs, cmp_lhs;
1913 :
1914 1742954 : gcond *cmp_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit_edge->src));
1915 857179 : if (!cmp_stmt)
1916 : return;
1917 :
1918 857179 : cmp_rhs = gimple_cond_rhs (cmp_stmt);
1919 857179 : cmp_lhs = gimple_cond_lhs (cmp_stmt);
1920 857179 : if (!TREE_CONSTANT (cmp_rhs)
1921 857179 : || !(integer_zerop (cmp_rhs) || integer_onep (cmp_rhs)))
1922 : return;
1923 227842 : if (TREE_CODE (cmp_lhs) != SSA_NAME)
1924 : return;
1925 :
1926 : /* If check_value_one is true, only the phi_args with value '1' will lead
1927 : to loop exit. Otherwise, only the phi_args with value '0' will lead to
1928 : loop exit. */
1929 227842 : check_value_one = (((integer_onep (cmp_rhs))
1930 227842 : ^ (gimple_cond_code (cmp_stmt) == EQ_EXPR))
1931 227842 : ^ ((exit_edge->flags & EDGE_TRUE_VALUE) != 0));
1932 :
1933 227842 : lhs_def_stmt = SSA_NAME_DEF_STMT (cmp_lhs);
1934 227842 : if (!lhs_def_stmt)
1935 : return;
1936 :
1937 227842 : phi_stmt = dyn_cast <gphi *> (lhs_def_stmt);
1938 : if (!phi_stmt)
1939 : return;
1940 :
1941 222517 : for (i = 0; i < gimple_phi_num_args (phi_stmt); i++)
1942 : {
1943 146953 : edge e1;
1944 146953 : edge_iterator ei;
1945 146953 : tree val = gimple_phi_arg_def (phi_stmt, i);
1946 146953 : edge e = gimple_phi_arg_edge (phi_stmt, i);
1947 :
1948 146953 : if (!TREE_CONSTANT (val) || !(integer_zerop (val) || integer_onep (val)))
1949 130696 : continue;
1950 39251 : if ((check_value_one ^ integer_onep (val)) == 1)
1951 18545 : continue;
1952 20706 : if (EDGE_COUNT (e->src->succs) != 1)
1953 : {
1954 4449 : predict_paths_leading_to_edge (e, PRED_LOOP_EXTRA_EXIT, NOT_TAKEN,
1955 : loop);
1956 4449 : continue;
1957 : }
1958 :
1959 35388 : FOR_EACH_EDGE (e1, ei, e->src->preds)
1960 19131 : predict_paths_leading_to_edge (e1, PRED_LOOP_EXTRA_EXIT, NOT_TAKEN,
1961 : loop);
1962 : }
1963 : }
1964 :
1965 :
1966 : /* Predict edge probabilities by exploiting loop structure. */
1967 :
1968 : static void
1969 287186 : predict_loops (void)
1970 : {
1971 287186 : basic_block bb;
1972 287186 : hash_set <class loop *> with_recursion(10);
1973 :
1974 5712406 : FOR_EACH_BB_FN (bb, cfun)
1975 : {
1976 5425220 : gimple_stmt_iterator gsi;
1977 5425220 : tree decl;
1978 :
1979 37078500 : for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1980 26228060 : if (is_gimple_call (gsi_stmt (gsi))
1981 2304662 : && (decl = gimple_call_fndecl (gsi_stmt (gsi))) != NULL
1982 28340293 : && recursive_call_p (current_function_decl, decl))
1983 : {
1984 6462 : class loop *loop = bb->loop_father;
1985 12817 : while (loop && !with_recursion.add (loop))
1986 6355 : loop = loop_outer (loop);
1987 : }
1988 : }
1989 :
1990 : /* Try to predict out blocks in a loop that are not part of a
1991 : natural loop. */
1992 1536311 : for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
1993 : {
1994 674753 : basic_block bb, *bbs;
1995 674753 : unsigned j, n_exits = 0;
1996 674753 : class tree_niter_desc niter_desc;
1997 674753 : edge ex;
1998 674753 : class nb_iter_bound *nb_iter;
1999 674753 : enum tree_code loop_bound_code = ERROR_MARK;
2000 674753 : tree loop_bound_step = NULL;
2001 674753 : tree loop_bound_var = NULL;
2002 674753 : tree loop_iv_base = NULL;
2003 674753 : gcond *stmt = NULL;
2004 674753 : bool recursion = with_recursion.contains (loop);
2005 :
2006 674753 : auto_vec<edge> exits = get_loop_exit_edges (loop);
2007 2432382 : FOR_EACH_VEC_ELT (exits, j, ex)
2008 1082876 : if (!unlikely_executed_edge_p (ex) && !(ex->flags & EDGE_ABNORMAL_CALL))
2009 920249 : n_exits ++;
2010 674753 : if (!n_exits)
2011 16038 : continue;
2012 :
2013 658715 : if (dump_file && (dump_flags & TDF_DETAILS))
2014 542 : fprintf (dump_file, "Predicting loop %i%s with %i exits.\n",
2015 : loop->num, recursion ? " (with recursion)" : "", n_exits);
2016 331 : if (dump_file && (dump_flags & TDF_DETAILS)
2017 658986 : && max_loop_iterations_int (loop) >= 0)
2018 : {
2019 215 : fprintf (dump_file,
2020 : "Loop %d iterates at most %i times.\n", loop->num,
2021 215 : (int)max_loop_iterations_int (loop));
2022 : }
2023 331 : if (dump_file && (dump_flags & TDF_DETAILS)
2024 658986 : && likely_max_loop_iterations_int (loop) >= 0)
2025 : {
2026 215 : fprintf (dump_file, "Loop %d likely iterates at most %i times.\n",
2027 215 : loop->num, (int)likely_max_loop_iterations_int (loop));
2028 : }
2029 :
2030 1725344 : FOR_EACH_VEC_ELT (exits, j, ex)
2031 : {
2032 1066629 : tree niter = NULL;
2033 1066629 : HOST_WIDE_INT nitercst;
2034 1066629 : int max = param_max_predicted_iterations;
2035 1066629 : int probability;
2036 1066629 : enum br_predictor predictor;
2037 1066629 : widest_int nit;
2038 :
2039 1066629 : if (unlikely_executed_edge_p (ex)
2040 1066629 : || (ex->flags & EDGE_ABNORMAL_CALL))
2041 146380 : continue;
2042 : /* Loop heuristics do not expect exit conditional to be inside
2043 : inner loop. We predict from innermost to outermost loop. */
2044 920249 : if (predicted_by_loop_heuristics_p (ex->src))
2045 : {
2046 48772 : if (dump_file && (dump_flags & TDF_DETAILS))
2047 0 : fprintf (dump_file, "Skipping exit %i->%i because "
2048 : "it is already predicted.\n",
2049 0 : ex->src->index, ex->dest->index);
2050 48772 : continue;
2051 : }
2052 871477 : predict_extra_loop_exits (loop, ex);
2053 :
2054 871477 : if (number_of_iterations_exit (loop, ex, &niter_desc, false, false))
2055 458864 : niter = niter_desc.niter;
2056 458864 : if (!niter || TREE_CODE (niter_desc.niter) != INTEGER_CST)
2057 583922 : niter = loop_niter_by_eval (loop, ex);
2058 336 : if (dump_file && (dump_flags & TDF_DETAILS)
2059 871748 : && TREE_CODE (niter) == INTEGER_CST)
2060 : {
2061 190 : fprintf (dump_file, "Exit %i->%i %d iterates ",
2062 190 : ex->src->index, ex->dest->index,
2063 : loop->num);
2064 190 : print_generic_expr (dump_file, niter, TDF_SLIM);
2065 190 : fprintf (dump_file, " times.\n");
2066 : }
2067 :
2068 871477 : if (TREE_CODE (niter) == INTEGER_CST)
2069 : {
2070 300754 : if (tree_fits_uhwi_p (niter)
2071 300754 : && max
2072 601502 : && compare_tree_int (niter, max - 1) == -1)
2073 214792 : nitercst = tree_to_uhwi (niter) + 1;
2074 : else
2075 85962 : nitercst = max;
2076 : predictor = PRED_LOOP_ITERATIONS;
2077 : }
2078 : /* If we have just one exit and we can derive some information about
2079 : the number of iterations of the loop from the statements inside
2080 : the loop, use it to predict this exit. */
2081 570723 : else if (n_exits == 1
2082 570723 : && estimated_stmt_executions (loop, &nit))
2083 : {
2084 11 : if (wi::gtu_p (nit, max))
2085 1 : nitercst = max;
2086 : else
2087 10 : nitercst = nit.to_shwi ();
2088 : predictor = PRED_LOOP_ITERATIONS_GUESSED;
2089 : }
2090 : /* If we have likely upper bound, trust it for very small iteration
2091 : counts. Such loops would otherwise get mispredicted by standard
2092 : LOOP_EXIT heuristics. */
2093 1135590 : else if (n_exits == 1
2094 266525 : && likely_max_stmt_executions (loop, &nit)
2095 723316 : && wi::ltu_p (nit,
2096 304792 : RDIV (REG_BR_PROB_BASE,
2097 : REG_BR_PROB_BASE
2098 : - predictor_info
2099 : [recursion
2100 : ? PRED_LOOP_EXIT_WITH_RECURSION
2101 : : PRED_LOOP_EXIT].hitrate)))
2102 : {
2103 5834 : nitercst = nit.to_shwi ();
2104 5834 : predictor = PRED_LOOP_ITERATIONS_MAX;
2105 : }
2106 : else
2107 : {
2108 564878 : if (dump_file && (dump_flags & TDF_DETAILS))
2109 79 : fprintf (dump_file, "Nothing known about exit %i->%i.\n",
2110 79 : ex->src->index, ex->dest->index);
2111 564878 : continue;
2112 : }
2113 :
2114 306599 : if (dump_file && (dump_flags & TDF_DETAILS))
2115 192 : fprintf (dump_file, "Recording prediction to %i iterations by %s.\n",
2116 192 : (int)nitercst, predictor_info[predictor].name);
2117 : /* If the prediction for number of iterations is zero, do not
2118 : predict the exit edges. */
2119 306599 : if (nitercst == 0)
2120 6 : continue;
2121 :
2122 306593 : probability = RDIV (REG_BR_PROB_BASE, nitercst);
2123 306593 : predict_edge (ex, predictor, probability);
2124 1066629 : }
2125 :
2126 : /* Find information about loop bound variables. */
2127 929022 : for (nb_iter = loop->bounds; nb_iter;
2128 270307 : nb_iter = nb_iter->next)
2129 407229 : if (nb_iter->stmt
2130 407229 : && gimple_code (nb_iter->stmt) == GIMPLE_COND)
2131 : {
2132 136922 : stmt = as_a <gcond *> (nb_iter->stmt);
2133 136922 : break;
2134 : }
2135 136922 : if (!stmt)
2136 1043586 : stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (loop->header));
2137 : if (stmt)
2138 634417 : is_comparison_with_loop_invariant_p (stmt, loop,
2139 : &loop_bound_var,
2140 : &loop_bound_code,
2141 : &loop_bound_step,
2142 : &loop_iv_base);
2143 :
2144 658715 : bbs = get_loop_body (loop);
2145 :
2146 4619230 : for (j = 0; j < loop->num_nodes; j++)
2147 : {
2148 3301800 : edge e;
2149 3301800 : edge_iterator ei;
2150 :
2151 3301800 : bb = bbs[j];
2152 :
2153 : /* Bypass loop heuristics on continue statement. These
2154 : statements construct loops via "non-loop" constructs
2155 : in the source language and are better to be handled
2156 : separately. */
2157 3301800 : if (predicted_by_p (bb, PRED_CONTINUE))
2158 : {
2159 8614 : if (dump_file && (dump_flags & TDF_DETAILS))
2160 0 : fprintf (dump_file, "BB %i predicted by continue.\n",
2161 : bb->index);
2162 8614 : continue;
2163 : }
2164 :
2165 : /* If we already used more reliable loop exit predictors, do not
2166 : bother with PRED_LOOP_EXIT. */
2167 3293186 : if (!predicted_by_loop_heuristics_p (bb))
2168 : {
2169 : /* For loop with many exits we don't want to predict all exits
2170 : with the pretty large probability, because if all exits are
2171 : considered in row, the loop would be predicted to iterate
2172 : almost never. The code to divide probability by number of
2173 : exits is very rough. It should compute the number of exits
2174 : taken in each patch through function (not the overall number
2175 : of exits that might be a lot higher for loops with wide switch
2176 : statements in them) and compute n-th square root.
2177 :
2178 : We limit the minimal probability by 2% to avoid
2179 : EDGE_PROBABILITY_RELIABLE from trusting the branch prediction
2180 : as this was causing regression in perl benchmark containing such
2181 : a wide loop. */
2182 :
2183 5348848 : int probability = ((REG_BR_PROB_BASE
2184 2674424 : - predictor_info
2185 : [recursion
2186 2674424 : ? PRED_LOOP_EXIT_WITH_RECURSION
2187 2674424 : : PRED_LOOP_EXIT].hitrate)
2188 2674424 : / n_exits);
2189 2674424 : if (probability < HITRATE (2))
2190 : probability = HITRATE (2);
2191 6516733 : FOR_EACH_EDGE (e, ei, bb->succs)
2192 3842309 : if (e->dest->index < NUM_FIXED_BLOCKS
2193 3842309 : || !flow_bb_inside_loop_p (loop, e->dest))
2194 : {
2195 690451 : if (dump_file && (dump_flags & TDF_DETAILS))
2196 89 : fprintf (dump_file,
2197 : "Predicting exit %i->%i with prob %i.\n",
2198 89 : e->src->index, e->dest->index, probability);
2199 1374072 : predict_edge (e,
2200 : recursion ? PRED_LOOP_EXIT_WITH_RECURSION
2201 : : PRED_LOOP_EXIT, probability);
2202 : }
2203 : }
2204 3293186 : if (loop_bound_var)
2205 2086357 : predict_iv_comparison (loop, bb, loop_bound_var, loop_iv_base,
2206 : loop_bound_code,
2207 2086357 : tree_to_shwi (loop_bound_step));
2208 : }
2209 :
2210 : /* In the following code
2211 : for (loop1)
2212 : if (cond)
2213 : for (loop2)
2214 : body;
2215 : guess that cond is unlikely. */
2216 658715 : if (loop_outer (loop)->num)
2217 : {
2218 138933 : basic_block bb = NULL;
2219 138933 : edge preheader_edge = loop_preheader_edge (loop);
2220 :
2221 277866 : if (single_pred_p (preheader_edge->src)
2222 138933 : && single_succ_p (preheader_edge->src))
2223 115211 : preheader_edge = single_pred_edge (preheader_edge->src);
2224 :
2225 : /* Pattern match fortran loop preheader:
2226 : _16 = BUILTIN_EXPECT (_15, 1, PRED_FORTRAN_LOOP_PREHEADER);
2227 : _17 = (logical(kind=4)) _16;
2228 : if (_17 != 0)
2229 : goto <bb 11>;
2230 : else
2231 : goto <bb 13>;
2232 :
2233 : Loop guard branch prediction says nothing about duplicated loop
2234 : headers produced by fortran frontend and in this case we want
2235 : to predict paths leading to this preheader. */
2236 :
2237 138933 : gcond *stmt
2238 277866 : = safe_dyn_cast <gcond *> (*gsi_last_bb (preheader_edge->src));
2239 112476 : if (stmt
2240 112476 : && gimple_cond_code (stmt) == NE_EXPR
2241 36048 : && TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME
2242 36048 : && integer_zerop (gimple_cond_rhs (stmt)))
2243 : {
2244 14699 : gimple *call_stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (stmt));
2245 14699 : gassign *assign = dyn_cast<gassign *> (call_stmt);
2246 6607 : if (assign
2247 6607 : && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (assign))
2248 922 : && TREE_CODE (gimple_assign_rhs1 (assign)) == SSA_NAME)
2249 922 : call_stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (assign));
2250 14699 : if (gimple_call_internal_p (call_stmt, IFN_BUILTIN_EXPECT)
2251 890 : && TREE_CODE (gimple_call_arg (call_stmt, 2)) == INTEGER_CST
2252 890 : && tree_fits_uhwi_p (gimple_call_arg (call_stmt, 2))
2253 15589 : && tree_to_uhwi (gimple_call_arg (call_stmt, 2))
2254 : == PRED_FORTRAN_LOOP_PREHEADER)
2255 24 : bb = preheader_edge->src;
2256 : }
2257 24 : if (!bb)
2258 : {
2259 138909 : if (!dominated_by_p (CDI_DOMINATORS,
2260 138909 : loop_outer (loop)->latch, loop->header))
2261 57329 : predict_paths_leading_to_edge (loop_preheader_edge (loop),
2262 : recursion
2263 : ? PRED_LOOP_GUARD_WITH_RECURSION
2264 : : PRED_LOOP_GUARD,
2265 : NOT_TAKEN,
2266 : loop_outer (loop));
2267 : }
2268 : else
2269 : {
2270 24 : if (!dominated_by_p (CDI_DOMINATORS,
2271 24 : loop_outer (loop)->latch, bb))
2272 0 : predict_paths_leading_to (bb,
2273 : recursion
2274 : ? PRED_LOOP_GUARD_WITH_RECURSION
2275 : : PRED_LOOP_GUARD,
2276 : NOT_TAKEN,
2277 : loop_outer (loop));
2278 : }
2279 : }
2280 :
2281 : /* Free basic blocks from get_loop_body. */
2282 658715 : free (bbs);
2283 961941 : }
2284 287186 : }
2285 :
2286 : /* Attempt to predict probabilities of BB outgoing edges using local
2287 : properties. */
2288 : static void
2289 605468 : bb_estimate_probability_locally (basic_block bb)
2290 : {
2291 605468 : rtx_insn *last_insn = BB_END (bb);
2292 605468 : rtx cond;
2293 :
2294 605468 : if (! can_predict_insn_p (last_insn))
2295 : return;
2296 188237 : cond = get_condition (last_insn, NULL, false, false);
2297 188237 : if (! cond)
2298 : return;
2299 :
2300 : /* Try "pointer heuristic."
2301 : A comparison ptr == 0 is predicted as false.
2302 : Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2303 164573 : if (COMPARISON_P (cond)
2304 164573 : && ((REG_P (XEXP (cond, 0)) && REG_POINTER (XEXP (cond, 0)))
2305 163371 : || (REG_P (XEXP (cond, 1)) && REG_POINTER (XEXP (cond, 1)))))
2306 : {
2307 1203 : if (GET_CODE (cond) == EQ)
2308 39 : predict_insn_def (last_insn, PRED_POINTER, NOT_TAKEN);
2309 1164 : else if (GET_CODE (cond) == NE)
2310 34 : predict_insn_def (last_insn, PRED_POINTER, TAKEN);
2311 : }
2312 : else
2313 :
2314 : /* Try "opcode heuristic."
2315 : EQ tests are usually false and NE tests are usually true. Also,
2316 : most quantities are positive, so we can make the appropriate guesses
2317 : about signed comparisons against zero. */
2318 163370 : switch (GET_CODE (cond))
2319 : {
2320 0 : case CONST_INT:
2321 : /* Unconditional branch. */
2322 0 : predict_insn_def (last_insn, PRED_UNCONDITIONAL,
2323 0 : cond == const0_rtx ? NOT_TAKEN : TAKEN);
2324 0 : break;
2325 :
2326 15433 : case EQ:
2327 15433 : case UNEQ:
2328 : /* Floating point comparisons appears to behave in a very
2329 : unpredictable way because of special role of = tests in
2330 : FP code. */
2331 15433 : if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
2332 : ;
2333 : /* Comparisons with 0 are often used for booleans and there is
2334 : nothing useful to predict about them. */
2335 15433 : else if (XEXP (cond, 1) == const0_rtx
2336 733 : || XEXP (cond, 0) == const0_rtx)
2337 : ;
2338 : else
2339 733 : predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, NOT_TAKEN);
2340 : break;
2341 :
2342 85233 : case NE:
2343 85233 : case LTGT:
2344 : /* Floating point comparisons appears to behave in a very
2345 : unpredictable way because of special role of = tests in
2346 : FP code. */
2347 85233 : if (FLOAT_MODE_P (GET_MODE (XEXP (cond, 0))))
2348 : ;
2349 : /* Comparisons with 0 are often used for booleans and there is
2350 : nothing useful to predict about them. */
2351 85233 : else if (XEXP (cond, 1) == const0_rtx
2352 79863 : || XEXP (cond, 0) == const0_rtx)
2353 : ;
2354 : else
2355 79863 : predict_insn_def (last_insn, PRED_OPCODE_NONEQUAL, TAKEN);
2356 : break;
2357 :
2358 0 : case ORDERED:
2359 0 : predict_insn_def (last_insn, PRED_FPOPCODE, TAKEN);
2360 0 : break;
2361 :
2362 54 : case UNORDERED:
2363 54 : predict_insn_def (last_insn, PRED_FPOPCODE, NOT_TAKEN);
2364 54 : break;
2365 :
2366 6239 : case LE:
2367 6239 : case LT:
2368 6239 : if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
2369 0 : || XEXP (cond, 1) == constm1_rtx)
2370 6239 : predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, NOT_TAKEN);
2371 : break;
2372 :
2373 5685 : case GE:
2374 5685 : case GT:
2375 5685 : if (XEXP (cond, 1) == const0_rtx || XEXP (cond, 1) == const1_rtx
2376 5616 : || XEXP (cond, 1) == constm1_rtx)
2377 2274 : predict_insn_def (last_insn, PRED_OPCODE_POSITIVE, TAKEN);
2378 : break;
2379 :
2380 : default:
2381 : break;
2382 : }
2383 : }
2384 :
2385 : /* Set edge->probability for each successor edge of BB. */
2386 : void
2387 605468 : guess_outgoing_edge_probabilities (basic_block bb)
2388 : {
2389 605468 : bb_estimate_probability_locally (bb);
2390 605468 : combine_predictions_for_insn (BB_END (bb), bb);
2391 605468 : }
2392 :
2393 : static tree expr_expected_value (tree, enum br_predictor *predictor,
2394 : HOST_WIDE_INT *probability);
2395 :
2396 : /* Helper function for expr_expected_value. */
2397 :
2398 : static tree
2399 16782753 : expr_expected_value_1 (tree type, tree op0, enum tree_code code,
2400 : tree op1, enum br_predictor *predictor,
2401 : HOST_WIDE_INT *probability)
2402 : {
2403 16782753 : gimple *def;
2404 :
2405 : /* Reset returned probability value. */
2406 16782753 : *probability = -1;
2407 16782753 : *predictor = PRED_UNCONDITIONAL;
2408 :
2409 16782753 : if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
2410 : {
2411 10696810 : if (TREE_CONSTANT (op0))
2412 : return op0;
2413 :
2414 10694932 : if (code == IMAGPART_EXPR)
2415 : {
2416 66923 : if (TREE_CODE (TREE_OPERAND (op0, 0)) == SSA_NAME)
2417 : {
2418 65064 : def = SSA_NAME_DEF_STMT (TREE_OPERAND (op0, 0));
2419 65064 : if (is_gimple_call (def)
2420 62913 : && gimple_call_internal_p (def)
2421 113407 : && (gimple_call_internal_fn (def)
2422 : == IFN_ATOMIC_COMPARE_EXCHANGE))
2423 : {
2424 : /* Assume that any given atomic operation has low contention,
2425 : and thus the compare-and-swap operation succeeds. */
2426 5965 : *predictor = PRED_COMPARE_AND_SWAP;
2427 5965 : return build_one_cst (TREE_TYPE (op0));
2428 : }
2429 : }
2430 : }
2431 :
2432 10688967 : if (code != SSA_NAME)
2433 : return NULL_TREE;
2434 :
2435 8338992 : def = SSA_NAME_DEF_STMT (op0);
2436 :
2437 : /* If we were already here, break the infinite cycle. */
2438 8338992 : bool existed_p;
2439 8338992 : expected_value *res
2440 8338992 : = &ssa_expected_value->get_or_insert (SSA_NAME_VERSION (op0),
2441 : &existed_p);
2442 8338992 : if (existed_p)
2443 : {
2444 1724920 : *probability = res->probability;
2445 1724920 : *predictor = res->predictor;
2446 1724920 : return res->val;
2447 : }
2448 6614072 : res->val = NULL_TREE;
2449 6614072 : res->predictor = *predictor;
2450 6614072 : res->probability = *probability;
2451 :
2452 6614072 : if (gphi *phi = dyn_cast <gphi *> (def))
2453 : {
2454 : /* All the arguments of the PHI node must have the same constant
2455 : length. */
2456 950482 : int i, n = gimple_phi_num_args (phi);
2457 950482 : tree val = NULL;
2458 950482 : bool has_nonzero_edge = false;
2459 :
2460 : /* If we already proved that given edge is unlikely, we do not need
2461 : to handle merging of the probabilities. */
2462 1906071 : for (i = 0; i < n && !has_nonzero_edge; i++)
2463 : {
2464 955589 : tree arg = PHI_ARG_DEF (phi, i);
2465 955589 : if (arg == PHI_RESULT (phi))
2466 0 : continue;
2467 955589 : profile_count cnt = gimple_phi_arg_edge (phi, i)->count ();
2468 1911178 : if (!cnt.initialized_p () || cnt.nonzero_p ())
2469 : has_nonzero_edge = true;
2470 : }
2471 :
2472 1556369 : for (i = 0; i < n; i++)
2473 : {
2474 1530455 : tree arg = PHI_ARG_DEF (phi, i);
2475 1530455 : enum br_predictor predictor2;
2476 :
2477 : /* Skip self-referring parameters, since they does not change
2478 : expected value. */
2479 1530455 : if (arg == PHI_RESULT (phi))
2480 605880 : continue;
2481 :
2482 : /* Skip edges which we already predicted as executing
2483 : zero times. */
2484 1530455 : if (has_nonzero_edge)
2485 : {
2486 1525787 : profile_count cnt = gimple_phi_arg_edge (phi, i)->count ();
2487 1525787 : if (cnt.initialized_p () && !cnt.nonzero_p ())
2488 215 : continue;
2489 : }
2490 1530240 : HOST_WIDE_INT probability2;
2491 1530240 : tree new_val = expr_expected_value (arg, &predictor2,
2492 : &probability2);
2493 : /* If we know nothing about value, give up. */
2494 1530240 : if (!new_val)
2495 924568 : return NULL;
2496 :
2497 : /* If this is a first edge, trust its prediction. */
2498 675544 : if (!val)
2499 : {
2500 595540 : val = new_val;
2501 595540 : *predictor = predictor2;
2502 595540 : *probability = probability2;
2503 595540 : continue;
2504 : }
2505 : /* If there are two different values, give up. */
2506 80004 : if (!operand_equal_p (val, new_val, false))
2507 : return NULL;
2508 :
2509 10132 : int p1 = get_predictor_value (*predictor, *probability);
2510 10132 : int p2 = get_predictor_value (predictor2, probability2);
2511 : /* If both predictors agree, it does not matter from which
2512 : edge we enter the basic block. */
2513 10132 : if (*predictor == predictor2 && p1 == p2)
2514 10125 : continue;
2515 : /* The general case has no precise solution, since we do not
2516 : know probabilities of incoming edges, yet.
2517 : Still if value is predicted over all incoming edges, we
2518 : can hope it will be indeed the case. Conservatively
2519 : downgrade prediction quality (so first match merging is not
2520 : performed) and take least successful prediction. */
2521 :
2522 7 : *predictor = PRED_COMBINED_VALUE_PREDICTIONS_PHI;
2523 7 : *probability = MIN (p1, p2);
2524 : }
2525 :
2526 25914 : res = ssa_expected_value->get (SSA_NAME_VERSION (op0));
2527 25914 : res->val = val;
2528 25914 : res->predictor = *predictor;
2529 25914 : res->probability = *probability;
2530 25914 : return val;
2531 : }
2532 5663590 : if (auto a_def = dyn_cast<gassign *> (def))
2533 : {
2534 4349868 : if (gimple_assign_lhs (a_def) != op0)
2535 : return NULL;
2536 :
2537 4349868 : tree val
2538 6661004 : = expr_expected_value_1 (TREE_TYPE (gimple_assign_lhs (a_def)),
2539 : gimple_assign_rhs1 (a_def),
2540 : gimple_assign_rhs_code (a_def),
2541 : gimple_assign_rhs2 (a_def),
2542 : predictor, probability);
2543 4349868 : if (val)
2544 : {
2545 49685 : res = ssa_expected_value->get (SSA_NAME_VERSION (op0));
2546 49685 : res->val = val;
2547 49685 : res->predictor = *predictor;
2548 49685 : res->probability = *probability;
2549 : }
2550 : return val;
2551 : }
2552 :
2553 1313722 : if (is_gimple_call (def))
2554 : {
2555 896914 : tree decl = gimple_call_fndecl (def);
2556 896914 : if (!decl)
2557 : {
2558 81269 : if (gimple_call_internal_p (def)
2559 81269 : && gimple_call_internal_fn (def) == IFN_BUILTIN_EXPECT)
2560 : {
2561 34341 : gcc_assert (gimple_call_num_args (def) == 3);
2562 34341 : tree val = gimple_call_arg (def, 0);
2563 34341 : if (TREE_CONSTANT (val))
2564 : return val;
2565 34341 : tree val2 = gimple_call_arg (def, 2);
2566 34341 : gcc_assert (TREE_CODE (val2) == INTEGER_CST
2567 : && tree_fits_uhwi_p (val2)
2568 : && tree_to_uhwi (val2) < END_PREDICTORS);
2569 34341 : *predictor = (enum br_predictor) tree_to_uhwi (val2);
2570 34341 : if (*predictor == PRED_BUILTIN_EXPECT)
2571 8796 : *probability
2572 8796 : = HITRATE (param_builtin_expect_probability);
2573 34341 : val = gimple_call_arg (def, 1);
2574 34341 : res->val = val;
2575 34341 : res->predictor = *predictor;
2576 34341 : res->probability = *probability;
2577 34341 : return val;
2578 : }
2579 : return NULL;
2580 : }
2581 :
2582 815645 : if (DECL_IS_MALLOC (decl) || DECL_IS_OPERATOR_NEW_P (decl))
2583 : {
2584 12038 : if (predictor)
2585 12038 : *predictor = PRED_MALLOC_NONNULL;
2586 : /* FIXME: This is wrong and we need to convert the logic
2587 : to value ranges. This makes predictor to assume that
2588 : malloc always returns (size_t)1 which is not the same
2589 : as returning non-NULL. */
2590 12038 : tree val = fold_convert (type, boolean_true_node);
2591 12038 : res->val = val;
2592 12038 : res->predictor = *predictor;
2593 12038 : res->probability = *probability;
2594 12038 : return val;
2595 : }
2596 :
2597 803607 : if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
2598 432580 : switch (DECL_FUNCTION_CODE (decl))
2599 : {
2600 94485 : case BUILT_IN_EXPECT:
2601 94485 : {
2602 94485 : tree val;
2603 94485 : if (gimple_call_num_args (def) != 2)
2604 : return NULL;
2605 94485 : val = gimple_call_arg (def, 0);
2606 94485 : if (TREE_CONSTANT (val))
2607 : return val;
2608 94485 : *predictor = PRED_BUILTIN_EXPECT;
2609 94485 : *probability
2610 94485 : = HITRATE (param_builtin_expect_probability);
2611 94485 : val = gimple_call_arg (def, 1);
2612 94485 : res->val = val;
2613 94485 : res->predictor = *predictor;
2614 94485 : res->probability = *probability;
2615 94485 : return val;
2616 : }
2617 23 : case BUILT_IN_EXPECT_WITH_PROBABILITY:
2618 23 : {
2619 23 : tree val;
2620 23 : if (gimple_call_num_args (def) != 3)
2621 : return NULL;
2622 23 : val = gimple_call_arg (def, 0);
2623 23 : if (TREE_CONSTANT (val))
2624 : {
2625 0 : res->val = val;
2626 0 : res->predictor = *predictor;
2627 0 : res->probability = *probability;
2628 0 : return val;
2629 : }
2630 : /* Compute final probability as:
2631 : probability * REG_BR_PROB_BASE. */
2632 23 : tree prob = gimple_call_arg (def, 2);
2633 23 : tree t = TREE_TYPE (prob);
2634 23 : tree base = build_int_cst (integer_type_node,
2635 : REG_BR_PROB_BASE);
2636 23 : base = build_real_from_int_cst (t, base);
2637 23 : tree r = fold_build2_initializer_loc (UNKNOWN_LOCATION,
2638 : MULT_EXPR, t, prob, base);
2639 23 : if (TREE_CODE (r) != REAL_CST)
2640 : {
2641 1 : error_at (gimple_location (def),
2642 : "probability %qE must be "
2643 : "constant floating-point expression", prob);
2644 1 : return NULL;
2645 : }
2646 22 : HOST_WIDE_INT probi
2647 22 : = real_to_integer (TREE_REAL_CST_PTR (r));
2648 22 : if (probi >= 0 && probi <= REG_BR_PROB_BASE)
2649 : {
2650 21 : *predictor = PRED_BUILTIN_EXPECT_WITH_PROBABILITY;
2651 21 : *probability = probi;
2652 : }
2653 : else
2654 1 : error_at (gimple_location (def),
2655 : "probability %qE is outside "
2656 : "the range [0.0, 1.0]", prob);
2657 :
2658 22 : val = gimple_call_arg (def, 1);
2659 22 : res->val = val;
2660 22 : res->predictor = *predictor;
2661 22 : res->probability = *probability;
2662 22 : return val;
2663 : }
2664 :
2665 5329 : case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
2666 5329 : case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
2667 5329 : case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
2668 5329 : case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
2669 5329 : case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
2670 5329 : case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
2671 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
2672 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
2673 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
2674 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
2675 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
2676 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
2677 5329 : case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
2678 : /* Assume that any given atomic operation has low contention,
2679 : and thus the compare-and-swap operation succeeds. */
2680 5329 : *predictor = PRED_COMPARE_AND_SWAP;
2681 5329 : res->val = boolean_true_node;
2682 5329 : res->predictor = *predictor;
2683 5329 : res->probability = *probability;
2684 5329 : return boolean_true_node;
2685 1990 : case BUILT_IN_REALLOC:
2686 1990 : case BUILT_IN_GOMP_REALLOC:
2687 1990 : if (predictor)
2688 1990 : *predictor = PRED_MALLOC_NONNULL;
2689 : /* FIXME: This is wrong and we need to convert the logic
2690 : to value ranges. */
2691 1990 : res->val = fold_convert (type, boolean_true_node);
2692 1990 : res->predictor = *predictor;
2693 1990 : res->probability = *probability;
2694 1990 : return res->val;
2695 : default:
2696 : break;
2697 : }
2698 : }
2699 :
2700 : return NULL;
2701 : }
2702 :
2703 6085943 : if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
2704 : {
2705 5650573 : tree res;
2706 5650573 : tree nop0 = op0;
2707 5650573 : tree nop1 = op1;
2708 :
2709 : /* First handle situation where single op is enough to determine final
2710 : value. In this case we can do better job by avoiding the prediction
2711 : merging. */
2712 5650573 : if (TREE_CODE (op0) != INTEGER_CST)
2713 : {
2714 : /* See if expected value of op0 is good enough to determine the result. */
2715 5624292 : nop0 = expr_expected_value (op0, predictor, probability);
2716 5624292 : if (nop0
2717 183747 : && (res = fold_build2 (code, type, nop0, op1)) != NULL
2718 5808039 : && TREE_CODE (res) == INTEGER_CST)
2719 : /* We are now getting conservative probability. Consider for
2720 : example:
2721 : op0 * op1
2722 : If op0 is 0 with probability p, then we will ignore the
2723 : possibility that op0 != 0 and op1 == 0. It does not seem to be
2724 : worthwhile to downgrade prediction quality for this. */
2725 : return res;
2726 5446361 : if (!nop0)
2727 5466826 : nop0 = op0;
2728 : }
2729 5472642 : enum br_predictor predictor2 = PRED_UNCONDITIONAL;
2730 5472642 : HOST_WIDE_INT probability2 = -1;
2731 5472642 : if (TREE_CODE (op1) != INTEGER_CST)
2732 : {
2733 : /* See if expected value of op1 is good enough to determine the result. */
2734 1673013 : nop1 = expr_expected_value (op1, &predictor2, &probability2);
2735 1673013 : if (nop1
2736 232977 : && (res = fold_build2 (code, type, op0, nop1)) != NULL
2737 1905990 : && TREE_CODE (res) == INTEGER_CST)
2738 : {
2739 : /* Similarly as above we now get conservative probability. */
2740 57 : *predictor = predictor2;
2741 57 : *probability = probability2;
2742 57 : return res;
2743 : }
2744 1672956 : if (!nop1)
2745 5239665 : nop1 = op1;
2746 : }
2747 : /* We already checked if folding one of arguments to constant is good
2748 : enough. Consequently failing to fold both means that we will not
2749 : succeed determining the value. */
2750 5472585 : if (nop0 == op0 || nop1 == op1)
2751 : return NULL;
2752 : /* Finally see if we have two known values. */
2753 236 : res = fold_build2 (code, type, nop0, nop1);
2754 236 : if (TREE_CODE (res) == INTEGER_CST)
2755 : {
2756 161 : HOST_WIDE_INT p1 = get_predictor_value (*predictor, *probability);
2757 161 : HOST_WIDE_INT p2 = get_predictor_value (predictor2, probability2);
2758 :
2759 : /* If one of predictions is sure, such as PRED_UNCONDITIONAL, we
2760 : can ignore it. */
2761 161 : if (p2 == PROB_ALWAYS)
2762 : return res;
2763 141 : if (p1 == PROB_ALWAYS)
2764 : {
2765 1 : *predictor = predictor2;
2766 1 : *probability = probability2;
2767 1 : return res;
2768 : }
2769 : /* Combine binary predictions.
2770 : Since we do not know about independence of predictors, we
2771 : can not determine value precisely. */
2772 140 : *probability = RDIV (p1 * p2, REG_BR_PROB_BASE);
2773 : /* If we no longer track useful information, give up. */
2774 140 : if (!*probability)
2775 : return NULL;
2776 : /* Otherwise mark that prediction is a result of combining
2777 : different heuristics, since we do not want it to participate
2778 : in first match merging. It is no longer reliable since
2779 : we do not know if the probabilities are indpenendet. */
2780 140 : *predictor = PRED_COMBINED_VALUE_PREDICTIONS;
2781 :
2782 140 : return res;
2783 : }
2784 : return NULL;
2785 : }
2786 435370 : if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
2787 : {
2788 434144 : tree res;
2789 434144 : op0 = expr_expected_value (op0, predictor, probability);
2790 434144 : if (!op0)
2791 : return NULL;
2792 39573 : res = fold_build1 (code, type, op0);
2793 39573 : if (TREE_CONSTANT (res))
2794 : return res;
2795 0 : return NULL;
2796 : }
2797 : return NULL;
2798 : }
2799 :
2800 : /* Return constant EXPR will likely have at execution time, NULL if unknown.
2801 : The function is used by builtin_expect branch predictor so the evidence
2802 : must come from this construct and additional possible constant folding.
2803 :
2804 : We may want to implement more involved value guess (such as value range
2805 : propagation based prediction), but such tricks shall go to new
2806 : implementation. */
2807 :
2808 : static tree
2809 9290248 : expr_expected_value (tree expr, enum br_predictor *predictor,
2810 : HOST_WIDE_INT *probability)
2811 : {
2812 9290248 : enum tree_code code;
2813 9290248 : tree op0, op1;
2814 :
2815 9290248 : if (TREE_CONSTANT (expr))
2816 : {
2817 904574 : *predictor = PRED_UNCONDITIONAL;
2818 904574 : *probability = -1;
2819 904574 : return expr;
2820 : }
2821 :
2822 8385674 : extract_ops_from_tree (expr, &code, &op0, &op1);
2823 8385674 : return expr_expected_value_1 (TREE_TYPE (expr),
2824 8385674 : op0, code, op1, predictor, probability);
2825 : }
2826 :
2827 :
2828 : /* Return probability of a PREDICTOR. If the predictor has variable
2829 : probability return passed PROBABILITY. */
2830 :
2831 : static HOST_WIDE_INT
2832 196483 : get_predictor_value (br_predictor predictor, HOST_WIDE_INT probability)
2833 : {
2834 196483 : switch (predictor)
2835 : {
2836 103629 : case PRED_BUILTIN_EXPECT:
2837 103629 : case PRED_BUILTIN_EXPECT_WITH_PROBABILITY:
2838 103629 : case PRED_COMBINED_VALUE_PREDICTIONS_PHI:
2839 103629 : case PRED_COMBINED_VALUE_PREDICTIONS:
2840 103629 : gcc_assert (probability != -1);
2841 : return probability;
2842 92854 : default:
2843 92854 : gcc_assert (probability == -1);
2844 92854 : return predictor_info[(int) predictor].hitrate;
2845 : }
2846 : }
2847 :
2848 : /* Predict using opcode of the last statement in basic block. */
2849 : static void
2850 11906230 : tree_predict_by_opcode (basic_block bb)
2851 : {
2852 11906230 : edge then_edge;
2853 11906230 : tree op0, op1;
2854 11906230 : tree type;
2855 11906230 : tree val;
2856 11906230 : enum tree_code cmp;
2857 11906230 : edge_iterator ei;
2858 11906230 : enum br_predictor predictor;
2859 11906230 : HOST_WIDE_INT probability;
2860 :
2861 11906230 : gimple *stmt = *gsi_last_bb (bb);
2862 11906230 : if (!stmt)
2863 7859019 : return;
2864 :
2865 11423739 : if (gswitch *sw = dyn_cast <gswitch *> (stmt))
2866 : {
2867 28559 : tree index = gimple_switch_index (sw);
2868 28559 : tree val = expr_expected_value (index, &predictor, &probability);
2869 28559 : if (val && TREE_CODE (val) == INTEGER_CST)
2870 : {
2871 4 : edge e = find_taken_edge_switch_expr (sw, val);
2872 4 : if (predictor == PRED_BUILTIN_EXPECT)
2873 : {
2874 4 : int percent = param_builtin_expect_probability;
2875 4 : gcc_assert (percent >= 0 && percent <= 100);
2876 4 : predict_edge (e, PRED_BUILTIN_EXPECT,
2877 4 : HITRATE (percent));
2878 : }
2879 : else
2880 0 : predict_edge_def (e, predictor, TAKEN);
2881 : }
2882 : }
2883 :
2884 11423739 : if (gimple_code (stmt) != GIMPLE_COND)
2885 : return;
2886 4190016 : FOR_EACH_EDGE (then_edge, ei, bb->succs)
2887 4190016 : if (then_edge->flags & EDGE_TRUE_VALUE)
2888 : break;
2889 4047211 : op0 = gimple_cond_lhs (stmt);
2890 4047211 : op1 = gimple_cond_rhs (stmt);
2891 4047211 : cmp = gimple_cond_code (stmt);
2892 4047211 : type = TREE_TYPE (op0);
2893 4047211 : val = expr_expected_value_1 (boolean_type_node, op0, cmp, op1,
2894 : &predictor, &probability);
2895 4047211 : if (val && TREE_CODE (val) == INTEGER_CST)
2896 : {
2897 175897 : HOST_WIDE_INT prob = get_predictor_value (predictor, probability);
2898 175897 : if (integer_zerop (val))
2899 137499 : prob = REG_BR_PROB_BASE - prob;
2900 175897 : predict_edge (then_edge, predictor, prob);
2901 : }
2902 : /* Try "pointer heuristic."
2903 : A comparison ptr == 0 is predicted as false.
2904 : Similarly, a comparison ptr1 == ptr2 is predicted as false. */
2905 4047211 : if (POINTER_TYPE_P (type))
2906 : {
2907 581048 : if (cmp == EQ_EXPR)
2908 233913 : predict_edge_def (then_edge, PRED_TREE_POINTER, NOT_TAKEN);
2909 347135 : else if (cmp == NE_EXPR)
2910 327633 : predict_edge_def (then_edge, PRED_TREE_POINTER, TAKEN);
2911 : }
2912 : else
2913 :
2914 : /* Try "opcode heuristic."
2915 : EQ tests are usually false and NE tests are usually true. Also,
2916 : most quantities are positive, so we can make the appropriate guesses
2917 : about signed comparisons against zero. */
2918 3466163 : switch (cmp)
2919 : {
2920 917458 : case EQ_EXPR:
2921 917458 : case UNEQ_EXPR:
2922 : /* Floating point comparisons appears to behave in a very
2923 : unpredictable way because of special role of = tests in
2924 : FP code. */
2925 917458 : if (FLOAT_TYPE_P (type))
2926 : ;
2927 : /* Comparisons with 0 are often used for booleans and there is
2928 : nothing useful to predict about them. */
2929 902587 : else if (integer_zerop (op0) || integer_zerop (op1))
2930 : ;
2931 : else
2932 362619 : predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, NOT_TAKEN);
2933 : break;
2934 :
2935 1688827 : case NE_EXPR:
2936 1688827 : case LTGT_EXPR:
2937 : /* Floating point comparisons appears to behave in a very
2938 : unpredictable way because of special role of = tests in
2939 : FP code. */
2940 1688827 : if (FLOAT_TYPE_P (type))
2941 : ;
2942 : /* Comparisons with 0 are often used for booleans and there is
2943 : nothing useful to predict about them. */
2944 1571994 : else if (integer_zerop (op0)
2945 1571994 : || integer_zerop (op1))
2946 : ;
2947 : else
2948 554406 : predict_edge_def (then_edge, PRED_TREE_OPCODE_NONEQUAL, TAKEN);
2949 : break;
2950 :
2951 2304 : case ORDERED_EXPR:
2952 2304 : predict_edge_def (then_edge, PRED_TREE_FPOPCODE, TAKEN);
2953 2304 : break;
2954 :
2955 2801 : case UNORDERED_EXPR:
2956 2801 : predict_edge_def (then_edge, PRED_TREE_FPOPCODE, NOT_TAKEN);
2957 2801 : break;
2958 :
2959 348439 : case LE_EXPR:
2960 348439 : case LT_EXPR:
2961 348439 : if (integer_zerop (op1)
2962 287848 : || integer_onep (op1)
2963 280020 : || integer_all_onesp (op1)
2964 279961 : || real_zerop (op1)
2965 276710 : || real_onep (op1)
2966 624414 : || real_minus_onep (op1))
2967 72468 : predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, NOT_TAKEN);
2968 : break;
2969 :
2970 497177 : case GE_EXPR:
2971 497177 : case GT_EXPR:
2972 497177 : if (integer_zerop (op1)
2973 430691 : || integer_onep (op1)
2974 418538 : || integer_all_onesp (op1)
2975 418261 : || real_zerop (op1)
2976 416684 : || real_onep (op1)
2977 913116 : || real_minus_onep (op1))
2978 81262 : predict_edge_def (then_edge, PRED_TREE_OPCODE_POSITIVE, TAKEN);
2979 : break;
2980 :
2981 : default:
2982 : break;
2983 : }
2984 : }
2985 :
2986 : /* Returns TRUE if the STMT is exit(0) like statement. */
2987 :
2988 : static bool
2989 874249 : is_exit_with_zero_arg (const gimple *stmt)
2990 : {
2991 : /* This is not exit, _exit or _Exit. */
2992 874249 : if (!gimple_call_builtin_p (stmt, BUILT_IN_EXIT)
2993 870240 : && !gimple_call_builtin_p (stmt, BUILT_IN__EXIT)
2994 1744467 : && !gimple_call_builtin_p (stmt, BUILT_IN__EXIT2))
2995 : return false;
2996 :
2997 : /* Argument is an integer zero. */
2998 4031 : return integer_zerop (gimple_call_arg (stmt, 0));
2999 : }
3000 :
3001 : /* Try to guess whether the value of return means error code. */
3002 :
3003 : static enum br_predictor
3004 711918 : return_prediction (tree val, enum prediction *prediction)
3005 : {
3006 : /* VOID. */
3007 711918 : if (!val)
3008 : return PRED_NO_PREDICTION;
3009 : /* Different heuristics for pointers and scalars. */
3010 711918 : if (POINTER_TYPE_P (TREE_TYPE (val)))
3011 : {
3012 : /* NULL is usually not returned. */
3013 127047 : if (integer_zerop (val))
3014 : {
3015 26542 : *prediction = NOT_TAKEN;
3016 26542 : return PRED_NULL_RETURN;
3017 : }
3018 : }
3019 584871 : else if (INTEGRAL_TYPE_P (TREE_TYPE (val)))
3020 : {
3021 : /* Negative return values are often used to indicate
3022 : errors. */
3023 482314 : if (TREE_CODE (val) == INTEGER_CST
3024 482314 : && tree_int_cst_sgn (val) < 0)
3025 : {
3026 16503 : *prediction = NOT_TAKEN;
3027 16503 : return PRED_NEGATIVE_RETURN;
3028 : }
3029 : /* Constant return values seems to be commonly taken.
3030 : Zero/one often represent booleans so exclude them from the
3031 : heuristics. */
3032 465811 : if (TREE_CONSTANT (val)
3033 465811 : && (!integer_zerop (val) && !integer_onep (val)))
3034 : {
3035 73155 : *prediction = NOT_TAKEN;
3036 73155 : return PRED_CONST_RETURN;
3037 : }
3038 : }
3039 : return PRED_NO_PREDICTION;
3040 : }
3041 :
3042 : /* Return zero if phi result could have values other than -1, 0 or 1,
3043 : otherwise return a bitmask, with bits 0, 1 and 2 set if -1, 0 and 1
3044 : values are used or likely. */
3045 :
3046 : static int
3047 66212 : zero_one_minusone (gphi *phi, int limit)
3048 : {
3049 66212 : int phi_num_args = gimple_phi_num_args (phi);
3050 66212 : int ret = 0;
3051 223463 : for (int i = 0; i < phi_num_args; i++)
3052 : {
3053 168303 : tree t = PHI_ARG_DEF (phi, i);
3054 168303 : if (TREE_CODE (t) != INTEGER_CST)
3055 77200 : continue;
3056 91103 : wide_int w = wi::to_wide (t);
3057 91103 : if (w == -1)
3058 8298 : ret |= 1;
3059 82805 : else if (w == 0)
3060 41354 : ret |= 2;
3061 41451 : else if (w == 1)
3062 30399 : ret |= 4;
3063 : else
3064 11052 : return 0;
3065 91103 : }
3066 125074 : for (int i = 0; i < phi_num_args; i++)
3067 : {
3068 107660 : tree t = PHI_ARG_DEF (phi, i);
3069 107660 : if (TREE_CODE (t) == INTEGER_CST)
3070 67991 : continue;
3071 39669 : if (TREE_CODE (t) != SSA_NAME)
3072 : return 0;
3073 39669 : gimple *g = SSA_NAME_DEF_STMT (t);
3074 39669 : if (gimple_code (g) == GIMPLE_PHI && limit > 0)
3075 12856 : if (int r = zero_one_minusone (as_a <gphi *> (g), limit - 1))
3076 : {
3077 498 : ret |= r;
3078 498 : continue;
3079 : }
3080 39171 : gassign *assign = dyn_cast<gassign *> (g);
3081 14834 : if (!assign)
3082 : return 0;
3083 14834 : if (gimple_assign_cast_p (assign))
3084 : {
3085 3707 : tree rhs1 = gimple_assign_rhs1 (assign);
3086 3707 : if (TREE_CODE (rhs1) != SSA_NAME
3087 3707 : || !INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
3088 3627 : || TYPE_PRECISION (TREE_TYPE (rhs1)) != 1
3089 5133 : || !TYPE_UNSIGNED (TREE_TYPE (rhs1)))
3090 : return 0;
3091 1425 : ret |= (2 | 4);
3092 1425 : continue;
3093 1425 : }
3094 11127 : if (TREE_CODE_CLASS (gimple_assign_rhs_code (g)) != tcc_comparison)
3095 : return 0;
3096 0 : ret |= (2 | 4);
3097 : }
3098 : return ret;
3099 : }
3100 :
3101 : /* Find the basic block with return expression and look up for possible
3102 : return value trying to apply RETURN_PREDICTION heuristics. */
3103 : static void
3104 2526247 : apply_return_prediction (void)
3105 : {
3106 2526247 : greturn *return_stmt = NULL;
3107 2526247 : tree return_val;
3108 2526247 : edge e;
3109 2526247 : gphi *phi;
3110 2526247 : int phi_num_args, i;
3111 2526247 : enum br_predictor pred;
3112 2526247 : enum prediction direction;
3113 2526247 : edge_iterator ei;
3114 :
3115 2590488 : FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
3116 : {
3117 5184654 : if (greturn *last = safe_dyn_cast <greturn *> (*gsi_last_bb (e->src)))
3118 : {
3119 : return_stmt = last;
3120 : break;
3121 : }
3122 : }
3123 2526247 : if (!e)
3124 2345623 : return;
3125 2496323 : return_val = gimple_return_retval (return_stmt);
3126 2496323 : if (!return_val)
3127 : return;
3128 1402351 : if (TREE_CODE (return_val) != SSA_NAME
3129 1020769 : || !SSA_NAME_DEF_STMT (return_val)
3130 2423120 : || gimple_code (SSA_NAME_DEF_STMT (return_val)) != GIMPLE_PHI)
3131 : return;
3132 181446 : phi = as_a <gphi *> (SSA_NAME_DEF_STMT (return_val));
3133 181446 : phi_num_args = gimple_phi_num_args (phi);
3134 181446 : pred = return_prediction (PHI_ARG_DEF (phi, 0), &direction);
3135 :
3136 : /* Avoid the case where the function returns -1, 0 and 1 values and
3137 : nothing else. Those could be qsort etc. comparison functions
3138 : where the negative return isn't less probable than positive.
3139 : For this require that the function returns at least -1 or 1
3140 : or -1 and a boolean value or comparison result, so that functions
3141 : returning just -1 and 0 are treated as if -1 represents error value. */
3142 361318 : if (INTEGRAL_TYPE_P (TREE_TYPE (return_val))
3143 133151 : && !TYPE_UNSIGNED (TREE_TYPE (return_val))
3144 234802 : && TYPE_PRECISION (TREE_TYPE (return_val)) > 1)
3145 53356 : if (int r = zero_one_minusone (phi, 3))
3146 16916 : if ((r & (1 | 4)) == (1 | 4))
3147 : return;
3148 :
3149 : /* Avoid the degenerate case where all return values form the function
3150 : belongs to same category (ie they are all positive constants)
3151 : so we can hardly say something about them. */
3152 582709 : for (i = 1; i < phi_num_args; i++)
3153 432440 : if (pred != return_prediction (PHI_ARG_DEF (phi, i), &direction))
3154 : break;
3155 180624 : if (i != phi_num_args)
3156 128387 : for (i = 0; i < phi_num_args; i++)
3157 : {
3158 98032 : pred = return_prediction (PHI_ARG_DEF (phi, i), &direction);
3159 98032 : if (pred != PRED_NO_PREDICTION)
3160 51416 : predict_paths_leading_to_edge (gimple_phi_arg_edge (phi, i), pred,
3161 : direction);
3162 : }
3163 : }
3164 :
3165 : /* Look for basic block that contains unlikely to happen events
3166 : (such as noreturn calls) and mark all paths leading to execution
3167 : of this basic blocks as unlikely. */
3168 :
3169 : static void
3170 2526247 : tree_bb_level_predictions (void)
3171 : {
3172 2526247 : basic_block bb;
3173 2526247 : bool has_return_edges = false;
3174 2526247 : edge e;
3175 2526247 : edge_iterator ei;
3176 :
3177 2601608 : FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
3178 2570134 : if (!unlikely_executed_edge_p (e) && !(e->flags & EDGE_ABNORMAL_CALL))
3179 : {
3180 : has_return_edges = true;
3181 : break;
3182 : }
3183 :
3184 2526247 : apply_return_prediction ();
3185 :
3186 14292748 : FOR_EACH_BB_FN (bb, cfun)
3187 : {
3188 11766501 : gimple_stmt_iterator gsi;
3189 :
3190 96701138 : for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3191 : {
3192 73168136 : gimple *stmt = gsi_stmt (gsi);
3193 73168136 : tree decl;
3194 :
3195 73168136 : if (is_gimple_call (stmt))
3196 : {
3197 6373750 : if (gimple_call_noreturn_p (stmt)
3198 942892 : && has_return_edges
3199 7247999 : && !is_exit_with_zero_arg (stmt))
3200 871531 : predict_paths_leading_to (bb, PRED_NORETURN,
3201 : NOT_TAKEN);
3202 6373750 : decl = gimple_call_fndecl (stmt);
3203 6373750 : if (decl
3204 12353444 : && lookup_attribute ("cold",
3205 5979694 : DECL_ATTRIBUTES (decl)))
3206 553889 : predict_paths_leading_to (bb, PRED_COLD_FUNCTION,
3207 : NOT_TAKEN);
3208 6373750 : if (decl && recursive_call_p (current_function_decl, decl))
3209 10518 : predict_paths_leading_to (bb, PRED_RECURSIVE_CALL,
3210 : NOT_TAKEN);
3211 : }
3212 66794386 : else if (gimple_code (stmt) == GIMPLE_PREDICT)
3213 : {
3214 462266 : predict_paths_leading_to (bb, gimple_predict_predictor (stmt),
3215 : gimple_predict_outcome (stmt));
3216 : /* Keep GIMPLE_PREDICT around so early inlining will propagate
3217 : hints to callers. */
3218 : }
3219 : }
3220 : }
3221 2526247 : }
3222 :
3223 : /* Callback for hash_map::traverse, asserts that the pointer map is
3224 : empty. */
3225 :
3226 : bool
3227 3740197 : assert_is_empty (const_basic_block const &, edge_prediction *const &value,
3228 : void *)
3229 : {
3230 3740197 : gcc_assert (!value);
3231 3740197 : return true;
3232 : }
3233 :
3234 : /* Predict branch probabilities and estimate profile for basic block BB.
3235 : When LOCAL_ONLY is set do not use any global properties of CFG. */
3236 :
3237 : static void
3238 11906230 : tree_estimate_probability_bb (basic_block bb, bool local_only)
3239 : {
3240 11906230 : edge e;
3241 11906230 : edge_iterator ei;
3242 :
3243 28588659 : FOR_EACH_EDGE (e, ei, bb->succs)
3244 : {
3245 : /* Look for block we are guarding (ie we dominate it,
3246 : but it doesn't postdominate us). */
3247 13175780 : if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun) && e->dest != bb
3248 13175760 : && !local_only
3249 13006610 : && dominated_by_p (CDI_DOMINATORS, e->dest, e->src)
3250 25255592 : && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e->dest))
3251 : {
3252 6687520 : gimple_stmt_iterator bi;
3253 :
3254 : /* The call heuristic claims that a guarded function call
3255 : is improbable. This is because such calls are often used
3256 : to signal exceptional situations such as printing error
3257 : messages. */
3258 39101216 : for (bi = gsi_start_bb (e->dest); !gsi_end_p (bi);
3259 25726176 : gsi_next (&bi))
3260 : {
3261 28252203 : gimple *stmt = gsi_stmt (bi);
3262 28252203 : if (is_gimple_call (stmt)
3263 3172044 : && !gimple_inexpensive_call_p (as_a <gcall *> (stmt))
3264 : /* Constant and pure calls are hardly used to signalize
3265 : something exceptional. */
3266 31128843 : && gimple_has_side_effects (stmt))
3267 : {
3268 2526027 : if (gimple_call_fndecl (stmt))
3269 2461624 : predict_edge_def (e, PRED_CALL, NOT_TAKEN);
3270 64403 : else if (virtual_method_call_p (gimple_call_fn (stmt)))
3271 13408 : predict_edge_def (e, PRED_POLYMORPHIC_CALL, NOT_TAKEN);
3272 : else
3273 50995 : predict_edge_def (e, PRED_INDIR_CALL, TAKEN);
3274 : break;
3275 : }
3276 : }
3277 : }
3278 : }
3279 11906230 : tree_predict_by_opcode (bb);
3280 11906230 : }
3281 :
3282 : /* Predict branch probabilities and estimate profile of the tree CFG.
3283 : This function can be called from the loop optimizers to recompute
3284 : the profile information.
3285 : If DRY_RUN is set, do not modify CFG and only produce dump files. */
3286 :
3287 : void
3288 2526247 : tree_estimate_probability (bool dry_run)
3289 : {
3290 2526247 : basic_block bb;
3291 :
3292 2526247 : connect_infinite_loops_to_exit ();
3293 : /* We use loop_niter_by_eval, which requires that the loops have
3294 : preheaders. */
3295 2526247 : create_preheaders (CP_SIMPLE_PREHEADERS);
3296 2526247 : calculate_dominance_info (CDI_POST_DOMINATORS);
3297 : /* Decide which edges are known to be unlikely. This improves later
3298 : branch prediction. */
3299 2526247 : if (!dry_run)
3300 2526235 : determine_unlikely_bbs ();
3301 :
3302 2526247 : bb_predictions = new hash_map<const_basic_block, edge_prediction *>;
3303 2526247 : ssa_expected_value = new hash_map<int_hash<unsigned, 0>, expected_value>;
3304 :
3305 2526247 : tree_bb_level_predictions ();
3306 2526247 : record_loop_exits ();
3307 :
3308 5052494 : if (number_of_loops (cfun) > 1)
3309 287186 : predict_loops ();
3310 :
3311 14292748 : FOR_EACH_BB_FN (bb, cfun)
3312 11766501 : tree_estimate_probability_bb (bb, false);
3313 :
3314 14292748 : FOR_EACH_BB_FN (bb, cfun)
3315 11766501 : combine_predictions_for_bb (bb, dry_run);
3316 :
3317 2526247 : if (flag_checking)
3318 6266416 : bb_predictions->traverse<void *, assert_is_empty> (NULL);
3319 :
3320 5052494 : delete bb_predictions;
3321 2526247 : bb_predictions = NULL;
3322 5052494 : delete ssa_expected_value;
3323 2526247 : ssa_expected_value = NULL;
3324 :
3325 2526247 : if (!dry_run
3326 2526235 : && profile_status_for_fn (cfun) != PROFILE_READ)
3327 2526235 : estimate_bb_frequencies ();
3328 2526247 : free_dominance_info (CDI_POST_DOMINATORS);
3329 2526247 : remove_fake_exit_edges ();
3330 2526247 : }
3331 :
3332 : /* Set edge->probability for each successor edge of BB. */
3333 : void
3334 139729 : tree_guess_outgoing_edge_probabilities (basic_block bb)
3335 : {
3336 139729 : bb_predictions = new hash_map<const_basic_block, edge_prediction *>;
3337 139729 : ssa_expected_value = new hash_map<int_hash<unsigned, 0>, expected_value>;
3338 139729 : tree_estimate_probability_bb (bb, true);
3339 139729 : combine_predictions_for_bb (bb, false);
3340 139729 : if (flag_checking)
3341 139729 : bb_predictions->traverse<void *, assert_is_empty> (NULL);
3342 279458 : delete bb_predictions;
3343 139729 : bb_predictions = NULL;
3344 279458 : delete ssa_expected_value;
3345 139729 : ssa_expected_value = NULL;
3346 139729 : }
3347 :
3348 : /* Filter function predicate that returns true for a edge predicate P
3349 : if its edge is equal to DATA. */
3350 :
3351 : static bool
3352 8 : not_loop_guard_equal_edge_p (edge_prediction *p, void *data)
3353 : {
3354 8 : return p->ep_edge != (edge)data || p->ep_predictor != PRED_LOOP_GUARD;
3355 : }
3356 :
3357 : /* Predict edge E with PRED unless it is already predicted by some predictor
3358 : considered equivalent. */
3359 :
3360 : static void
3361 1112204 : maybe_predict_edge (edge e, enum br_predictor pred, enum prediction taken)
3362 : {
3363 1112204 : if (edge_predicted_by_p (e, pred, taken))
3364 : return;
3365 1107858 : if (pred == PRED_LOOP_GUARD
3366 1107858 : && edge_predicted_by_p (e, PRED_LOOP_GUARD_WITH_RECURSION, taken))
3367 : return;
3368 : /* Consider PRED_LOOP_GUARD_WITH_RECURSION superrior to LOOP_GUARD. */
3369 1107850 : if (pred == PRED_LOOP_GUARD_WITH_RECURSION)
3370 : {
3371 15 : edge_prediction **preds = bb_predictions->get (e->src);
3372 15 : if (preds)
3373 4 : filter_predictions (preds, not_loop_guard_equal_edge_p, e);
3374 : }
3375 1107850 : predict_edge_def (e, pred, taken);
3376 : }
3377 : /* Predict edges to successors of CUR whose sources are not postdominated by
3378 : BB by PRED and recurse to all postdominators. */
3379 :
3380 : static void
3381 2459615 : predict_paths_for_bb (basic_block cur, basic_block bb,
3382 : enum br_predictor pred,
3383 : enum prediction taken,
3384 : bitmap visited, class loop *in_loop = NULL)
3385 : {
3386 2459615 : edge e;
3387 2459615 : edge_iterator ei;
3388 2459615 : basic_block son;
3389 :
3390 : /* If we exited the loop or CUR is unconditional in the loop, there is
3391 : nothing to do. */
3392 2459615 : if (in_loop
3393 2459615 : && (!flow_bb_inside_loop_p (in_loop, cur)
3394 74363 : || dominated_by_p (CDI_DOMINATORS, in_loop->latch, cur)))
3395 11634 : return;
3396 :
3397 : /* We are looking for all edges forming edge cut induced by
3398 : set of all blocks postdominated by BB. */
3399 5463867 : FOR_EACH_EDGE (e, ei, cur->preds)
3400 3015886 : if (e->src->index >= NUM_FIXED_BLOCKS
3401 3015886 : && !dominated_by_p (CDI_POST_DOMINATORS, e->src, bb))
3402 : {
3403 2351926 : edge e2;
3404 2351926 : edge_iterator ei2;
3405 2351926 : bool found = false;
3406 :
3407 : /* Ignore fake edges and eh, we predict them as not taken anyway. */
3408 2351926 : if (unlikely_executed_edge_p (e))
3409 1243746 : continue;
3410 1108180 : gcc_assert (bb == cur || dominated_by_p (CDI_POST_DOMINATORS, cur, bb));
3411 :
3412 : /* See if there is an edge from e->src that is not abnormal
3413 : and does not lead to BB and does not exit the loop. */
3414 2009359 : FOR_EACH_EDGE (e2, ei2, e->src->succs)
3415 1981102 : if (e2 != e
3416 1115252 : && !unlikely_executed_edge_p (e2)
3417 1089180 : && !dominated_by_p (CDI_POST_DOMINATORS, e2->dest, bb)
3418 3064093 : && (!in_loop || !loop_exit_edge_p (in_loop, e2)))
3419 : {
3420 : found = true;
3421 : break;
3422 : }
3423 :
3424 : /* If there is non-abnormal path leaving e->src, predict edge
3425 : using predictor. Otherwise we need to look for paths
3426 : leading to e->src.
3427 :
3428 : The second may lead to infinite loop in the case we are predicting
3429 : regions that are only reachable by abnormal edges. We simply
3430 : prevent visiting given BB twice. */
3431 1108180 : if (found)
3432 1079923 : maybe_predict_edge (e, pred, taken);
3433 28257 : else if (bitmap_set_bit (visited, e->src->index))
3434 28207 : predict_paths_for_bb (e->src, e->src, pred, taken, visited, in_loop);
3435 : }
3436 2447981 : for (son = first_dom_son (CDI_POST_DOMINATORS, cur);
3437 2909798 : son;
3438 461817 : son = next_dom_son (CDI_POST_DOMINATORS, son))
3439 461817 : predict_paths_for_bb (son, bb, pred, taken, visited, in_loop);
3440 : }
3441 :
3442 : /* Sets branch probabilities according to PREDiction and
3443 : FLAGS. */
3444 :
3445 : static void
3446 1898204 : predict_paths_leading_to (basic_block bb, enum br_predictor pred,
3447 : enum prediction taken, class loop *in_loop)
3448 : {
3449 1898204 : predict_paths_for_bb (bb, bb, pred, taken, auto_bitmap (), in_loop);
3450 1898204 : }
3451 :
3452 : /* Like predict_paths_leading_to but take edge instead of basic block. */
3453 :
3454 : static void
3455 103668 : predict_paths_leading_to_edge (edge e, enum br_predictor pred,
3456 : enum prediction taken, class loop *in_loop)
3457 : {
3458 103668 : bool has_nonloop_edge = false;
3459 103668 : edge_iterator ei;
3460 103668 : edge e2;
3461 :
3462 103668 : basic_block bb = e->src;
3463 197575 : FOR_EACH_EDGE (e2, ei, bb->succs)
3464 126188 : if (e2->dest != e->src && e2->dest != e->dest
3465 44533 : && !unlikely_executed_edge_p (e2)
3466 168070 : && !dominated_by_p (CDI_POST_DOMINATORS, e->src, e2->dest))
3467 : {
3468 : has_nonloop_edge = true;
3469 : break;
3470 : }
3471 :
3472 103668 : if (!has_nonloop_edge)
3473 71387 : predict_paths_for_bb (bb, bb, pred, taken, auto_bitmap (), in_loop);
3474 : else
3475 32281 : maybe_predict_edge (e, pred, taken);
3476 103668 : }
3477 :
3478 : /* This is used to carry information about basic blocks. It is
3479 : attached to the AUX field of the standard CFG block. */
3480 :
3481 : class block_info
3482 : {
3483 : public:
3484 : /* Estimated frequency of execution of basic_block. */
3485 : sreal frequency;
3486 :
3487 : /* To keep queue of basic blocks to process. */
3488 : basic_block next;
3489 :
3490 : /* Number of predecessors we need to visit first. */
3491 : int npredecessors;
3492 : };
3493 :
3494 : /* Similar information for edges. */
3495 : class edge_prob_info
3496 : {
3497 : public:
3498 : /* In case edge is a loopback edge, the probability edge will be reached
3499 : in case header is. Estimated number of iterations of the loop can be
3500 : then computed as 1 / (1 - back_edge_prob). */
3501 : sreal back_edge_prob;
3502 : /* True if the edge is a loopback edge in the natural loop. */
3503 : unsigned int back_edge:1;
3504 : };
3505 :
3506 : #define BLOCK_INFO(B) ((block_info *) (B)->aux)
3507 : #undef EDGE_INFO
3508 : #define EDGE_INFO(E) ((edge_prob_info *) (E)->aux)
3509 :
3510 : /* Helper function for estimate_bb_frequencies.
3511 : Propagate the frequencies in blocks marked in
3512 : TOVISIT, starting in HEAD. */
3513 :
3514 : static void
3515 3407208 : propagate_freq (basic_block head, bitmap tovisit,
3516 : sreal max_cyclic_prob)
3517 : {
3518 3407208 : basic_block bb;
3519 3407208 : basic_block last;
3520 3407208 : unsigned i;
3521 3407208 : edge e;
3522 3407208 : basic_block nextbb;
3523 3407208 : bitmap_iterator bi;
3524 :
3525 : /* For each basic block we need to visit count number of his predecessors
3526 : we need to visit first. */
3527 27545839 : EXECUTE_IF_SET_IN_BITMAP (tovisit, 0, i, bi)
3528 : {
3529 24138631 : edge_iterator ei;
3530 24138631 : int count = 0;
3531 :
3532 24138631 : bb = BASIC_BLOCK_FOR_FN (cfun, i);
3533 :
3534 53786937 : FOR_EACH_EDGE (e, ei, bb->preds)
3535 : {
3536 29648306 : bool visit = bitmap_bit_p (tovisit, e->src->index);
3537 :
3538 29648306 : if (visit && !(e->flags & EDGE_DFS_BACK))
3539 26859965 : count++;
3540 1965714 : else if (visit && dump_file && !EDGE_INFO (e)->back_edge)
3541 3 : fprintf (dump_file,
3542 : "Irreducible region hit, ignoring edge to %i->%i\n",
3543 3 : e->src->index, bb->index);
3544 : }
3545 24138631 : BLOCK_INFO (bb)->npredecessors = count;
3546 : /* When function never returns, we will never process exit block. */
3547 24138631 : if (!count && bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
3548 0 : bb->count = profile_count::zero ();
3549 : }
3550 :
3551 3407208 : BLOCK_INFO (head)->frequency = 1;
3552 3407208 : last = head;
3553 27545839 : for (bb = head; bb; bb = nextbb)
3554 : {
3555 24138631 : edge_iterator ei;
3556 24138631 : sreal cyclic_probability = 0;
3557 24138631 : sreal frequency = 0;
3558 :
3559 24138631 : nextbb = BLOCK_INFO (bb)->next;
3560 24138631 : BLOCK_INFO (bb)->next = NULL;
3561 :
3562 : /* Compute frequency of basic block. */
3563 24138631 : if (bb != head)
3564 : {
3565 20731423 : if (flag_checking)
3566 48733767 : FOR_EACH_EDGE (e, ei, bb->preds)
3567 28002738 : gcc_assert (!bitmap_bit_p (tovisit, e->src->index)
3568 : || (e->flags & EDGE_DFS_BACK));
3569 :
3570 48734727 : FOR_EACH_EDGE (e, ei, bb->preds)
3571 28003304 : if (EDGE_INFO (e)->back_edge)
3572 1138090 : cyclic_probability += EDGE_INFO (e)->back_edge_prob;
3573 26865214 : else if (!(e->flags & EDGE_DFS_BACK))
3574 : {
3575 : /* FIXME: Graphite is producing edges with no profile. Once
3576 : this is fixed, drop this. */
3577 26859965 : sreal tmp = e->probability.initialized_p () ?
3578 26859965 : e->probability.to_sreal () : 0;
3579 26859965 : frequency += tmp * BLOCK_INFO (e->src)->frequency;
3580 : }
3581 :
3582 20731423 : if (cyclic_probability == 0)
3583 : {
3584 19620839 : BLOCK_INFO (bb)->frequency = frequency;
3585 : }
3586 : else
3587 : {
3588 1110584 : if (cyclic_probability > max_cyclic_prob)
3589 : {
3590 9894 : if (dump_file)
3591 252 : fprintf (dump_file,
3592 : "cyclic probability of bb %i is %f (capped to %f)"
3593 : "; turning freq %f",
3594 : bb->index, cyclic_probability.to_double (),
3595 : max_cyclic_prob.to_double (),
3596 : frequency.to_double ());
3597 :
3598 9894 : cyclic_probability = max_cyclic_prob;
3599 : }
3600 1100690 : else if (dump_file)
3601 111 : fprintf (dump_file,
3602 : "cyclic probability of bb %i is %f; turning freq %f",
3603 : bb->index, cyclic_probability.to_double (),
3604 : frequency.to_double ());
3605 :
3606 1110584 : BLOCK_INFO (bb)->frequency = frequency
3607 1110584 : / (sreal (1) - cyclic_probability);
3608 1110584 : if (dump_file)
3609 363 : fprintf (dump_file, " to %f\n",
3610 363 : BLOCK_INFO (bb)->frequency.to_double ());
3611 : }
3612 : }
3613 :
3614 24138631 : bitmap_clear_bit (tovisit, bb->index);
3615 :
3616 24138631 : e = find_edge (bb, head);
3617 24138631 : if (e)
3618 : {
3619 : /* FIXME: Graphite is producing edges with no profile. Once
3620 : this is fixed, drop this. */
3621 822375 : sreal tmp = e->probability.initialized_p () ?
3622 822375 : e->probability.to_sreal () : 0;
3623 822375 : EDGE_INFO (e)->back_edge_prob = tmp * BLOCK_INFO (bb)->frequency;
3624 : }
3625 :
3626 : /* Propagate to successor blocks. */
3627 54362582 : FOR_EACH_EDGE (e, ei, bb->succs)
3628 30223951 : if (!(e->flags & EDGE_DFS_BACK)
3629 28256929 : && BLOCK_INFO (e->dest)->npredecessors)
3630 : {
3631 26859965 : BLOCK_INFO (e->dest)->npredecessors--;
3632 26859965 : if (!BLOCK_INFO (e->dest)->npredecessors)
3633 : {
3634 20731423 : if (!nextbb)
3635 : nextbb = e->dest;
3636 : else
3637 7888475 : BLOCK_INFO (last)->next = e->dest;
3638 :
3639 : last = e->dest;
3640 : }
3641 : }
3642 : }
3643 3407208 : }
3644 :
3645 : /* Estimate frequencies in loops at same nest level. */
3646 :
3647 : static void
3648 1145128 : estimate_loops_at_level (class loop *first_loop, sreal max_cyclic_prob)
3649 : {
3650 1145128 : class loop *loop;
3651 :
3652 1967503 : for (loop = first_loop; loop; loop = loop->next)
3653 : {
3654 822375 : edge e;
3655 822375 : basic_block *bbs;
3656 822375 : unsigned i;
3657 822375 : auto_bitmap tovisit;
3658 :
3659 822375 : estimate_loops_at_level (loop->inner, max_cyclic_prob);
3660 :
3661 : /* Find current loop back edge and mark it. */
3662 822375 : e = loop_latch_edge (loop);
3663 822375 : EDGE_INFO (e)->back_edge = 1;
3664 :
3665 822375 : bbs = get_loop_body (loop);
3666 6144339 : for (i = 0; i < loop->num_nodes; i++)
3667 4499589 : bitmap_set_bit (tovisit, bbs[i]->index);
3668 822375 : free (bbs);
3669 822375 : propagate_freq (loop->header, tovisit, max_cyclic_prob);
3670 822375 : }
3671 1145128 : }
3672 :
3673 : /* Propagates frequencies through structure of loops. */
3674 :
3675 : static void
3676 2584833 : estimate_loops (void)
3677 : {
3678 2584833 : auto_bitmap tovisit;
3679 2584833 : basic_block bb;
3680 7754499 : sreal max_cyclic_prob = (sreal)1
3681 2584833 : - (sreal)1 / (param_max_predicted_iterations + 1);
3682 :
3683 : /* Start by estimating the frequencies in the loops. */
3684 5169666 : if (number_of_loops (cfun) > 1)
3685 322753 : estimate_loops_at_level (current_loops->tree_root->inner, max_cyclic_prob);
3686 :
3687 : /* Now propagate the frequencies through all the blocks. */
3688 22223875 : FOR_ALL_BB_FN (bb, cfun)
3689 : {
3690 19639042 : bitmap_set_bit (tovisit, bb->index);
3691 : }
3692 2584833 : propagate_freq (ENTRY_BLOCK_PTR_FOR_FN (cfun), tovisit, max_cyclic_prob);
3693 2584833 : }
3694 :
3695 : /* Drop the profile for NODE to guessed, and update its frequency based on
3696 : whether it is expected to be hot given the CALL_COUNT. */
3697 :
3698 : static void
3699 0 : drop_profile (struct cgraph_node *node, profile_count call_count)
3700 : {
3701 0 : struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3702 : /* In the case where this was called by another function with a
3703 : dropped profile, call_count will be 0. Since there are no
3704 : non-zero call counts to this function, we don't know for sure
3705 : whether it is hot, and therefore it will be marked normal below. */
3706 0 : bool hot = maybe_hot_count_p (NULL, call_count);
3707 :
3708 0 : if (dump_file)
3709 0 : fprintf (dump_file,
3710 : "Dropping 0 profile for %s. %s based on calls.\n",
3711 : node->dump_name (),
3712 : hot ? "Function is hot" : "Function is normal");
3713 : /* We only expect to miss profiles for functions that are reached
3714 : via non-zero call edges in cases where the function may have
3715 : been linked from another module or library (COMDATs and extern
3716 : templates). See the comments below for handle_missing_profiles.
3717 : Also, only warn in cases where the missing counts exceed the
3718 : number of training runs. In certain cases with an execv followed
3719 : by a no-return call the profile for the no-return call is not
3720 : dumped and there can be a mismatch. */
3721 0 : if (!DECL_COMDAT (node->decl) && !DECL_EXTERNAL (node->decl)
3722 0 : && call_count > profile_info->runs)
3723 : {
3724 0 : if (flag_profile_correction)
3725 : {
3726 0 : if (dump_file)
3727 0 : fprintf (dump_file,
3728 : "Missing counts for called function %s\n",
3729 : node->dump_name ());
3730 : }
3731 : else
3732 0 : warning (0, "Missing counts for called function %s",
3733 : node->dump_name ());
3734 : }
3735 :
3736 0 : basic_block bb;
3737 0 : if (opt_for_fn (node->decl, flag_guess_branch_prob))
3738 : {
3739 0 : bool clear_zeros
3740 0 : = !ENTRY_BLOCK_PTR_FOR_FN (fn)->count.nonzero_p ();
3741 0 : FOR_ALL_BB_FN (bb, fn)
3742 0 : if (clear_zeros || !(bb->count == profile_count::zero ()))
3743 0 : bb->count = bb->count.guessed_local ();
3744 0 : fn->cfg->count_max = fn->cfg->count_max.guessed_local ();
3745 : }
3746 : else
3747 : {
3748 0 : FOR_ALL_BB_FN (bb, fn)
3749 0 : bb->count = profile_count::uninitialized ();
3750 0 : fn->cfg->count_max = profile_count::uninitialized ();
3751 : }
3752 :
3753 0 : struct cgraph_edge *e;
3754 0 : for (e = node->callees; e; e = e->next_callee)
3755 0 : e->count = gimple_bb (e->call_stmt)->count;
3756 0 : for (e = node->indirect_calls; e; e = e->next_callee)
3757 0 : e->count = gimple_bb (e->call_stmt)->count;
3758 0 : node->count = ENTRY_BLOCK_PTR_FOR_FN (fn)->count;
3759 :
3760 0 : profile_status_for_fn (fn)
3761 0 : = (flag_guess_branch_prob ? PROFILE_GUESSED : PROFILE_ABSENT);
3762 0 : node->frequency
3763 0 : = hot ? NODE_FREQUENCY_HOT : NODE_FREQUENCY_NORMAL;
3764 0 : }
3765 :
3766 : /* In the case of COMDAT routines, multiple object files will contain the same
3767 : function and the linker will select one for the binary. In that case
3768 : all the other copies from the profile instrument binary will be missing
3769 : profile counts. Look for cases where this happened, due to non-zero
3770 : call counts going to 0-count functions, and drop the profile to guessed
3771 : so that we can use the estimated probabilities and avoid optimizing only
3772 : for size.
3773 :
3774 : The other case where the profile may be missing is when the routine
3775 : is not going to be emitted to the object file, e.g. for "extern template"
3776 : class methods. Those will be marked DECL_EXTERNAL. Emit a warning in
3777 : all other cases of non-zero calls to 0-count functions. */
3778 :
3779 : void
3780 631 : handle_missing_profiles (void)
3781 : {
3782 631 : const int unlikely_frac = param_unlikely_bb_count_fraction;
3783 631 : struct cgraph_node *node;
3784 631 : auto_vec<struct cgraph_node *, 64> worklist;
3785 :
3786 : /* See if 0 count function has non-0 count callers. In this case we
3787 : lost some profile. Drop its function profile to PROFILE_GUESSED. */
3788 3937 : FOR_EACH_DEFINED_FUNCTION (node)
3789 : {
3790 3306 : struct cgraph_edge *e;
3791 3306 : profile_count call_count = profile_count::zero ();
3792 3306 : gcov_type max_tp_first_run = 0;
3793 3306 : struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
3794 :
3795 3306 : if (node->count.ipa ().nonzero_p ())
3796 369 : continue;
3797 6161 : for (e = node->callers; e; e = e->next_caller)
3798 3224 : if (e->count.ipa ().initialized_p () && e->count.ipa () > 0)
3799 : {
3800 8 : call_count = call_count + e->count.ipa ();
3801 :
3802 8 : if (e->caller->tp_first_run > max_tp_first_run)
3803 3224 : max_tp_first_run = e->caller->tp_first_run;
3804 : }
3805 :
3806 : /* If time profile is missing, let assign the maximum that comes from
3807 : caller functions. */
3808 2937 : if (!node->tp_first_run && max_tp_first_run)
3809 4 : node->tp_first_run = max_tp_first_run + 1;
3810 :
3811 2937 : if (call_count > 0
3812 6 : && fn && fn->cfg
3813 2943 : && call_count * unlikely_frac >= profile_info->runs)
3814 : {
3815 0 : drop_profile (node, call_count);
3816 0 : worklist.safe_push (node);
3817 : }
3818 : }
3819 :
3820 : /* Propagate the profile dropping to other 0-count COMDATs that are
3821 : potentially called by COMDATs we already dropped the profile on. */
3822 631 : while (worklist.length () > 0)
3823 : {
3824 0 : struct cgraph_edge *e;
3825 :
3826 0 : node = worklist.pop ();
3827 0 : for (e = node->callees; e; e = e->next_caller)
3828 : {
3829 0 : struct cgraph_node *callee = e->callee;
3830 0 : struct function *fn = DECL_STRUCT_FUNCTION (callee->decl);
3831 :
3832 0 : if (!(e->count.ipa () == profile_count::zero ())
3833 0 : && callee->count.ipa ().nonzero_p ())
3834 0 : continue;
3835 0 : if ((DECL_COMDAT (callee->decl) || DECL_EXTERNAL (callee->decl))
3836 0 : && fn && fn->cfg
3837 0 : && profile_status_for_fn (fn) == PROFILE_READ)
3838 : {
3839 0 : drop_profile (node, profile_count::zero ());
3840 0 : worklist.safe_push (callee);
3841 : }
3842 : }
3843 : }
3844 631 : }
3845 :
3846 : /* Convert counts measured by profile driven feedback to frequencies.
3847 : Return nonzero iff there was any nonzero execution count. */
3848 :
3849 : bool
3850 1830656 : update_max_bb_count (void)
3851 : {
3852 1830656 : profile_count true_count_max = profile_count::uninitialized ();
3853 1830656 : basic_block bb;
3854 :
3855 38608362 : FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
3856 36777706 : true_count_max = profile_count::max_prefer_initialized (true_count_max, bb->count);
3857 :
3858 1830656 : cfun->cfg->count_max = true_count_max;
3859 :
3860 1830656 : return true_count_max.ipa ().nonzero_p ();
3861 : }
3862 :
3863 : /* Return true if function is likely to be expensive, so there is no point to
3864 : optimize performance of prologue, epilogue or do inlining at the expense
3865 : of code size growth. THRESHOLD is the limit of number of instructions
3866 : function can execute at average to be still considered not expensive. */
3867 :
3868 : bool
3869 293676 : expensive_function_p (int threshold)
3870 : {
3871 293676 : basic_block bb;
3872 :
3873 : /* If profile was scaled in a way entry block has count 0, then the function
3874 : is deifnitly taking a lot of time. */
3875 293676 : if (!ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.nonzero_p ())
3876 : return true;
3877 :
3878 252490 : profile_count limit = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count * threshold;
3879 252490 : profile_count sum = profile_count::zero ();
3880 3074213 : FOR_EACH_BB_FN (bb, cfun)
3881 : {
3882 2990615 : rtx_insn *insn;
3883 :
3884 2990615 : if (!bb->count.initialized_p ())
3885 : {
3886 1 : if (dump_file)
3887 0 : fprintf (dump_file, "Function is considered expensive because"
3888 : " count of bb %i is not initialized\n", bb->index);
3889 : return true;
3890 : }
3891 :
3892 46578282 : FOR_BB_INSNS (bb, insn)
3893 43756559 : if (active_insn_p (insn))
3894 : {
3895 17619495 : sum += bb->count;
3896 17619495 : if (sum > limit)
3897 : return true;
3898 : }
3899 : }
3900 :
3901 : return false;
3902 : }
3903 :
3904 : /* All basic blocks that are reachable only from unlikely basic blocks are
3905 : unlikely. */
3906 :
3907 : void
3908 7519240 : propagate_unlikely_bbs_forward (void)
3909 : {
3910 7519240 : auto_vec<basic_block, 64> worklist;
3911 7519240 : basic_block bb;
3912 7519240 : edge_iterator ei;
3913 7519240 : edge e;
3914 :
3915 7538323 : if (!(ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ()))
3916 : {
3917 7500157 : ENTRY_BLOCK_PTR_FOR_FN (cfun)->aux = (void *)(size_t) 1;
3918 7500157 : worklist.safe_push (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3919 :
3920 81078740 : while (worklist.length () > 0)
3921 : {
3922 66078426 : bb = worklist.pop ();
3923 147552726 : FOR_EACH_EDGE (e, ei, bb->succs)
3924 83198225 : if (!(e->count () == profile_count::zero ())
3925 98357680 : && !(e->dest->count == profile_count::zero ())
3926 74766638 : && !e->dest->aux)
3927 : {
3928 58578269 : e->dest->aux = (void *)(size_t) 1;
3929 58578269 : worklist.safe_push (e->dest);
3930 : }
3931 : }
3932 : }
3933 :
3934 77740428 : FOR_ALL_BB_FN (bb, cfun)
3935 : {
3936 70221188 : if (!bb->aux)
3937 : {
3938 8284848 : if (!(bb->count == profile_count::zero ())
3939 426966 : && (dump_file && (dump_flags & TDF_DETAILS)))
3940 676 : fprintf (dump_file,
3941 : "Basic block %i is marked unlikely by forward prop\n",
3942 : bb->index);
3943 4142762 : bb->count = profile_count::zero ();
3944 : }
3945 : else
3946 66078426 : bb->aux = NULL;
3947 : }
3948 7519240 : }
3949 :
3950 : /* Determine basic blocks/edges that are known to be unlikely executed and set
3951 : their counters to zero.
3952 : This is done with first identifying obviously unlikely BBs/edges and then
3953 : propagating in both directions. */
3954 :
3955 : static void
3956 6175091 : determine_unlikely_bbs ()
3957 : {
3958 6175091 : basic_block bb;
3959 6175091 : auto_vec<basic_block, 64> worklist;
3960 6175091 : edge_iterator ei;
3961 6175091 : edge e;
3962 :
3963 42021573 : FOR_EACH_BB_FN (bb, cfun)
3964 : {
3965 71278496 : if (!(bb->count == profile_count::zero ())
3966 33825372 : && unlikely_executed_bb_p (bb))
3967 : {
3968 414468 : if (dump_file && (dump_flags & TDF_DETAILS))
3969 0 : fprintf (dump_file, "Basic block %i is locally unlikely\n",
3970 : bb->index);
3971 414468 : bb->count = profile_count::zero ();
3972 : }
3973 :
3974 86276062 : FOR_EACH_EDGE (e, ei, bb->succs)
3975 94298624 : if (!(e->probability == profile_probability::never ())
3976 50429580 : && unlikely_executed_edge_p (e))
3977 : {
3978 2099571 : if (dump_file && (dump_flags & TDF_DETAILS))
3979 26 : fprintf (dump_file, "Edge %i->%i is locally unlikely\n",
3980 26 : bb->index, e->dest->index);
3981 2099571 : e->probability = profile_probability::never ();
3982 : }
3983 :
3984 35846482 : gcc_checking_assert (!bb->aux);
3985 : }
3986 6175091 : propagate_unlikely_bbs_forward ();
3987 :
3988 6175091 : auto_vec<int, 64> nsuccs;
3989 6175091 : nsuccs.safe_grow_cleared (last_basic_block_for_fn (cfun), true);
3990 54371755 : FOR_ALL_BB_FN (bb, cfun)
3991 57112007 : if (!(bb->count == profile_count::zero ())
3992 45348828 : && bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
3993 : {
3994 39281321 : nsuccs[bb->index] = 0;
3995 93460105 : FOR_EACH_EDGE (e, ei, bb->succs)
3996 54178784 : if (!(e->probability == profile_probability::never ())
3997 104596242 : && !(e->dest->count == profile_count::zero ()))
3998 49312824 : nsuccs[bb->index]++;
3999 39281321 : if (!nsuccs[bb->index])
4000 1563888 : worklist.safe_push (bb);
4001 : }
4002 7765606 : while (worklist.length () > 0)
4003 : {
4004 1590515 : bb = worklist.pop ();
4005 1590515 : if (bb->count == profile_count::zero ())
4006 0 : continue;
4007 1590515 : if (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun))
4008 : {
4009 1581526 : bool found = false;
4010 3163052 : for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
4011 2757531 : !gsi_end_p (gsi); gsi_next (&gsi))
4012 2727599 : if (stmt_can_terminate_bb_p (gsi_stmt (gsi))
4013 : /* stmt_can_terminate_bb_p special cases noreturns because it
4014 : assumes that fake edges are created. We want to know that
4015 : noreturn alone does not imply BB to be unlikely. */
4016 2727599 : || (is_gimple_call (gsi_stmt (gsi))
4017 640312 : && (gimple_call_flags (gsi_stmt (gsi)) & ECF_NORETURN)))
4018 : {
4019 : found = true;
4020 : break;
4021 : }
4022 1581526 : if (found)
4023 1551594 : continue;
4024 : }
4025 38921 : if (dump_file && (dump_flags & TDF_DETAILS))
4026 0 : fprintf (dump_file,
4027 : "Basic block %i is marked unlikely by backward prop\n",
4028 : bb->index);
4029 38921 : bb->count = profile_count::zero ();
4030 81833 : FOR_EACH_EDGE (e, ei, bb->preds)
4031 42912 : if (!(e->probability == profile_probability::never ()))
4032 : {
4033 41976 : if (!(e->src->count == profile_count::zero ()))
4034 : {
4035 41974 : gcc_checking_assert (nsuccs[e->src->index] > 0);
4036 41974 : nsuccs[e->src->index]--;
4037 41974 : if (!nsuccs[e->src->index])
4038 26627 : worklist.safe_push (e->src);
4039 : }
4040 : }
4041 : }
4042 : /* Finally all edges from non-0 regions to 0 are unlikely. */
4043 54371755 : FOR_ALL_BB_FN (bb, cfun)
4044 : {
4045 51083421 : if (!(bb->count == profile_count::zero ()))
4046 99433027 : FOR_EACH_EDGE (e, ei, bb->succs)
4047 54123120 : if (!(e->probability == profile_probability::never ())
4048 104461174 : && e->dest->count == profile_count::zero ())
4049 : {
4050 540092 : if (dump_file && (dump_flags & TDF_DETAILS))
4051 0 : fprintf (dump_file, "Edge %i->%i is unlikely because "
4052 : "it enters unlikely block\n",
4053 : bb->index, e->dest->index);
4054 540092 : e->probability = profile_probability::never ();
4055 : }
4056 :
4057 48196664 : edge other = NULL;
4058 :
4059 93168820 : FOR_EACH_EDGE (e, ei, bb->succs)
4060 56275601 : if (e->probability == profile_probability::never ())
4061 : ;
4062 49188750 : else if (other)
4063 : {
4064 : other = NULL;
4065 : break;
4066 : }
4067 : else
4068 : other = e;
4069 48196664 : if (other
4070 48196664 : && !(other->probability == profile_probability::always ()))
4071 : {
4072 8605029 : if (dump_file && (dump_flags & TDF_DETAILS))
4073 6 : fprintf (dump_file, "Edge %i->%i is locally likely\n",
4074 6 : bb->index, other->dest->index);
4075 8605029 : other->probability = profile_probability::always ();
4076 : }
4077 : }
4078 6175095 : if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count == profile_count::zero ())
4079 24481 : cgraph_node::get (current_function_decl)->count = profile_count::zero ();
4080 6175091 : }
4081 :
4082 : /* Estimate and propagate basic block frequencies using the given branch
4083 : probabilities. */
4084 :
4085 : static void
4086 2584833 : estimate_bb_frequencies ()
4087 : {
4088 2584833 : basic_block bb;
4089 2584833 : sreal freq_max;
4090 :
4091 2584833 : determine_unlikely_bbs ();
4092 :
4093 2584833 : mark_dfs_back_edges ();
4094 :
4095 2584833 : single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun))->probability =
4096 : profile_probability::always ();
4097 :
4098 : /* Set up block info for each basic block. */
4099 2584833 : alloc_aux_for_blocks (sizeof (block_info));
4100 2584833 : alloc_aux_for_edges (sizeof (edge_prob_info));
4101 22223875 : FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
4102 : {
4103 19639042 : edge e;
4104 19639042 : edge_iterator ei;
4105 :
4106 42877687 : FOR_EACH_EDGE (e, ei, bb->succs)
4107 : {
4108 : /* FIXME: Graphite is producing edges with no profile. Once
4109 : this is fixed, drop this. */
4110 23238645 : if (e->probability.initialized_p ())
4111 23238613 : EDGE_INFO (e)->back_edge_prob
4112 23238613 : = e->probability.to_sreal ();
4113 : else
4114 : /* back_edge_prob = 0.5 */
4115 32 : EDGE_INFO (e)->back_edge_prob = sreal (1, -1);
4116 : }
4117 : }
4118 :
4119 : /* First compute frequencies locally for each loop from innermost
4120 : to outermost to examine frequencies for back edges. */
4121 2584833 : estimate_loops ();
4122 :
4123 2584833 : freq_max = 0;
4124 17054209 : FOR_EACH_BB_FN (bb, cfun)
4125 14469376 : if (freq_max < BLOCK_INFO (bb)->frequency)
4126 3268100 : freq_max = BLOCK_INFO (bb)->frequency;
4127 :
4128 : /* Scaling frequencies up to maximal profile count may result in
4129 : frequent overflows especially when inlining loops.
4130 : Small scaling results in unnecessary precision loss. Stay in
4131 : the half of the (exponential) range. */
4132 2584833 : freq_max = (sreal (1) << (profile_count::n_bits / 2)) / freq_max;
4133 2584833 : if (freq_max < 16)
4134 74 : freq_max = 16;
4135 2584833 : profile_count ipa_count = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa ();
4136 2584833 : cfun->cfg->count_max = profile_count::uninitialized ();
4137 22223875 : FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
4138 : {
4139 19639042 : sreal tmp = BLOCK_INFO (bb)->frequency;
4140 19639042 : if (tmp >= 1)
4141 : {
4142 11638809 : gimple_stmt_iterator gsi;
4143 11638809 : tree decl;
4144 :
4145 : /* Self recursive calls can not have frequency greater than 1
4146 : or program will never terminate. This will result in an
4147 : inconsistent bb profile but it is better than greatly confusing
4148 : IPA cost metrics. */
4149 77956777 : for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4150 54684680 : if (is_gimple_call (gsi_stmt (gsi))
4151 3066441 : && (decl = gimple_call_fndecl (gsi_stmt (gsi))) != NULL
4152 57438087 : && recursive_call_p (current_function_decl, decl))
4153 : {
4154 5521 : if (dump_file)
4155 0 : fprintf (dump_file, "Dropping frequency of recursive call"
4156 : " in bb %i from %f\n", bb->index,
4157 : tmp.to_double ());
4158 5521 : tmp = (sreal)9 / (sreal)10;
4159 5521 : break;
4160 : }
4161 : }
4162 19639042 : tmp = tmp * freq_max;
4163 19639042 : profile_count count = profile_count::from_gcov_type (tmp.to_nearest_int ());
4164 :
4165 : /* If we have profile feedback in which this function was never
4166 : executed, then preserve this info. */
4167 20910419 : if (!(bb->count == profile_count::zero ()))
4168 18367665 : bb->count = count.guessed_local ().combine_with_ipa_count (ipa_count);
4169 19639042 : cfun->cfg->count_max
4170 19639042 : = profile_count::max_prefer_initialized (cfun->cfg->count_max,
4171 : bb->count);
4172 : }
4173 :
4174 2584833 : free_aux_for_blocks ();
4175 2584833 : free_aux_for_edges ();
4176 2584833 : compute_function_frequency ();
4177 2584833 : }
4178 :
4179 : /* Decide whether function is hot, cold or unlikely executed. */
4180 : void
4181 2615673 : compute_function_frequency (void)
4182 : {
4183 2615673 : basic_block bb;
4184 2615673 : struct cgraph_node *node = cgraph_node::get (current_function_decl);
4185 :
4186 2615673 : if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
4187 2615673 : || MAIN_NAME_P (DECL_NAME (current_function_decl)))
4188 96668 : node->only_called_at_startup = true;
4189 2615673 : if (DECL_STATIC_DESTRUCTOR (current_function_decl))
4190 1280 : node->only_called_at_exit = true;
4191 :
4192 2615673 : if (!ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa_p ())
4193 : {
4194 2606222 : int flags = flags_from_decl_or_type (current_function_decl);
4195 2606222 : if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
4196 : != NULL)
4197 781 : node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
4198 2605441 : else if (lookup_attribute ("hot", DECL_ATTRIBUTES (current_function_decl))
4199 : != NULL)
4200 60 : node->frequency = NODE_FREQUENCY_HOT;
4201 2605381 : else if (flags & ECF_NORETURN)
4202 2029 : node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
4203 2603352 : else if (MAIN_NAME_P (DECL_NAME (current_function_decl)))
4204 82973 : node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
4205 2520379 : else if (DECL_STATIC_CONSTRUCTOR (current_function_decl)
4206 2520379 : || DECL_STATIC_DESTRUCTOR (current_function_decl))
4207 14152 : node->frequency = NODE_FREQUENCY_EXECUTED_ONCE;
4208 : return;
4209 : }
4210 :
4211 9451 : node->frequency = NODE_FREQUENCY_UNLIKELY_EXECUTED;
4212 9451 : if (lookup_attribute ("cold", DECL_ATTRIBUTES (current_function_decl))
4213 : == NULL)
4214 9440 : warn_function_cold (current_function_decl);
4215 9451 : if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.ipa() == profile_count::zero ())
4216 9080 : return;
4217 967 : FOR_EACH_BB_FN (bb, cfun)
4218 : {
4219 852 : if (maybe_hot_bb_p (cfun, bb))
4220 : {
4221 256 : node->frequency = NODE_FREQUENCY_HOT;
4222 256 : return;
4223 : }
4224 596 : if (!probably_never_executed_bb_p (cfun, bb))
4225 542 : node->frequency = NODE_FREQUENCY_NORMAL;
4226 : }
4227 : }
4228 :
4229 : /* Build PREDICT_EXPR. */
4230 : tree
4231 2018283 : build_predict_expr (enum br_predictor predictor, enum prediction taken)
4232 : {
4233 2018283 : tree t = build1 (PREDICT_EXPR, void_type_node,
4234 2018283 : build_int_cst (integer_type_node, predictor));
4235 2018283 : SET_PREDICT_EXPR_OUTCOME (t, taken);
4236 2018283 : return t;
4237 : }
4238 :
4239 : const char *
4240 1311 : predictor_name (enum br_predictor predictor)
4241 : {
4242 1311 : return predictor_info[predictor].name;
4243 : }
4244 :
4245 : /* Predict branch probabilities and estimate profile of the tree CFG. */
4246 :
4247 : namespace {
4248 :
4249 : const pass_data pass_data_profile =
4250 : {
4251 : GIMPLE_PASS, /* type */
4252 : "profile_estimate", /* name */
4253 : OPTGROUP_NONE, /* optinfo_flags */
4254 : TV_BRANCH_PROB, /* tv_id */
4255 : PROP_cfg, /* properties_required */
4256 : 0, /* properties_provided */
4257 : 0, /* properties_destroyed */
4258 : 0, /* todo_flags_start */
4259 : 0, /* todo_flags_finish */
4260 : };
4261 :
4262 : class pass_profile : public gimple_opt_pass
4263 : {
4264 : public:
4265 302985 : pass_profile (gcc::context *ctxt)
4266 605970 : : gimple_opt_pass (pass_data_profile, ctxt)
4267 : {}
4268 :
4269 : /* opt_pass methods: */
4270 2527232 : bool gate (function *) final override { return flag_guess_branch_prob; }
4271 : unsigned int execute (function *) final override;
4272 :
4273 : }; // class pass_profile
4274 :
4275 : unsigned int
4276 2526120 : pass_profile::execute (function *fun)
4277 : {
4278 2526120 : unsigned nb_loops;
4279 :
4280 2526120 : if (profile_status_for_fn (cfun) == PROFILE_GUESSED)
4281 : return 0;
4282 :
4283 2526082 : loop_optimizer_init (LOOPS_NORMAL);
4284 2526082 : if (dump_file && (dump_flags & TDF_DETAILS))
4285 2 : flow_loops_dump (dump_file, NULL, 0);
4286 :
4287 2526082 : nb_loops = number_of_loops (fun);
4288 2526082 : if (nb_loops > 1)
4289 287028 : scev_initialize ();
4290 :
4291 2526082 : tree_estimate_probability (false);
4292 2526082 : cfun->cfg->full_profile = true;
4293 :
4294 2526082 : if (nb_loops > 1)
4295 287028 : scev_finalize ();
4296 :
4297 2526082 : loop_optimizer_finalize ();
4298 2526082 : if (dump_file && (dump_flags & TDF_DETAILS))
4299 2 : gimple_dump_cfg (dump_file, dump_flags);
4300 2526082 : if (profile_status_for_fn (fun) == PROFILE_ABSENT)
4301 2526082 : profile_status_for_fn (fun) = PROFILE_GUESSED;
4302 2526082 : if (dump_file && (dump_flags & TDF_DETAILS))
4303 : {
4304 2 : sreal iterations;
4305 7 : for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
4306 1 : if (expected_loop_iterations_by_profile (loop, &iterations))
4307 1 : fprintf (dump_file, "Loop %d got predicted to iterate %f times.\n",
4308 2 : loop->num, iterations.to_double ());
4309 : }
4310 : return 0;
4311 : }
4312 :
4313 : } // anon namespace
4314 :
4315 : gimple_opt_pass *
4316 302985 : make_pass_profile (gcc::context *ctxt)
4317 : {
4318 302985 : return new pass_profile (ctxt);
4319 : }
4320 :
4321 : /* Return true when PRED predictor should be removed after early
4322 : tree passes. Most of the predictors are beneficial to survive
4323 : as early inlining can also distribute then into caller's bodies. */
4324 :
4325 : static bool
4326 372285 : strip_predictor_early (enum br_predictor pred)
4327 : {
4328 0 : switch (pred)
4329 : {
4330 : case PRED_TREE_EARLY_RETURN:
4331 : return true;
4332 0 : default:
4333 0 : return false;
4334 : }
4335 : }
4336 :
4337 : /* Get rid of all builtin_expect calls and GIMPLE_PREDICT statements
4338 : we no longer need. EARLY is set to true when called from early
4339 : optimizations. */
4340 :
4341 : unsigned int
4342 3597650 : strip_predict_hints (function *fun, bool early)
4343 : {
4344 3597650 : basic_block bb;
4345 3597650 : gimple *ass_stmt;
4346 3597650 : tree var;
4347 3597650 : bool changed = false;
4348 :
4349 27592822 : FOR_EACH_BB_FN (bb, fun)
4350 : {
4351 23995172 : gimple_stmt_iterator bi;
4352 216186638 : for (bi = gsi_start_bb (bb); !gsi_end_p (bi);)
4353 : {
4354 168196294 : gimple *stmt = gsi_stmt (bi);
4355 :
4356 168196294 : if (gimple_code (stmt) == GIMPLE_PREDICT)
4357 : {
4358 1110616 : if (!early
4359 587711 : || strip_predictor_early (gimple_predict_predictor (stmt)))
4360 : {
4361 522905 : gsi_remove (&bi, true);
4362 522905 : changed = true;
4363 522905 : continue;
4364 : }
4365 : }
4366 167608583 : else if (is_gimple_call (stmt))
4367 : {
4368 12679544 : tree fndecl = gimple_call_fndecl (stmt);
4369 :
4370 12679544 : if (!early
4371 12679544 : && ((fndecl != NULL_TREE
4372 6074057 : && fndecl_built_in_p (fndecl, BUILT_IN_EXPECT)
4373 159969 : && gimple_call_num_args (stmt) == 2)
4374 : || (fndecl != NULL_TREE
4375 5914088 : && fndecl_built_in_p (fndecl,
4376 : BUILT_IN_EXPECT_WITH_PROBABILITY)
4377 22 : && gimple_call_num_args (stmt) == 3)
4378 6281380 : || (gimple_call_internal_p (stmt)
4379 184897 : && gimple_call_internal_fn (stmt) == IFN_BUILTIN_EXPECT)))
4380 : {
4381 195752 : var = gimple_call_lhs (stmt);
4382 195752 : changed = true;
4383 195752 : if (var)
4384 : {
4385 195751 : ass_stmt
4386 195751 : = gimple_build_assign (var, gimple_call_arg (stmt, 0));
4387 195751 : gsi_replace (&bi, ass_stmt, true);
4388 : }
4389 : else
4390 : {
4391 1 : gsi_remove (&bi, true);
4392 1 : continue;
4393 : }
4394 : }
4395 : }
4396 167673388 : gsi_next (&bi);
4397 : }
4398 : }
4399 3597650 : return changed ? TODO_cleanup_cfg : 0;
4400 : }
4401 :
4402 : namespace {
4403 :
4404 : const pass_data pass_data_strip_predict_hints =
4405 : {
4406 : GIMPLE_PASS, /* type */
4407 : "*strip_predict_hints", /* name */
4408 : OPTGROUP_NONE, /* optinfo_flags */
4409 : TV_BRANCH_PROB, /* tv_id */
4410 : PROP_cfg, /* properties_required */
4411 : 0, /* properties_provided */
4412 : 0, /* properties_destroyed */
4413 : 0, /* todo_flags_start */
4414 : 0, /* todo_flags_finish */
4415 : };
4416 :
4417 : class pass_strip_predict_hints : public gimple_opt_pass
4418 : {
4419 : public:
4420 908955 : pass_strip_predict_hints (gcc::context *ctxt)
4421 1817910 : : gimple_opt_pass (pass_data_strip_predict_hints, ctxt)
4422 : {}
4423 :
4424 : /* opt_pass methods: */
4425 605970 : opt_pass * clone () final override
4426 : {
4427 605970 : return new pass_strip_predict_hints (m_ctxt);
4428 : }
4429 908955 : void set_pass_param (unsigned int n, bool param) final override
4430 : {
4431 908955 : gcc_assert (n == 0);
4432 908955 : early_p = param;
4433 908955 : }
4434 :
4435 : unsigned int execute (function *) final override;
4436 :
4437 : private:
4438 : bool early_p;
4439 :
4440 : }; // class pass_strip_predict_hints
4441 :
4442 : unsigned int
4443 3597650 : pass_strip_predict_hints::execute (function *fun)
4444 : {
4445 3597650 : return strip_predict_hints (fun, early_p);
4446 : }
4447 :
4448 : } // anon namespace
4449 :
4450 : gimple_opt_pass *
4451 302985 : make_pass_strip_predict_hints (gcc::context *ctxt)
4452 : {
4453 302985 : return new pass_strip_predict_hints (ctxt);
4454 : }
4455 :
4456 : /* Rebuild function frequencies. Passes are in general expected to
4457 : maintain profile by hand, however in some cases this is not possible:
4458 : for example when inlining several functions with loops freuqencies might run
4459 : out of scale and thus needs to be recomputed. */
4460 :
4461 : void
4462 1122887 : rebuild_frequencies (void)
4463 : {
4464 : /* If we have no profile, do nothing. Note that after inlining
4465 : profile_status_for_fn may not represent the actual presence/absence of
4466 : profile. */
4467 1122887 : if (profile_status_for_fn (cfun) == PROFILE_ABSENT
4468 1122887 : && !ENTRY_BLOCK_PTR_FOR_FN (cfun)->count.initialized_p ())
4469 : return;
4470 :
4471 :
4472 : /* See if everything is OK and update count_max. */
4473 1122621 : basic_block bb;
4474 1122621 : bool inconsistency_found = false;
4475 1122621 : bool uninitialized_probablity_found = false;
4476 1122621 : bool uninitialized_count_found = false;
4477 1122621 : bool feedback_found = false;
4478 :
4479 1122621 : cfun->cfg->count_max = profile_count::uninitialized ();
4480 15681465 : FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL, next_bb)
4481 : {
4482 14558844 : cfun->cfg->count_max
4483 14558844 : = profile_count::max_prefer_initialized (cfun->cfg->count_max,
4484 : bb->count);
4485 27534229 : if (bb->count.nonzero_p () && bb->count.quality () >= AFDO)
4486 : feedback_found = true;
4487 : /* Uninitialized count may be result of inlining or an omission in an
4488 : optimization pass. */
4489 14558844 : if (!bb->count.initialized_p ())
4490 : {
4491 18 : uninitialized_count_found = true;
4492 18 : if (dump_file)
4493 0 : fprintf (dump_file, "BB %i has uninitialized count\n",
4494 : bb->index);
4495 : }
4496 14558844 : if (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun)
4497 : && (!uninitialized_probablity_found || !inconsistency_found))
4498 : {
4499 13436223 : profile_count sum = profile_count::zero ();
4500 13436223 : edge e;
4501 13436223 : edge_iterator ei;
4502 :
4503 31617635 : FOR_EACH_EDGE (e, ei, bb->preds)
4504 : {
4505 18181412 : sum += e->count ();
4506 : /* Uninitialized probability may be result of inlining or an
4507 : omission in an optimization pass. */
4508 18181412 : if (!e->probability.initialized_p ())
4509 : {
4510 36 : if (dump_file)
4511 0 : fprintf (dump_file,
4512 : "Edge %i->%i has uninitialized probability\n",
4513 0 : e->src->index, e->dest->index);
4514 : }
4515 : }
4516 13436223 : if (sum.differs_from_p (bb->count))
4517 : {
4518 185458 : if (dump_file)
4519 18 : fprintf (dump_file,
4520 : "BB %i has invalid sum of incoming counts\n",
4521 : bb->index);
4522 : inconsistency_found = true;
4523 : }
4524 : }
4525 : }
4526 :
4527 : /* If everything is OK, do not re-propagate frequencies. */
4528 1122621 : if (!inconsistency_found
4529 1064059 : && (!uninitialized_count_found || uninitialized_probablity_found)
4530 2186680 : && !cfun->cfg->count_max.very_large_p ())
4531 : {
4532 : /* Propagating zero counts should be safe and may
4533 : help hot/cold splitting. */
4534 1064014 : determine_unlikely_bbs ();
4535 1064014 : if (dump_file)
4536 31 : fprintf (dump_file, "Profile is consistent\n");
4537 : return;
4538 : }
4539 : /* Do not re-propagate if we have profile feedback. Even if the profile is
4540 : inconsistent from previous transformations, it is probably more realistic
4541 : for hot part of the program than result of repropagating.
4542 :
4543 : Consider example where we previously has
4544 :
4545 : if (test)
4546 : then [large probability for true]
4547 :
4548 : and we later proved that test is always 0. In this case, if profile was
4549 : read correctly, we must have duplicated the conditional (for example by
4550 : inlining) in to a context where test is false. From profile feedback
4551 : we know that most executions if the conditionals were true, so the
4552 : important copy is not the one we look on.
4553 :
4554 : Propagating from probabilities would make profile look consistent, but
4555 : because probabilities after code duplication may not be representative
4556 : for a given run, we would only propagate the error further. */
4557 58607 : if (feedback_found && !uninitialized_count_found)
4558 : {
4559 : /* Propagating zero counts should be safe and may
4560 : help hot/cold splitting. */
4561 9 : determine_unlikely_bbs ();
4562 9 : if (dump_file)
4563 0 : fprintf (dump_file,
4564 : "Profile is inconsistent but read from profile feedback;"
4565 : " not rebuilding\n");
4566 : return;
4567 : }
4568 :
4569 58598 : loop_optimizer_init (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS);
4570 58598 : connect_infinite_loops_to_exit ();
4571 58598 : estimate_bb_frequencies ();
4572 58598 : remove_fake_exit_edges ();
4573 58598 : loop_optimizer_finalize ();
4574 58598 : if (dump_file)
4575 5 : fprintf (dump_file, "Rebuilt basic block counts\n");
4576 :
4577 : return;
4578 : }
4579 :
4580 : namespace {
4581 :
4582 : const pass_data pass_data_rebuild_frequencies =
4583 : {
4584 : GIMPLE_PASS, /* type */
4585 : "rebuild_frequencies", /* name */
4586 : OPTGROUP_NONE, /* optinfo_flags */
4587 : TV_REBUILD_FREQUENCIES, /* tv_id */
4588 : PROP_cfg, /* properties_required */
4589 : 0, /* properties_provided */
4590 : 0, /* properties_destroyed */
4591 : 0, /* todo_flags_start */
4592 : 0, /* todo_flags_finish */
4593 : };
4594 :
4595 : class pass_rebuild_frequencies : public gimple_opt_pass
4596 : {
4597 : public:
4598 605970 : pass_rebuild_frequencies (gcc::context *ctxt)
4599 1211940 : : gimple_opt_pass (pass_data_rebuild_frequencies, ctxt)
4600 : {}
4601 :
4602 : /* opt_pass methods: */
4603 302985 : opt_pass * clone () final override
4604 : {
4605 302985 : return new pass_rebuild_frequencies (m_ctxt);
4606 : }
4607 0 : void set_pass_param (unsigned int n, bool param) final override
4608 : {
4609 0 : gcc_assert (n == 0);
4610 0 : early_p = param;
4611 0 : }
4612 :
4613 1070576 : unsigned int execute (function *) final override
4614 : {
4615 1070576 : rebuild_frequencies ();
4616 1070576 : return 0;
4617 : }
4618 :
4619 : private:
4620 : bool early_p;
4621 :
4622 : }; // class pass_rebuild_frequencies
4623 :
4624 : } // anon namespace
4625 :
4626 : gimple_opt_pass *
4627 302985 : make_pass_rebuild_frequencies (gcc::context *ctxt)
4628 : {
4629 302985 : return new pass_rebuild_frequencies (ctxt);
4630 : }
4631 :
4632 : /* Perform a dry run of the branch prediction pass and report comparison of
4633 : the predicted and real profile into the dump file. */
4634 :
4635 : void
4636 12 : report_predictor_hitrates (void)
4637 : {
4638 12 : unsigned nb_loops;
4639 :
4640 12 : loop_optimizer_init (LOOPS_NORMAL);
4641 12 : if (dump_file && (dump_flags & TDF_DETAILS))
4642 12 : flow_loops_dump (dump_file, NULL, 0);
4643 :
4644 12 : nb_loops = number_of_loops (cfun);
4645 12 : if (nb_loops > 1)
4646 5 : scev_initialize ();
4647 :
4648 12 : tree_estimate_probability (true);
4649 :
4650 12 : if (nb_loops > 1)
4651 5 : scev_finalize ();
4652 :
4653 12 : loop_optimizer_finalize ();
4654 12 : }
4655 :
4656 : /* Force edge E to be cold.
4657 : If IMPOSSIBLE is true, for edge to have count and probability 0 otherwise
4658 : keep low probability to represent possible error in a guess. This is used
4659 : i.e. in case we predict loop to likely iterate given number of times but
4660 : we are not 100% sure.
4661 :
4662 : This function locally updates profile without attempt to keep global
4663 : consistency which cannot be reached in full generality without full profile
4664 : rebuild from probabilities alone. Doing so is not necessarily a good idea
4665 : because frequencies and counts may be more realistic then probabilities.
4666 :
4667 : In some cases (such as for elimination of early exits during full loop
4668 : unrolling) the caller can ensure that profile will get consistent
4669 : afterwards. */
4670 :
4671 : void
4672 618943 : force_edge_cold (edge e, bool impossible)
4673 : {
4674 619000 : profile_count count_sum = profile_count::zero ();
4675 619000 : profile_probability prob_sum = profile_probability::never ();
4676 619000 : edge_iterator ei;
4677 619000 : edge e2;
4678 619000 : bool uninitialized_exit = false;
4679 :
4680 : /* When branch probability guesses are not known, then do nothing. */
4681 619381 : if (!impossible && !e->count ().initialized_p ())
4682 2689 : return;
4683 :
4684 619000 : profile_probability goal = (impossible ? profile_probability::never ()
4685 381 : : profile_probability::very_unlikely ());
4686 :
4687 : /* If edge is already improbably or cold, just return. */
4688 619000 : if (e->probability <= goal
4689 64019 : && (!impossible || e->count () == profile_count::zero ()))
4690 : return;
4691 1850911 : FOR_EACH_EDGE (e2, ei, e->src->succs)
4692 1233780 : if (e2 != e)
4693 : {
4694 616649 : if (e->flags & EDGE_FAKE)
4695 0 : continue;
4696 616649 : if (e2->count ().initialized_p ())
4697 616421 : count_sum += e2->count ();
4698 616649 : if (e2->probability.initialized_p ())
4699 616421 : prob_sum += e2->probability;
4700 : else
4701 : uninitialized_exit = true;
4702 : }
4703 :
4704 : /* If we are not guessing profiles but have some other edges out,
4705 : just assume the control flow goes elsewhere. */
4706 617131 : if (uninitialized_exit)
4707 228 : e->probability = goal;
4708 : /* If there are other edges out of e->src, redistribute probabilitity
4709 : there. */
4710 616903 : else if (prob_sum > profile_probability::never ())
4711 : {
4712 615720 : if (dump_file && (dump_flags & TDF_DETAILS))
4713 : {
4714 1007 : fprintf (dump_file, "Making edge %i->%i %s by redistributing "
4715 : "probability to other edges. Original probability: ",
4716 1007 : e->src->index, e->dest->index,
4717 : impossible ? "impossible" : "cold");
4718 1007 : e->probability.dump (dump_file);
4719 1007 : fprintf (dump_file, "\n");
4720 : }
4721 615720 : set_edge_probability_and_rescale_others (e, goal);
4722 615720 : if (current_ir_type () != IR_GIMPLE
4723 615720 : && e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
4724 151773 : update_br_prob_note (e->src);
4725 : }
4726 : /* If all edges out of e->src are unlikely, the basic block itself
4727 : is unlikely. */
4728 : else
4729 : {
4730 1183 : if (prob_sum == profile_probability::never ())
4731 906 : e->probability = profile_probability::always ();
4732 : else
4733 : {
4734 277 : if (impossible)
4735 277 : e->probability = profile_probability::never ();
4736 : /* If BB has some edges out that are not impossible, we cannot
4737 : assume that BB itself is. */
4738 : impossible = false;
4739 : }
4740 1183 : if (current_ir_type () != IR_GIMPLE
4741 1183 : && e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
4742 63 : update_br_prob_note (e->src);
4743 1183 : if (e->src->count == profile_count::zero ())
4744 144 : return;
4745 2078 : if (count_sum == profile_count::zero () && impossible)
4746 : {
4747 728 : bool found = false;
4748 728 : if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun))
4749 : ;
4750 698 : else if (current_ir_type () == IR_GIMPLE)
4751 1396 : for (gimple_stmt_iterator gsi = gsi_start_bb (e->src);
4752 2750 : !gsi_end_p (gsi); gsi_next (&gsi))
4753 : {
4754 2104 : if (stmt_can_terminate_bb_p (gsi_stmt (gsi)))
4755 : {
4756 : found = true;
4757 : break;
4758 : }
4759 : }
4760 : /* FIXME: Implement RTL path. */
4761 : else
4762 : found = true;
4763 698 : if (!found)
4764 : {
4765 676 : if (dump_file && (dump_flags & TDF_DETAILS))
4766 0 : fprintf (dump_file,
4767 : "Making bb %i impossible and dropping count to 0.\n",
4768 0 : e->src->index);
4769 676 : e->src->count = profile_count::zero ();
4770 1436 : FOR_EACH_EDGE (e2, ei, e->src->preds)
4771 760 : force_edge_cold (e2, impossible);
4772 : return;
4773 : }
4774 : }
4775 :
4776 : /* If we did not adjusting, the source basic block has no likely edeges
4777 : leaving other direction. In that case force that bb cold, too.
4778 : This in general is difficult task to do, but handle special case when
4779 : BB has only one predecestor. This is common case when we are updating
4780 : after loop transforms. */
4781 726 : if (!(prob_sum > profile_probability::never ())
4782 669 : && count_sum == profile_count::zero ()
4783 143 : && single_pred_p (e->src) && e->src->count.to_frequency (cfun)
4784 57 : > (impossible ? 0 : 1))
4785 : {
4786 57 : int old_frequency = e->src->count.to_frequency (cfun);
4787 57 : if (dump_file && (dump_flags & TDF_DETAILS))
4788 0 : fprintf (dump_file, "Making bb %i %s.\n", e->src->index,
4789 : impossible ? "impossible" : "cold");
4790 57 : int new_frequency = MIN (e->src->count.to_frequency (cfun),
4791 : impossible ? 0 : 1);
4792 0 : if (impossible)
4793 29 : e->src->count = profile_count::zero ();
4794 : else
4795 28 : e->src->count = e->count ().apply_scale (new_frequency,
4796 : old_frequency);
4797 57 : force_edge_cold (single_pred_edge (e->src), impossible);
4798 : }
4799 2 : else if (dump_file && (dump_flags & TDF_DETAILS)
4800 306 : && maybe_hot_bb_p (cfun, e->src))
4801 0 : fprintf (dump_file, "Giving up on making bb %i %s.\n", e->src->index,
4802 : impossible ? "impossible" : "cold");
4803 : }
4804 : }
4805 :
4806 : #if CHECKING_P
4807 :
4808 : namespace selftest {
4809 :
4810 : /* Test that value range of predictor values defined in predict.def is
4811 : within range (50, 100]. */
4812 :
4813 : struct branch_predictor
4814 : {
4815 : const char *name;
4816 : int probability;
4817 : };
4818 :
4819 : #define DEF_PREDICTOR(ENUM, NAME, HITRATE, FLAGS) { NAME, HITRATE },
4820 :
4821 : static void
4822 4 : test_prediction_value_range ()
4823 : {
4824 4 : branch_predictor predictors[] = {
4825 : #include "predict.def"
4826 : { NULL, PROB_UNINITIALIZED }
4827 : };
4828 :
4829 216 : for (unsigned i = 0; predictors[i].name != NULL; i++)
4830 : {
4831 212 : if (predictors[i].probability == PROB_UNINITIALIZED)
4832 28 : continue;
4833 :
4834 184 : unsigned p = 100 * predictors[i].probability / REG_BR_PROB_BASE;
4835 212 : ASSERT_TRUE (p >= 50 && p <= 100);
4836 : }
4837 4 : }
4838 :
4839 : #undef DEF_PREDICTOR
4840 :
4841 : /* Run all of the selfests within this file. */
4842 :
4843 : void
4844 4 : predict_cc_tests ()
4845 : {
4846 4 : test_prediction_value_range ();
4847 4 : }
4848 :
4849 : } // namespace selftest
4850 : #endif /* CHECKING_P. */
|