]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-cfgcleanup.c
* asan.c (create_cond_insert_point): Do not update edge count.
[thirdparty/gcc.git] / gcc / tree-cfgcleanup.c
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2017 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
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "diagnostic-core.h"
31 #include "fold-const.h"
32 #include "cfganal.h"
33 #include "cfgcleanup.h"
34 #include "tree-eh.h"
35 #include "gimplify.h"
36 #include "gimple-iterator.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-manip.h"
39 #include "tree-dfa.h"
40 #include "tree-ssa.h"
41 #include "cfgloop.h"
42 #include "tree-scalar-evolution.h"
43 #include "gimple-match.h"
44 #include "gimple-fold.h"
45 #include "tree-ssa-loop-niter.h"
46
47
48 /* The set of blocks in that at least one of the following changes happened:
49 -- the statement at the end of the block was changed
50 -- the block was newly created
51 -- the set of the predecessors of the block changed
52 -- the set of the successors of the block changed
53 ??? Maybe we could track these changes separately, since they determine
54 what cleanups it makes sense to try on the block. */
55 bitmap cfgcleanup_altered_bbs;
56
57 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
58
59 static bool
60 remove_fallthru_edge (vec<edge, va_gc> *ev)
61 {
62 edge_iterator ei;
63 edge e;
64
65 FOR_EACH_EDGE (e, ei, ev)
66 if ((e->flags & EDGE_FALLTHRU) != 0)
67 {
68 if (e->flags & EDGE_COMPLEX)
69 e->flags &= ~EDGE_FALLTHRU;
70 else
71 remove_edge_and_dominated_blocks (e);
72 return true;
73 }
74 return false;
75 }
76
77 /* Convert a SWTCH with single non-default case to gcond and replace it
78 at GSI. */
79
80 static bool
81 convert_single_case_switch (gswitch *swtch, gimple_stmt_iterator &gsi)
82 {
83 if (gimple_switch_num_labels (swtch) != 2)
84 return false;
85
86 tree index = gimple_switch_index (swtch);
87 tree default_label = CASE_LABEL (gimple_switch_default_label (swtch));
88 tree label = gimple_switch_label (swtch, 1);
89 tree low = CASE_LOW (label);
90 tree high = CASE_HIGH (label);
91
92 basic_block default_bb = label_to_block_fn (cfun, default_label);
93 basic_block case_bb = label_to_block_fn (cfun, CASE_LABEL (label));
94
95 basic_block bb = gimple_bb (swtch);
96 gcond *cond;
97
98 /* Replace switch statement with condition statement. */
99 if (high)
100 {
101 tree lhs, rhs;
102 generate_range_test (bb, index, low, high, &lhs, &rhs);
103 cond = gimple_build_cond (LE_EXPR, lhs, rhs, NULL_TREE, NULL_TREE);
104 }
105 else
106 cond = gimple_build_cond (EQ_EXPR, index,
107 fold_convert (TREE_TYPE (index), low),
108 NULL_TREE, NULL_TREE);
109
110 gsi_replace (&gsi, cond, true);
111
112 /* Update edges. */
113 edge case_edge = find_edge (bb, case_bb);
114 edge default_edge = find_edge (bb, default_bb);
115
116 case_edge->flags |= EDGE_TRUE_VALUE;
117 default_edge->flags |= EDGE_FALSE_VALUE;
118 return true;
119 }
120
121 /* Disconnect an unreachable block in the control expression starting
122 at block BB. */
123
124 static bool
125 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi,
126 bool first_p)
127 {
128 edge taken_edge;
129 bool retval = false;
130 gimple *stmt = gsi_stmt (gsi);
131
132 if (!single_succ_p (bb))
133 {
134 edge e;
135 edge_iterator ei;
136 bool warned;
137 tree val = NULL_TREE;
138
139 /* Try to convert a switch with just a single non-default case to
140 GIMPLE condition. */
141 if (gimple_code (stmt) == GIMPLE_SWITCH
142 && convert_single_case_switch (as_a<gswitch *> (stmt), gsi))
143 stmt = gsi_stmt (gsi);
144
145 fold_defer_overflow_warnings ();
146 switch (gimple_code (stmt))
147 {
148 case GIMPLE_COND:
149 /* During a first iteration on the CFG only remove trivially
150 dead edges but mark other conditions for re-evaluation. */
151 if (first_p)
152 {
153 val = const_binop (gimple_cond_code (stmt), boolean_type_node,
154 gimple_cond_lhs (stmt),
155 gimple_cond_rhs (stmt));
156 if (! val)
157 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
158 }
159 else
160 {
161 code_helper rcode;
162 tree ops[3] = {};
163 if (gimple_simplify (stmt, &rcode, ops, NULL, no_follow_ssa_edges,
164 no_follow_ssa_edges)
165 && rcode == INTEGER_CST)
166 val = ops[0];
167 }
168 break;
169
170 case GIMPLE_SWITCH:
171 val = gimple_switch_index (as_a <gswitch *> (stmt));
172 break;
173
174 default:
175 ;
176 }
177 taken_edge = find_taken_edge (bb, val);
178 if (!taken_edge)
179 {
180 fold_undefer_and_ignore_overflow_warnings ();
181 return false;
182 }
183
184 /* Remove all the edges except the one that is always executed. */
185 warned = false;
186 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
187 {
188 if (e != taken_edge)
189 {
190 if (!warned)
191 {
192 fold_undefer_overflow_warnings
193 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
194 warned = true;
195 }
196
197 taken_edge->probability += e->probability;
198 remove_edge_and_dominated_blocks (e);
199 retval = true;
200 }
201 else
202 ei_next (&ei);
203 }
204 if (!warned)
205 fold_undefer_and_ignore_overflow_warnings ();
206 }
207 else
208 taken_edge = single_succ_edge (bb);
209
210 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
211 gsi_remove (&gsi, true);
212 taken_edge->flags = EDGE_FALLTHRU;
213
214 return retval;
215 }
216
217 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
218 to updated gimple_call_flags. */
219
220 static void
221 cleanup_call_ctrl_altering_flag (gimple *bb_end)
222 {
223 if (!is_gimple_call (bb_end)
224 || !gimple_call_ctrl_altering_p (bb_end))
225 return;
226
227 int flags = gimple_call_flags (bb_end);
228 if (((flags & (ECF_CONST | ECF_PURE))
229 && !(flags & ECF_LOOPING_CONST_OR_PURE))
230 || (flags & ECF_LEAF))
231 gimple_call_set_ctrl_altering (bb_end, false);
232 }
233
234 /* Try to remove superfluous control structures in basic block BB. Returns
235 true if anything changes. */
236
237 static bool
238 cleanup_control_flow_bb (basic_block bb, bool first_p)
239 {
240 gimple_stmt_iterator gsi;
241 bool retval = false;
242 gimple *stmt;
243
244 /* If the last statement of the block could throw and now cannot,
245 we need to prune cfg. */
246 retval |= gimple_purge_dead_eh_edges (bb);
247
248 gsi = gsi_last_nondebug_bb (bb);
249 if (gsi_end_p (gsi))
250 return retval;
251
252 stmt = gsi_stmt (gsi);
253
254 /* Try to cleanup ctrl altering flag for call which ends bb. */
255 cleanup_call_ctrl_altering_flag (stmt);
256
257 if (gimple_code (stmt) == GIMPLE_COND
258 || gimple_code (stmt) == GIMPLE_SWITCH)
259 {
260 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
261 retval |= cleanup_control_expr_graph (bb, gsi, first_p);
262 }
263 else if (gimple_code (stmt) == GIMPLE_GOTO
264 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
265 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
266 == LABEL_DECL))
267 {
268 /* If we had a computed goto which has a compile-time determinable
269 destination, then we can eliminate the goto. */
270 edge e;
271 tree label;
272 edge_iterator ei;
273 basic_block target_block;
274
275 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
276 /* First look at all the outgoing edges. Delete any outgoing
277 edges which do not go to the right block. For the one
278 edge which goes to the right block, fix up its flags. */
279 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
280 if (DECL_CONTEXT (label) != cfun->decl)
281 return retval;
282 target_block = label_to_block (label);
283 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
284 {
285 if (e->dest != target_block)
286 remove_edge_and_dominated_blocks (e);
287 else
288 {
289 /* Turn off the EDGE_ABNORMAL flag. */
290 e->flags &= ~EDGE_ABNORMAL;
291
292 /* And set EDGE_FALLTHRU. */
293 e->flags |= EDGE_FALLTHRU;
294 ei_next (&ei);
295 }
296 }
297
298 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
299 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
300
301 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
302 relevant information we need. */
303 gsi_remove (&gsi, true);
304 retval = true;
305 }
306
307 /* Check for indirect calls that have been turned into
308 noreturn calls. */
309 else if (is_gimple_call (stmt)
310 && gimple_call_noreturn_p (stmt))
311 {
312 /* If there are debug stmts after the noreturn call, remove them
313 now, they should be all unreachable anyway. */
314 for (gsi_next (&gsi); !gsi_end_p (gsi); )
315 gsi_remove (&gsi, true);
316 if (remove_fallthru_edge (bb->succs))
317 retval = true;
318 }
319
320 return retval;
321 }
322
323 /* Return true if basic block BB does nothing except pass control
324 flow to another block and that we can safely insert a label at
325 the start of the successor block.
326
327 As a precondition, we require that BB be not equal to
328 the entry block. */
329
330 static bool
331 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
332 {
333 gimple_stmt_iterator gsi;
334 location_t locus;
335
336 /* BB must have a single outgoing edge. */
337 if (single_succ_p (bb) != 1
338 /* If PHI_WANTED is false, BB must not have any PHI nodes.
339 Otherwise, BB must have PHI nodes. */
340 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
341 /* BB may not be a predecessor of the exit block. */
342 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
343 /* Nor should this be an infinite loop. */
344 || single_succ (bb) == bb
345 /* BB may not have an abnormal outgoing edge. */
346 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
347 return false;
348
349 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
350
351 locus = single_succ_edge (bb)->goto_locus;
352
353 /* There should not be an edge coming from entry, or an EH edge. */
354 {
355 edge_iterator ei;
356 edge e;
357
358 FOR_EACH_EDGE (e, ei, bb->preds)
359 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
360 return false;
361 /* If goto_locus of any of the edges differs, prevent removing
362 the forwarder block for -O0. */
363 else if (optimize == 0 && e->goto_locus != locus)
364 return false;
365 }
366
367 /* Now walk through the statements backward. We can ignore labels,
368 anything else means this is not a forwarder block. */
369 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
370 {
371 gimple *stmt = gsi_stmt (gsi);
372
373 switch (gimple_code (stmt))
374 {
375 case GIMPLE_LABEL:
376 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
377 return false;
378 if (optimize == 0 && gimple_location (stmt) != locus)
379 return false;
380 break;
381
382 /* ??? For now, hope there's a corresponding debug
383 assignment at the destination. */
384 case GIMPLE_DEBUG:
385 break;
386
387 default:
388 return false;
389 }
390 }
391
392 if (current_loops)
393 {
394 basic_block dest;
395 /* Protect loop headers. */
396 if (bb_loop_header_p (bb))
397 return false;
398
399 dest = EDGE_SUCC (bb, 0)->dest;
400 /* Protect loop preheaders and latches if requested. */
401 if (dest->loop_father->header == dest)
402 {
403 if (bb->loop_father == dest->loop_father)
404 {
405 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
406 return false;
407 /* If bb doesn't have a single predecessor we'd make this
408 loop have multiple latches. Don't do that if that
409 would in turn require disambiguating them. */
410 return (single_pred_p (bb)
411 || loops_state_satisfies_p
412 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
413 }
414 else if (bb->loop_father == loop_outer (dest->loop_father))
415 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
416 /* Always preserve other edges into loop headers that are
417 not simple latches or preheaders. */
418 return false;
419 }
420 }
421
422 return true;
423 }
424
425 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
426 those alternatives are equal in each of the PHI nodes, then return
427 true, else return false. */
428
429 static bool
430 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
431 {
432 int n1 = e1->dest_idx;
433 int n2 = e2->dest_idx;
434 gphi_iterator gsi;
435
436 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
437 {
438 gphi *phi = gsi.phi ();
439 tree val1 = gimple_phi_arg_def (phi, n1);
440 tree val2 = gimple_phi_arg_def (phi, n2);
441
442 gcc_assert (val1 != NULL_TREE);
443 gcc_assert (val2 != NULL_TREE);
444
445 if (!operand_equal_for_phi_arg_p (val1, val2))
446 return false;
447 }
448
449 return true;
450 }
451
452 /* Removes forwarder block BB. Returns false if this failed. */
453
454 static bool
455 remove_forwarder_block (basic_block bb)
456 {
457 edge succ = single_succ_edge (bb), e, s;
458 basic_block dest = succ->dest;
459 gimple *label;
460 edge_iterator ei;
461 gimple_stmt_iterator gsi, gsi_to;
462 bool can_move_debug_stmts;
463
464 /* We check for infinite loops already in tree_forwarder_block_p.
465 However it may happen that the infinite loop is created
466 afterwards due to removal of forwarders. */
467 if (dest == bb)
468 return false;
469
470 /* If the destination block consists of a nonlocal label or is a
471 EH landing pad, do not merge it. */
472 label = first_stmt (dest);
473 if (label)
474 if (glabel *label_stmt = dyn_cast <glabel *> (label))
475 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
476 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
477 return false;
478
479 /* If there is an abnormal edge to basic block BB, but not into
480 dest, problems might occur during removal of the phi node at out
481 of ssa due to overlapping live ranges of registers.
482
483 If there is an abnormal edge in DEST, the problems would occur
484 anyway since cleanup_dead_labels would then merge the labels for
485 two different eh regions, and rest of exception handling code
486 does not like it.
487
488 So if there is an abnormal edge to BB, proceed only if there is
489 no abnormal edge to DEST and there are no phi nodes in DEST. */
490 if (bb_has_abnormal_pred (bb)
491 && (bb_has_abnormal_pred (dest)
492 || !gimple_seq_empty_p (phi_nodes (dest))))
493 return false;
494
495 /* If there are phi nodes in DEST, and some of the blocks that are
496 predecessors of BB are also predecessors of DEST, check that the
497 phi node arguments match. */
498 if (!gimple_seq_empty_p (phi_nodes (dest)))
499 {
500 FOR_EACH_EDGE (e, ei, bb->preds)
501 {
502 s = find_edge (e->src, dest);
503 if (!s)
504 continue;
505
506 if (!phi_alternatives_equal (dest, succ, s))
507 return false;
508 }
509 }
510
511 can_move_debug_stmts = MAY_HAVE_DEBUG_STMTS && single_pred_p (dest);
512
513 basic_block pred = NULL;
514 if (single_pred_p (bb))
515 pred = single_pred (bb);
516
517 /* Redirect the edges. */
518 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
519 {
520 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
521
522 if (e->flags & EDGE_ABNORMAL)
523 {
524 /* If there is an abnormal edge, redirect it anyway, and
525 move the labels to the new block to make it legal. */
526 s = redirect_edge_succ_nodup (e, dest);
527 }
528 else
529 s = redirect_edge_and_branch (e, dest);
530
531 if (s == e)
532 {
533 /* Create arguments for the phi nodes, since the edge was not
534 here before. */
535 for (gphi_iterator psi = gsi_start_phis (dest);
536 !gsi_end_p (psi);
537 gsi_next (&psi))
538 {
539 gphi *phi = psi.phi ();
540 source_location l = gimple_phi_arg_location_from_edge (phi, succ);
541 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
542 add_phi_arg (phi, unshare_expr (def), s, l);
543 }
544 }
545 }
546
547 /* Move nonlocal labels and computed goto targets as well as user
548 defined labels and labels with an EH landing pad number to the
549 new block, so that the redirection of the abnormal edges works,
550 jump targets end up in a sane place and debug information for
551 labels is retained. */
552 gsi_to = gsi_start_bb (dest);
553 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
554 {
555 tree decl;
556 label = gsi_stmt (gsi);
557 if (is_gimple_debug (label))
558 break;
559 decl = gimple_label_label (as_a <glabel *> (label));
560 if (EH_LANDING_PAD_NR (decl) != 0
561 || DECL_NONLOCAL (decl)
562 || FORCED_LABEL (decl)
563 || !DECL_ARTIFICIAL (decl))
564 {
565 gsi_remove (&gsi, false);
566 gsi_insert_before (&gsi_to, label, GSI_SAME_STMT);
567 }
568 else
569 gsi_next (&gsi);
570 }
571
572 /* Move debug statements if the destination has a single predecessor. */
573 if (can_move_debug_stmts)
574 {
575 gsi_to = gsi_after_labels (dest);
576 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); )
577 {
578 gimple *debug = gsi_stmt (gsi);
579 if (!is_gimple_debug (debug))
580 break;
581 gsi_remove (&gsi, false);
582 gsi_insert_before (&gsi_to, debug, GSI_SAME_STMT);
583 }
584 }
585
586 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
587
588 /* Update the dominators. */
589 if (dom_info_available_p (CDI_DOMINATORS))
590 {
591 basic_block dom, dombb, domdest;
592
593 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
594 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
595 if (domdest == bb)
596 {
597 /* Shortcut to avoid calling (relatively expensive)
598 nearest_common_dominator unless necessary. */
599 dom = dombb;
600 }
601 else
602 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
603
604 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
605 }
606
607 /* Adjust latch infomation of BB's parent loop as otherwise
608 the cfg hook has a hard time not to kill the loop. */
609 if (current_loops && bb->loop_father->latch == bb)
610 bb->loop_father->latch = pred;
611
612 /* And kill the forwarder block. */
613 delete_basic_block (bb);
614
615 return true;
616 }
617
618 /* STMT is a call that has been discovered noreturn. Split the
619 block to prepare fixing up the CFG and remove LHS.
620 Return true if cleanup-cfg needs to run. */
621
622 bool
623 fixup_noreturn_call (gimple *stmt)
624 {
625 basic_block bb = gimple_bb (stmt);
626 bool changed = false;
627
628 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
629 return false;
630
631 /* First split basic block if stmt is not last. */
632 if (stmt != gsi_stmt (gsi_last_bb (bb)))
633 {
634 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
635 {
636 /* Don't split if there are only debug stmts
637 after stmt, that can result in -fcompare-debug
638 failures. Remove the debug stmts instead,
639 they should be all unreachable anyway. */
640 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
641 for (gsi_next (&gsi); !gsi_end_p (gsi); )
642 gsi_remove (&gsi, true);
643 }
644 else
645 {
646 split_block (bb, stmt);
647 changed = true;
648 }
649 }
650
651 /* If there is an LHS, remove it, but only if its type has fixed size.
652 The LHS will need to be recreated during RTL expansion and creating
653 temporaries of variable-sized types is not supported. Also don't
654 do this with TREE_ADDRESSABLE types, as assign_temp will abort.
655 Drop LHS regardless of TREE_ADDRESSABLE, if the function call
656 has been changed into a call that does not return a value, like
657 __builtin_unreachable or __cxa_pure_virtual. */
658 tree lhs = gimple_call_lhs (stmt);
659 if (lhs
660 && (should_remove_lhs_p (lhs)
661 || VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))))
662 {
663 gimple_call_set_lhs (stmt, NULL_TREE);
664
665 /* We need to fix up the SSA name to avoid checking errors. */
666 if (TREE_CODE (lhs) == SSA_NAME)
667 {
668 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
669 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
670 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
671 set_ssa_default_def (cfun, new_var, lhs);
672 }
673
674 update_stmt (stmt);
675 }
676
677 /* Mark the call as altering control flow. */
678 if (!gimple_call_ctrl_altering_p (stmt))
679 {
680 gimple_call_set_ctrl_altering (stmt, true);
681 changed = true;
682 }
683
684 return changed;
685 }
686
687 /* Return true if we want to merge BB1 and BB2 into a single block. */
688
689 static bool
690 want_merge_blocks_p (basic_block bb1, basic_block bb2)
691 {
692 if (!can_merge_blocks_p (bb1, bb2))
693 return false;
694 gimple_stmt_iterator gsi = gsi_last_nondebug_bb (bb1);
695 if (gsi_end_p (gsi) || !stmt_can_terminate_bb_p (gsi_stmt (gsi)))
696 return true;
697 return bb1->count.ok_for_merging (bb2->count);
698 }
699
700
701 /* Tries to cleanup cfg in basic block BB. Returns true if anything
702 changes. */
703
704 static bool
705 cleanup_tree_cfg_bb (basic_block bb)
706 {
707 if (tree_forwarder_block_p (bb, false)
708 && remove_forwarder_block (bb))
709 return true;
710
711 /* If there is a merge opportunity with the predecessor
712 do nothing now but wait until we process the predecessor.
713 This happens when we visit BBs in a non-optimal order and
714 avoids quadratic behavior with adjusting stmts BB pointer. */
715 if (single_pred_p (bb)
716 && want_merge_blocks_p (single_pred (bb), bb))
717 /* But make sure we _do_ visit it. When we remove unreachable paths
718 ending in a backedge we fail to mark the destinations predecessors
719 as changed. */
720 bitmap_set_bit (cfgcleanup_altered_bbs, single_pred (bb)->index);
721
722 /* Merging the blocks may create new opportunities for folding
723 conditional branches (due to the elimination of single-valued PHI
724 nodes). */
725 else if (single_succ_p (bb)
726 && want_merge_blocks_p (bb, single_succ (bb)))
727 {
728 merge_blocks (bb, single_succ (bb));
729 return true;
730 }
731
732 return false;
733 }
734
735 /* Iterate the cfg cleanups, while anything changes. */
736
737 static bool
738 cleanup_tree_cfg_1 (void)
739 {
740 bool retval = false;
741 basic_block bb;
742 unsigned i, n;
743
744 /* Prepare the worklists of altered blocks. */
745 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
746
747 /* During forwarder block cleanup, we may redirect edges out of
748 SWITCH_EXPRs, which can get expensive. So we want to enable
749 recording of edge to CASE_LABEL_EXPR. */
750 start_recording_case_labels ();
751
752 /* We cannot use FOR_EACH_BB_FN for the BB iterations below
753 since the basic blocks may get removed. */
754
755 /* Start by iterating over all basic blocks looking for edge removal
756 opportunities. Do this first because incoming SSA form may be
757 invalid and we want to avoid performing SSA related tasks such
758 as propgating out a PHI node during BB merging in that state. */
759 n = last_basic_block_for_fn (cfun);
760 for (i = NUM_FIXED_BLOCKS; i < n; i++)
761 {
762 bb = BASIC_BLOCK_FOR_FN (cfun, i);
763 if (bb)
764 retval |= cleanup_control_flow_bb (bb, true);
765 }
766
767 /* After doing the above SSA form should be valid (or an update SSA
768 should be required). */
769
770 /* Continue by iterating over all basic blocks looking for BB merging
771 opportunities. */
772 n = last_basic_block_for_fn (cfun);
773 for (i = NUM_FIXED_BLOCKS; i < n; i++)
774 {
775 bb = BASIC_BLOCK_FOR_FN (cfun, i);
776 if (bb)
777 retval |= cleanup_tree_cfg_bb (bb);
778 }
779
780 /* Now process the altered blocks, as long as any are available. */
781 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
782 {
783 i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
784 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
785 if (i < NUM_FIXED_BLOCKS)
786 continue;
787
788 bb = BASIC_BLOCK_FOR_FN (cfun, i);
789 if (!bb)
790 continue;
791
792 retval |= cleanup_control_flow_bb (bb, false);
793 retval |= cleanup_tree_cfg_bb (bb);
794 }
795
796 end_recording_case_labels ();
797 BITMAP_FREE (cfgcleanup_altered_bbs);
798 return retval;
799 }
800
801 static bool
802 mfb_keep_latches (edge e)
803 {
804 return ! dominated_by_p (CDI_DOMINATORS, e->src, e->dest);
805 }
806
807 /* Remove unreachable blocks and other miscellaneous clean up work.
808 Return true if the flowgraph was modified, false otherwise. */
809
810 static bool
811 cleanup_tree_cfg_noloop (void)
812 {
813 bool changed;
814
815 timevar_push (TV_TREE_CLEANUP_CFG);
816
817 /* Iterate until there are no more cleanups left to do. If any
818 iteration changed the flowgraph, set CHANGED to true.
819
820 If dominance information is available, there cannot be any unreachable
821 blocks. */
822 if (!dom_info_available_p (CDI_DOMINATORS))
823 {
824 changed = delete_unreachable_blocks ();
825 calculate_dominance_info (CDI_DOMINATORS);
826 }
827 else
828 {
829 checking_verify_dominators (CDI_DOMINATORS);
830 changed = false;
831 }
832
833 /* Ensure that we have single entries into loop headers. Otherwise
834 if one of the entries is becoming a latch due to CFG cleanup
835 (from formerly being part of an irreducible region) then we mess
836 up loop fixup and associate the old loop with a different region
837 which makes niter upper bounds invalid. See for example PR80549.
838 This needs to be done before we remove trivially dead edges as
839 we need to capture the dominance state before the pending transform. */
840 if (current_loops)
841 {
842 loop_p loop;
843 unsigned i;
844 FOR_EACH_VEC_ELT (*get_loops (cfun), i, loop)
845 if (loop && loop->header)
846 {
847 basic_block bb = loop->header;
848 edge_iterator ei;
849 edge e;
850 bool found_latch = false;
851 bool any_abnormal = false;
852 unsigned n = 0;
853 /* We are only interested in preserving existing loops, but
854 we need to check whether they are still real and of course
855 if we need to add a preheader at all. */
856 FOR_EACH_EDGE (e, ei, bb->preds)
857 {
858 if (e->flags & EDGE_ABNORMAL)
859 {
860 any_abnormal = true;
861 break;
862 }
863 if (dominated_by_p (CDI_DOMINATORS, e->src, bb))
864 {
865 found_latch = true;
866 continue;
867 }
868 n++;
869 }
870 /* If we have more than one entry to the loop header
871 create a forwarder. */
872 if (found_latch && ! any_abnormal && n > 1)
873 {
874 edge fallthru = make_forwarder_block (bb, mfb_keep_latches,
875 NULL);
876 loop->header = fallthru->dest;
877 if (! loops_state_satisfies_p (LOOPS_NEED_FIXUP))
878 {
879 /* The loop updating from the CFG hook is incomplete
880 when we have multiple latches, fixup manually. */
881 remove_bb_from_loops (fallthru->src);
882 loop_p cloop = loop;
883 FOR_EACH_EDGE (e, ei, fallthru->src->preds)
884 cloop = find_common_loop (cloop, e->src->loop_father);
885 add_bb_to_loop (fallthru->src, cloop);
886 }
887 }
888 }
889 }
890
891 changed |= cleanup_tree_cfg_1 ();
892
893 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
894
895 /* Do not renumber blocks if the SCEV cache is active, it is indexed by
896 basic-block numbers. */
897 if (! scev_initialized_p ())
898 compact_blocks ();
899
900 checking_verify_flow_info ();
901
902 timevar_pop (TV_TREE_CLEANUP_CFG);
903
904 if (changed && current_loops)
905 {
906 /* Removing edges and/or blocks may make recorded bounds refer
907 to stale GIMPLE stmts now, so clear them. */
908 free_numbers_of_iterations_estimates (cfun);
909 loops_state_set (LOOPS_NEED_FIXUP);
910 }
911
912 return changed;
913 }
914
915 /* Repairs loop structures. */
916
917 static void
918 repair_loop_structures (void)
919 {
920 bitmap changed_bbs;
921 unsigned n_new_loops;
922
923 calculate_dominance_info (CDI_DOMINATORS);
924
925 timevar_push (TV_REPAIR_LOOPS);
926 changed_bbs = BITMAP_ALLOC (NULL);
927 n_new_loops = fix_loop_structure (changed_bbs);
928
929 /* This usually does nothing. But sometimes parts of cfg that originally
930 were inside a loop get out of it due to edge removal (since they
931 become unreachable by back edges from latch). Also a former
932 irreducible loop can become reducible - in this case force a full
933 rewrite into loop-closed SSA form. */
934 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
935 rewrite_into_loop_closed_ssa (n_new_loops ? NULL : changed_bbs,
936 TODO_update_ssa);
937
938 BITMAP_FREE (changed_bbs);
939
940 checking_verify_loop_structure ();
941 scev_reset ();
942
943 timevar_pop (TV_REPAIR_LOOPS);
944 }
945
946 /* Cleanup cfg and repair loop structures. */
947
948 bool
949 cleanup_tree_cfg (void)
950 {
951 bool changed = cleanup_tree_cfg_noloop ();
952
953 if (current_loops != NULL
954 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
955 repair_loop_structures ();
956
957 return changed;
958 }
959
960 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
961 Returns true if successful. */
962
963 static bool
964 remove_forwarder_block_with_phi (basic_block bb)
965 {
966 edge succ = single_succ_edge (bb);
967 basic_block dest = succ->dest;
968 gimple *label;
969 basic_block dombb, domdest, dom;
970
971 /* We check for infinite loops already in tree_forwarder_block_p.
972 However it may happen that the infinite loop is created
973 afterwards due to removal of forwarders. */
974 if (dest == bb)
975 return false;
976
977 /* Removal of forwarders may expose new natural loops and thus
978 a block may turn into a loop header. */
979 if (current_loops && bb_loop_header_p (bb))
980 return false;
981
982 /* If the destination block consists of a nonlocal label, do not
983 merge it. */
984 label = first_stmt (dest);
985 if (label)
986 if (glabel *label_stmt = dyn_cast <glabel *> (label))
987 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
988 return false;
989
990 /* Record BB's single pred in case we need to update the father
991 loop's latch information later. */
992 basic_block pred = NULL;
993 if (single_pred_p (bb))
994 pred = single_pred (bb);
995
996 /* Redirect each incoming edge to BB to DEST. */
997 while (EDGE_COUNT (bb->preds) > 0)
998 {
999 edge e = EDGE_PRED (bb, 0), s;
1000 gphi_iterator gsi;
1001
1002 s = find_edge (e->src, dest);
1003 if (s)
1004 {
1005 /* We already have an edge S from E->src to DEST. If S and
1006 E->dest's sole successor edge have the same PHI arguments
1007 at DEST, redirect S to DEST. */
1008 if (phi_alternatives_equal (dest, s, succ))
1009 {
1010 e = redirect_edge_and_branch (e, dest);
1011 redirect_edge_var_map_clear (e);
1012 continue;
1013 }
1014
1015 /* PHI arguments are different. Create a forwarder block by
1016 splitting E so that we can merge PHI arguments on E to
1017 DEST. */
1018 e = single_succ_edge (split_edge (e));
1019 }
1020 else
1021 {
1022 /* If we merge the forwarder into a loop header verify if we
1023 are creating another loop latch edge. If so, reset
1024 number of iteration information of the loop. */
1025 if (dest->loop_father->header == dest
1026 && dominated_by_p (CDI_DOMINATORS, e->src, dest))
1027 {
1028 dest->loop_father->any_upper_bound = false;
1029 dest->loop_father->any_likely_upper_bound = false;
1030 free_numbers_of_iterations_estimates (dest->loop_father);
1031 }
1032 }
1033
1034 s = redirect_edge_and_branch (e, dest);
1035
1036 /* redirect_edge_and_branch must not create a new edge. */
1037 gcc_assert (s == e);
1038
1039 /* Add to the PHI nodes at DEST each PHI argument removed at the
1040 destination of E. */
1041 for (gsi = gsi_start_phis (dest);
1042 !gsi_end_p (gsi);
1043 gsi_next (&gsi))
1044 {
1045 gphi *phi = gsi.phi ();
1046 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
1047 source_location locus = gimple_phi_arg_location_from_edge (phi, succ);
1048
1049 if (TREE_CODE (def) == SSA_NAME)
1050 {
1051 /* If DEF is one of the results of PHI nodes removed during
1052 redirection, replace it with the PHI argument that used
1053 to be on E. */
1054 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
1055 size_t length = head ? head->length () : 0;
1056 for (size_t i = 0; i < length; i++)
1057 {
1058 edge_var_map *vm = &(*head)[i];
1059 tree old_arg = redirect_edge_var_map_result (vm);
1060 tree new_arg = redirect_edge_var_map_def (vm);
1061
1062 if (def == old_arg)
1063 {
1064 def = new_arg;
1065 locus = redirect_edge_var_map_location (vm);
1066 break;
1067 }
1068 }
1069 }
1070
1071 add_phi_arg (phi, def, s, locus);
1072 }
1073
1074 redirect_edge_var_map_clear (e);
1075 }
1076
1077 /* Update the dominators. */
1078 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
1079 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
1080 if (domdest == bb)
1081 {
1082 /* Shortcut to avoid calling (relatively expensive)
1083 nearest_common_dominator unless necessary. */
1084 dom = dombb;
1085 }
1086 else
1087 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
1088
1089 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
1090
1091 /* Adjust latch infomation of BB's parent loop as otherwise
1092 the cfg hook has a hard time not to kill the loop. */
1093 if (current_loops && bb->loop_father->latch == bb)
1094 bb->loop_father->latch = pred;
1095
1096 /* Remove BB since all of BB's incoming edges have been redirected
1097 to DEST. */
1098 delete_basic_block (bb);
1099
1100 return true;
1101 }
1102
1103 /* This pass merges PHI nodes if one feeds into another. For example,
1104 suppose we have the following:
1105
1106 goto <bb 9> (<L9>);
1107
1108 <L8>:;
1109 tem_17 = foo ();
1110
1111 # tem_6 = PHI <tem_17(8), tem_23(7)>;
1112 <L9>:;
1113
1114 # tem_3 = PHI <tem_6(9), tem_2(5)>;
1115 <L10>:;
1116
1117 Then we merge the first PHI node into the second one like so:
1118
1119 goto <bb 9> (<L10>);
1120
1121 <L8>:;
1122 tem_17 = foo ();
1123
1124 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
1125 <L10>:;
1126 */
1127
1128 namespace {
1129
1130 const pass_data pass_data_merge_phi =
1131 {
1132 GIMPLE_PASS, /* type */
1133 "mergephi", /* name */
1134 OPTGROUP_NONE, /* optinfo_flags */
1135 TV_TREE_MERGE_PHI, /* tv_id */
1136 ( PROP_cfg | PROP_ssa ), /* properties_required */
1137 0, /* properties_provided */
1138 0, /* properties_destroyed */
1139 0, /* todo_flags_start */
1140 0, /* todo_flags_finish */
1141 };
1142
1143 class pass_merge_phi : public gimple_opt_pass
1144 {
1145 public:
1146 pass_merge_phi (gcc::context *ctxt)
1147 : gimple_opt_pass (pass_data_merge_phi, ctxt)
1148 {}
1149
1150 /* opt_pass methods: */
1151 opt_pass * clone () { return new pass_merge_phi (m_ctxt); }
1152 virtual unsigned int execute (function *);
1153
1154 }; // class pass_merge_phi
1155
1156 unsigned int
1157 pass_merge_phi::execute (function *fun)
1158 {
1159 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
1160 basic_block *current = worklist;
1161 basic_block bb;
1162
1163 calculate_dominance_info (CDI_DOMINATORS);
1164
1165 /* Find all PHI nodes that we may be able to merge. */
1166 FOR_EACH_BB_FN (bb, fun)
1167 {
1168 basic_block dest;
1169
1170 /* Look for a forwarder block with PHI nodes. */
1171 if (!tree_forwarder_block_p (bb, true))
1172 continue;
1173
1174 dest = single_succ (bb);
1175
1176 /* We have to feed into another basic block with PHI
1177 nodes. */
1178 if (gimple_seq_empty_p (phi_nodes (dest))
1179 /* We don't want to deal with a basic block with
1180 abnormal edges. */
1181 || bb_has_abnormal_pred (bb))
1182 continue;
1183
1184 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1185 {
1186 /* If BB does not dominate DEST, then the PHI nodes at
1187 DEST must be the only users of the results of the PHI
1188 nodes at BB. */
1189 *current++ = bb;
1190 }
1191 else
1192 {
1193 gphi_iterator gsi;
1194 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1195
1196 /* BB dominates DEST. There may be many users of the PHI
1197 nodes in BB. However, there is still a trivial case we
1198 can handle. If the result of every PHI in BB is used
1199 only by a PHI in DEST, then we can trivially merge the
1200 PHI nodes from BB into DEST. */
1201 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1202 gsi_next (&gsi))
1203 {
1204 gphi *phi = gsi.phi ();
1205 tree result = gimple_phi_result (phi);
1206 use_operand_p imm_use;
1207 gimple *use_stmt;
1208
1209 /* If the PHI's result is never used, then we can just
1210 ignore it. */
1211 if (has_zero_uses (result))
1212 continue;
1213
1214 /* Get the single use of the result of this PHI node. */
1215 if (!single_imm_use (result, &imm_use, &use_stmt)
1216 || gimple_code (use_stmt) != GIMPLE_PHI
1217 || gimple_bb (use_stmt) != dest
1218 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1219 break;
1220 }
1221
1222 /* If the loop above iterated through all the PHI nodes
1223 in BB, then we can merge the PHIs from BB into DEST. */
1224 if (gsi_end_p (gsi))
1225 *current++ = bb;
1226 }
1227 }
1228
1229 /* Now let's drain WORKLIST. */
1230 bool changed = false;
1231 while (current != worklist)
1232 {
1233 bb = *--current;
1234 changed |= remove_forwarder_block_with_phi (bb);
1235 }
1236 free (worklist);
1237
1238 /* Removing forwarder blocks can cause formerly irreducible loops
1239 to become reducible if we merged two entry blocks. */
1240 if (changed
1241 && current_loops)
1242 loops_state_set (LOOPS_NEED_FIXUP);
1243
1244 return 0;
1245 }
1246
1247 } // anon namespace
1248
1249 gimple_opt_pass *
1250 make_pass_merge_phi (gcc::context *ctxt)
1251 {
1252 return new pass_merge_phi (ctxt);
1253 }
1254
1255 /* Pass: cleanup the CFG just before expanding trees to RTL.
1256 This is just a round of label cleanups and case node grouping
1257 because after the tree optimizers have run such cleanups may
1258 be necessary. */
1259
1260 static unsigned int
1261 execute_cleanup_cfg_post_optimizing (void)
1262 {
1263 unsigned int todo = execute_fixup_cfg ();
1264 if (cleanup_tree_cfg ())
1265 {
1266 todo &= ~TODO_cleanup_cfg;
1267 todo |= TODO_update_ssa;
1268 }
1269 maybe_remove_unreachable_handlers ();
1270 cleanup_dead_labels ();
1271 if (group_case_labels ())
1272 todo |= TODO_cleanup_cfg;
1273 if ((flag_compare_debug_opt || flag_compare_debug)
1274 && flag_dump_final_insns)
1275 {
1276 FILE *final_output = fopen (flag_dump_final_insns, "a");
1277
1278 if (!final_output)
1279 {
1280 error ("could not open final insn dump file %qs: %m",
1281 flag_dump_final_insns);
1282 flag_dump_final_insns = NULL;
1283 }
1284 else
1285 {
1286 int save_unnumbered = flag_dump_unnumbered;
1287 int save_noaddr = flag_dump_noaddr;
1288
1289 flag_dump_noaddr = flag_dump_unnumbered = 1;
1290 fprintf (final_output, "\n");
1291 dump_enumerated_decls (final_output, dump_flags | TDF_NOUID);
1292 flag_dump_noaddr = save_noaddr;
1293 flag_dump_unnumbered = save_unnumbered;
1294 if (fclose (final_output))
1295 {
1296 error ("could not close final insn dump file %qs: %m",
1297 flag_dump_final_insns);
1298 flag_dump_final_insns = NULL;
1299 }
1300 }
1301 }
1302 return todo;
1303 }
1304
1305 namespace {
1306
1307 const pass_data pass_data_cleanup_cfg_post_optimizing =
1308 {
1309 GIMPLE_PASS, /* type */
1310 "optimized", /* name */
1311 OPTGROUP_NONE, /* optinfo_flags */
1312 TV_TREE_CLEANUP_CFG, /* tv_id */
1313 PROP_cfg, /* properties_required */
1314 0, /* properties_provided */
1315 0, /* properties_destroyed */
1316 0, /* todo_flags_start */
1317 TODO_remove_unused_locals, /* todo_flags_finish */
1318 };
1319
1320 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1321 {
1322 public:
1323 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1324 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1325 {}
1326
1327 /* opt_pass methods: */
1328 virtual unsigned int execute (function *)
1329 {
1330 return execute_cleanup_cfg_post_optimizing ();
1331 }
1332
1333 }; // class pass_cleanup_cfg_post_optimizing
1334
1335 } // anon namespace
1336
1337 gimple_opt_pass *
1338 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1339 {
1340 return new pass_cleanup_cfg_post_optimizing (ctxt);
1341 }
1342
1343