PR target/81369
[official-gcc.git] / gcc / tree-cfgcleanup.c
blobc6e5c8da03c3391e1da693281d6ebf8ff2f2b3b2
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2017 Free Software Foundation, Inc.
4 This file is part of GCC.
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.
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.
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/>. */
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"
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;
57 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
59 static bool
60 remove_fallthru_edge (vec<edge, va_gc> *ev)
62 edge_iterator ei;
63 edge e;
65 FOR_EACH_EDGE (e, ei, ev)
66 if ((e->flags & EDGE_FALLTHRU) != 0)
68 if (e->flags & EDGE_COMPLEX)
69 e->flags &= ~EDGE_FALLTHRU;
70 else
71 remove_edge_and_dominated_blocks (e);
72 return true;
74 return false;
78 /* Disconnect an unreachable block in the control expression starting
79 at block BB. */
81 static bool
82 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi,
83 bool first_p)
85 edge taken_edge;
86 bool retval = false;
87 gimple *stmt = gsi_stmt (gsi);
89 if (!single_succ_p (bb))
91 edge e;
92 edge_iterator ei;
93 bool warned;
94 tree val = NULL_TREE;
96 fold_defer_overflow_warnings ();
97 switch (gimple_code (stmt))
99 case GIMPLE_COND:
100 /* During a first iteration on the CFG only remove trivially
101 dead edges but mark other conditions for re-evaluation. */
102 if (first_p)
104 val = const_binop (gimple_cond_code (stmt), boolean_type_node,
105 gimple_cond_lhs (stmt),
106 gimple_cond_rhs (stmt));
107 if (! val)
108 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
110 else
112 code_helper rcode;
113 tree ops[3] = {};
114 if (gimple_simplify (stmt, &rcode, ops, NULL, no_follow_ssa_edges,
115 no_follow_ssa_edges)
116 && rcode == INTEGER_CST)
117 val = ops[0];
119 break;
121 case GIMPLE_SWITCH:
122 val = gimple_switch_index (as_a <gswitch *> (stmt));
123 break;
125 default:
128 taken_edge = find_taken_edge (bb, val);
129 if (!taken_edge)
131 fold_undefer_and_ignore_overflow_warnings ();
132 return false;
135 /* Remove all the edges except the one that is always executed. */
136 warned = false;
137 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
139 if (e != taken_edge)
141 if (!warned)
143 fold_undefer_overflow_warnings
144 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
145 warned = true;
148 taken_edge->probability += e->probability;
149 taken_edge->count += e->count;
150 remove_edge_and_dominated_blocks (e);
151 retval = true;
153 else
154 ei_next (&ei);
156 if (!warned)
157 fold_undefer_and_ignore_overflow_warnings ();
159 else
160 taken_edge = single_succ_edge (bb);
162 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
163 gsi_remove (&gsi, true);
164 taken_edge->flags = EDGE_FALLTHRU;
166 return retval;
169 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
170 to updated gimple_call_flags. */
172 static void
173 cleanup_call_ctrl_altering_flag (gimple *bb_end)
175 if (!is_gimple_call (bb_end)
176 || !gimple_call_ctrl_altering_p (bb_end))
177 return;
179 int flags = gimple_call_flags (bb_end);
180 if (((flags & (ECF_CONST | ECF_PURE))
181 && !(flags & ECF_LOOPING_CONST_OR_PURE))
182 || (flags & ECF_LEAF))
183 gimple_call_set_ctrl_altering (bb_end, false);
186 /* Try to remove superfluous control structures in basic block BB. Returns
187 true if anything changes. */
189 static bool
190 cleanup_control_flow_bb (basic_block bb, bool first_p)
192 gimple_stmt_iterator gsi;
193 bool retval = false;
194 gimple *stmt;
196 /* If the last statement of the block could throw and now cannot,
197 we need to prune cfg. */
198 retval |= gimple_purge_dead_eh_edges (bb);
200 gsi = gsi_last_nondebug_bb (bb);
201 if (gsi_end_p (gsi))
202 return retval;
204 stmt = gsi_stmt (gsi);
206 /* Try to cleanup ctrl altering flag for call which ends bb. */
207 cleanup_call_ctrl_altering_flag (stmt);
209 if (gimple_code (stmt) == GIMPLE_COND
210 || gimple_code (stmt) == GIMPLE_SWITCH)
212 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
213 retval |= cleanup_control_expr_graph (bb, gsi, first_p);
215 else if (gimple_code (stmt) == GIMPLE_GOTO
216 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
217 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
218 == LABEL_DECL))
220 /* If we had a computed goto which has a compile-time determinable
221 destination, then we can eliminate the goto. */
222 edge e;
223 tree label;
224 edge_iterator ei;
225 basic_block target_block;
227 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
228 /* First look at all the outgoing edges. Delete any outgoing
229 edges which do not go to the right block. For the one
230 edge which goes to the right block, fix up its flags. */
231 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
232 if (DECL_CONTEXT (label) != cfun->decl)
233 return retval;
234 target_block = label_to_block (label);
235 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
237 if (e->dest != target_block)
238 remove_edge_and_dominated_blocks (e);
239 else
241 /* Turn off the EDGE_ABNORMAL flag. */
242 e->flags &= ~EDGE_ABNORMAL;
244 /* And set EDGE_FALLTHRU. */
245 e->flags |= EDGE_FALLTHRU;
246 ei_next (&ei);
250 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
251 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
253 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
254 relevant information we need. */
255 gsi_remove (&gsi, true);
256 retval = true;
259 /* Check for indirect calls that have been turned into
260 noreturn calls. */
261 else if (is_gimple_call (stmt)
262 && gimple_call_noreturn_p (stmt))
264 /* If there are debug stmts after the noreturn call, remove them
265 now, they should be all unreachable anyway. */
266 for (gsi_next (&gsi); !gsi_end_p (gsi); )
267 gsi_remove (&gsi, true);
268 if (remove_fallthru_edge (bb->succs))
269 retval = true;
272 return retval;
275 /* Return true if basic block BB does nothing except pass control
276 flow to another block and that we can safely insert a label at
277 the start of the successor block.
279 As a precondition, we require that BB be not equal to
280 the entry block. */
282 static bool
283 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
285 gimple_stmt_iterator gsi;
286 location_t locus;
288 /* BB must have a single outgoing edge. */
289 if (single_succ_p (bb) != 1
290 /* If PHI_WANTED is false, BB must not have any PHI nodes.
291 Otherwise, BB must have PHI nodes. */
292 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
293 /* BB may not be a predecessor of the exit block. */
294 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
295 /* Nor should this be an infinite loop. */
296 || single_succ (bb) == bb
297 /* BB may not have an abnormal outgoing edge. */
298 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
299 return false;
301 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
303 locus = single_succ_edge (bb)->goto_locus;
305 /* There should not be an edge coming from entry, or an EH edge. */
307 edge_iterator ei;
308 edge e;
310 FOR_EACH_EDGE (e, ei, bb->preds)
311 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
312 return false;
313 /* If goto_locus of any of the edges differs, prevent removing
314 the forwarder block for -O0. */
315 else if (optimize == 0 && e->goto_locus != locus)
316 return false;
319 /* Now walk through the statements backward. We can ignore labels,
320 anything else means this is not a forwarder block. */
321 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
323 gimple *stmt = gsi_stmt (gsi);
325 switch (gimple_code (stmt))
327 case GIMPLE_LABEL:
328 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
329 return false;
330 if (optimize == 0 && gimple_location (stmt) != locus)
331 return false;
332 break;
334 /* ??? For now, hope there's a corresponding debug
335 assignment at the destination. */
336 case GIMPLE_DEBUG:
337 break;
339 default:
340 return false;
344 if (current_loops)
346 basic_block dest;
347 /* Protect loop headers. */
348 if (bb_loop_header_p (bb))
349 return false;
351 dest = EDGE_SUCC (bb, 0)->dest;
352 /* Protect loop preheaders and latches if requested. */
353 if (dest->loop_father->header == dest)
355 if (bb->loop_father == dest->loop_father)
357 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
358 return false;
359 /* If bb doesn't have a single predecessor we'd make this
360 loop have multiple latches. Don't do that if that
361 would in turn require disambiguating them. */
362 return (single_pred_p (bb)
363 || loops_state_satisfies_p
364 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
366 else if (bb->loop_father == loop_outer (dest->loop_father))
367 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
368 /* Always preserve other edges into loop headers that are
369 not simple latches or preheaders. */
370 return false;
374 return true;
377 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
378 those alternatives are equal in each of the PHI nodes, then return
379 true, else return false. */
381 static bool
382 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
384 int n1 = e1->dest_idx;
385 int n2 = e2->dest_idx;
386 gphi_iterator gsi;
388 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
390 gphi *phi = gsi.phi ();
391 tree val1 = gimple_phi_arg_def (phi, n1);
392 tree val2 = gimple_phi_arg_def (phi, n2);
394 gcc_assert (val1 != NULL_TREE);
395 gcc_assert (val2 != NULL_TREE);
397 if (!operand_equal_for_phi_arg_p (val1, val2))
398 return false;
401 return true;
404 /* Removes forwarder block BB. Returns false if this failed. */
406 static bool
407 remove_forwarder_block (basic_block bb)
409 edge succ = single_succ_edge (bb), e, s;
410 basic_block dest = succ->dest;
411 gimple *label;
412 edge_iterator ei;
413 gimple_stmt_iterator gsi, gsi_to;
414 bool can_move_debug_stmts;
416 /* We check for infinite loops already in tree_forwarder_block_p.
417 However it may happen that the infinite loop is created
418 afterwards due to removal of forwarders. */
419 if (dest == bb)
420 return false;
422 /* If the destination block consists of a nonlocal label or is a
423 EH landing pad, do not merge it. */
424 label = first_stmt (dest);
425 if (label)
426 if (glabel *label_stmt = dyn_cast <glabel *> (label))
427 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
428 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
429 return false;
431 /* If there is an abnormal edge to basic block BB, but not into
432 dest, problems might occur during removal of the phi node at out
433 of ssa due to overlapping live ranges of registers.
435 If there is an abnormal edge in DEST, the problems would occur
436 anyway since cleanup_dead_labels would then merge the labels for
437 two different eh regions, and rest of exception handling code
438 does not like it.
440 So if there is an abnormal edge to BB, proceed only if there is
441 no abnormal edge to DEST and there are no phi nodes in DEST. */
442 if (bb_has_abnormal_pred (bb)
443 && (bb_has_abnormal_pred (dest)
444 || !gimple_seq_empty_p (phi_nodes (dest))))
445 return false;
447 /* If there are phi nodes in DEST, and some of the blocks that are
448 predecessors of BB are also predecessors of DEST, check that the
449 phi node arguments match. */
450 if (!gimple_seq_empty_p (phi_nodes (dest)))
452 FOR_EACH_EDGE (e, ei, bb->preds)
454 s = find_edge (e->src, dest);
455 if (!s)
456 continue;
458 if (!phi_alternatives_equal (dest, succ, s))
459 return false;
463 can_move_debug_stmts = MAY_HAVE_DEBUG_STMTS && single_pred_p (dest);
465 basic_block pred = NULL;
466 if (single_pred_p (bb))
467 pred = single_pred (bb);
469 /* Redirect the edges. */
470 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
472 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
474 if (e->flags & EDGE_ABNORMAL)
476 /* If there is an abnormal edge, redirect it anyway, and
477 move the labels to the new block to make it legal. */
478 s = redirect_edge_succ_nodup (e, dest);
480 else
481 s = redirect_edge_and_branch (e, dest);
483 if (s == e)
485 /* Create arguments for the phi nodes, since the edge was not
486 here before. */
487 for (gphi_iterator psi = gsi_start_phis (dest);
488 !gsi_end_p (psi);
489 gsi_next (&psi))
491 gphi *phi = psi.phi ();
492 source_location l = gimple_phi_arg_location_from_edge (phi, succ);
493 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
494 add_phi_arg (phi, unshare_expr (def), s, l);
499 /* Move nonlocal labels and computed goto targets as well as user
500 defined labels and labels with an EH landing pad number to the
501 new block, so that the redirection of the abnormal edges works,
502 jump targets end up in a sane place and debug information for
503 labels is retained. */
504 gsi_to = gsi_start_bb (dest);
505 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
507 tree decl;
508 label = gsi_stmt (gsi);
509 if (is_gimple_debug (label))
510 break;
511 decl = gimple_label_label (as_a <glabel *> (label));
512 if (EH_LANDING_PAD_NR (decl) != 0
513 || DECL_NONLOCAL (decl)
514 || FORCED_LABEL (decl)
515 || !DECL_ARTIFICIAL (decl))
517 gsi_remove (&gsi, false);
518 gsi_insert_before (&gsi_to, label, GSI_SAME_STMT);
520 else
521 gsi_next (&gsi);
524 /* Move debug statements if the destination has a single predecessor. */
525 if (can_move_debug_stmts)
527 gsi_to = gsi_after_labels (dest);
528 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); )
530 gimple *debug = gsi_stmt (gsi);
531 if (!is_gimple_debug (debug))
532 break;
533 gsi_remove (&gsi, false);
534 gsi_insert_before (&gsi_to, debug, GSI_SAME_STMT);
538 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
540 /* Update the dominators. */
541 if (dom_info_available_p (CDI_DOMINATORS))
543 basic_block dom, dombb, domdest;
545 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
546 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
547 if (domdest == bb)
549 /* Shortcut to avoid calling (relatively expensive)
550 nearest_common_dominator unless necessary. */
551 dom = dombb;
553 else
554 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
556 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
559 /* Adjust latch infomation of BB's parent loop as otherwise
560 the cfg hook has a hard time not to kill the loop. */
561 if (current_loops && bb->loop_father->latch == bb)
562 bb->loop_father->latch = pred;
564 /* And kill the forwarder block. */
565 delete_basic_block (bb);
567 return true;
570 /* STMT is a call that has been discovered noreturn. Split the
571 block to prepare fixing up the CFG and remove LHS.
572 Return true if cleanup-cfg needs to run. */
574 bool
575 fixup_noreturn_call (gimple *stmt)
577 basic_block bb = gimple_bb (stmt);
578 bool changed = false;
580 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
581 return false;
583 /* First split basic block if stmt is not last. */
584 if (stmt != gsi_stmt (gsi_last_bb (bb)))
586 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
588 /* Don't split if there are only debug stmts
589 after stmt, that can result in -fcompare-debug
590 failures. Remove the debug stmts instead,
591 they should be all unreachable anyway. */
592 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
593 for (gsi_next (&gsi); !gsi_end_p (gsi); )
594 gsi_remove (&gsi, true);
596 else
598 split_block (bb, stmt);
599 changed = true;
603 /* If there is an LHS, remove it, but only if its type has fixed size.
604 The LHS will need to be recreated during RTL expansion and creating
605 temporaries of variable-sized types is not supported. Also don't
606 do this with TREE_ADDRESSABLE types, as assign_temp will abort.
607 Drop LHS regardless of TREE_ADDRESSABLE, if the function call
608 has been changed into a call that does not return a value, like
609 __builtin_unreachable or __cxa_pure_virtual. */
610 tree lhs = gimple_call_lhs (stmt);
611 if (lhs
612 && (should_remove_lhs_p (lhs)
613 || VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))))
615 gimple_call_set_lhs (stmt, NULL_TREE);
617 /* We need to fix up the SSA name to avoid checking errors. */
618 if (TREE_CODE (lhs) == SSA_NAME)
620 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
621 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
622 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
623 set_ssa_default_def (cfun, new_var, lhs);
626 update_stmt (stmt);
629 /* Mark the call as altering control flow. */
630 if (!gimple_call_ctrl_altering_p (stmt))
632 gimple_call_set_ctrl_altering (stmt, true);
633 changed = true;
636 return changed;
639 /* Return true if we want to merge BB1 and BB2 into a single block. */
641 static bool
642 want_merge_blocks_p (basic_block bb1, basic_block bb2)
644 if (!can_merge_blocks_p (bb1, bb2))
645 return false;
646 gimple_stmt_iterator gsi = gsi_last_nondebug_bb (bb1);
647 if (gsi_end_p (gsi) || !stmt_can_terminate_bb_p (gsi_stmt (gsi)))
648 return true;
649 return bb1->count.ok_for_merging (bb2->count);
653 /* Tries to cleanup cfg in basic block BB. Returns true if anything
654 changes. */
656 static bool
657 cleanup_tree_cfg_bb (basic_block bb)
659 if (tree_forwarder_block_p (bb, false)
660 && remove_forwarder_block (bb))
661 return true;
663 /* If there is a merge opportunity with the predecessor
664 do nothing now but wait until we process the predecessor.
665 This happens when we visit BBs in a non-optimal order and
666 avoids quadratic behavior with adjusting stmts BB pointer. */
667 if (single_pred_p (bb)
668 && want_merge_blocks_p (single_pred (bb), bb))
669 /* But make sure we _do_ visit it. When we remove unreachable paths
670 ending in a backedge we fail to mark the destinations predecessors
671 as changed. */
672 bitmap_set_bit (cfgcleanup_altered_bbs, single_pred (bb)->index);
674 /* Merging the blocks may create new opportunities for folding
675 conditional branches (due to the elimination of single-valued PHI
676 nodes). */
677 else if (single_succ_p (bb)
678 && want_merge_blocks_p (bb, single_succ (bb)))
680 merge_blocks (bb, single_succ (bb));
681 return true;
684 return false;
687 /* Iterate the cfg cleanups, while anything changes. */
689 static bool
690 cleanup_tree_cfg_1 (void)
692 bool retval = false;
693 basic_block bb;
694 unsigned i, n;
696 /* Prepare the worklists of altered blocks. */
697 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
699 /* During forwarder block cleanup, we may redirect edges out of
700 SWITCH_EXPRs, which can get expensive. So we want to enable
701 recording of edge to CASE_LABEL_EXPR. */
702 start_recording_case_labels ();
704 /* We cannot use FOR_EACH_BB_FN for the BB iterations below
705 since the basic blocks may get removed. */
707 /* Start by iterating over all basic blocks looking for edge removal
708 opportunities. Do this first because incoming SSA form may be
709 invalid and we want to avoid performing SSA related tasks such
710 as propgating out a PHI node during BB merging in that state. */
711 n = last_basic_block_for_fn (cfun);
712 for (i = NUM_FIXED_BLOCKS; i < n; i++)
714 bb = BASIC_BLOCK_FOR_FN (cfun, i);
715 if (bb)
716 retval |= cleanup_control_flow_bb (bb, true);
719 /* After doing the above SSA form should be valid (or an update SSA
720 should be required). */
722 /* Continue by iterating over all basic blocks looking for BB merging
723 opportunities. */
724 n = last_basic_block_for_fn (cfun);
725 for (i = NUM_FIXED_BLOCKS; i < n; i++)
727 bb = BASIC_BLOCK_FOR_FN (cfun, i);
728 if (bb)
729 retval |= cleanup_tree_cfg_bb (bb);
732 /* Now process the altered blocks, as long as any are available. */
733 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
735 i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
736 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
737 if (i < NUM_FIXED_BLOCKS)
738 continue;
740 bb = BASIC_BLOCK_FOR_FN (cfun, i);
741 if (!bb)
742 continue;
744 retval |= cleanup_control_flow_bb (bb, false);
745 retval |= cleanup_tree_cfg_bb (bb);
748 end_recording_case_labels ();
749 BITMAP_FREE (cfgcleanup_altered_bbs);
750 return retval;
753 static bool
754 mfb_keep_latches (edge e)
756 return ! dominated_by_p (CDI_DOMINATORS, e->src, e->dest);
759 /* Remove unreachable blocks and other miscellaneous clean up work.
760 Return true if the flowgraph was modified, false otherwise. */
762 static bool
763 cleanup_tree_cfg_noloop (void)
765 bool changed;
767 timevar_push (TV_TREE_CLEANUP_CFG);
769 /* Iterate until there are no more cleanups left to do. If any
770 iteration changed the flowgraph, set CHANGED to true.
772 If dominance information is available, there cannot be any unreachable
773 blocks. */
774 if (!dom_info_available_p (CDI_DOMINATORS))
776 changed = delete_unreachable_blocks ();
777 calculate_dominance_info (CDI_DOMINATORS);
779 else
781 checking_verify_dominators (CDI_DOMINATORS);
782 changed = false;
785 /* Ensure that we have single entries into loop headers. Otherwise
786 if one of the entries is becoming a latch due to CFG cleanup
787 (from formerly being part of an irreducible region) then we mess
788 up loop fixup and associate the old loop with a different region
789 which makes niter upper bounds invalid. See for example PR80549.
790 This needs to be done before we remove trivially dead edges as
791 we need to capture the dominance state before the pending transform. */
792 if (current_loops)
794 loop_p loop;
795 unsigned i;
796 FOR_EACH_VEC_ELT (*get_loops (cfun), i, loop)
797 if (loop && loop->header)
799 basic_block bb = loop->header;
800 edge_iterator ei;
801 edge e;
802 bool found_latch = false;
803 bool any_abnormal = false;
804 unsigned n = 0;
805 /* We are only interested in preserving existing loops, but
806 we need to check whether they are still real and of course
807 if we need to add a preheader at all. */
808 FOR_EACH_EDGE (e, ei, bb->preds)
810 if (e->flags & EDGE_ABNORMAL)
812 any_abnormal = true;
813 break;
815 if (dominated_by_p (CDI_DOMINATORS, e->src, bb))
817 found_latch = true;
818 continue;
820 n++;
822 /* If we have more than one entry to the loop header
823 create a forwarder. */
824 if (found_latch && ! any_abnormal && n > 1)
826 edge fallthru = make_forwarder_block (bb, mfb_keep_latches,
827 NULL);
828 loop->header = fallthru->dest;
829 if (! loops_state_satisfies_p (LOOPS_NEED_FIXUP))
831 /* The loop updating from the CFG hook is incomplete
832 when we have multiple latches, fixup manually. */
833 remove_bb_from_loops (fallthru->src);
834 loop_p cloop = loop;
835 FOR_EACH_EDGE (e, ei, fallthru->src->preds)
836 cloop = find_common_loop (cloop, e->src->loop_father);
837 add_bb_to_loop (fallthru->src, cloop);
843 changed |= cleanup_tree_cfg_1 ();
845 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
846 compact_blocks ();
848 checking_verify_flow_info ();
850 timevar_pop (TV_TREE_CLEANUP_CFG);
852 if (changed && current_loops)
854 /* Removing edges and/or blocks may make recorded bounds refer
855 to stale GIMPLE stmts now, so clear them. */
856 free_numbers_of_iterations_estimates (cfun);
857 loops_state_set (LOOPS_NEED_FIXUP);
860 return changed;
863 /* Repairs loop structures. */
865 static void
866 repair_loop_structures (void)
868 bitmap changed_bbs;
869 unsigned n_new_loops;
871 calculate_dominance_info (CDI_DOMINATORS);
873 timevar_push (TV_REPAIR_LOOPS);
874 changed_bbs = BITMAP_ALLOC (NULL);
875 n_new_loops = fix_loop_structure (changed_bbs);
877 /* This usually does nothing. But sometimes parts of cfg that originally
878 were inside a loop get out of it due to edge removal (since they
879 become unreachable by back edges from latch). Also a former
880 irreducible loop can become reducible - in this case force a full
881 rewrite into loop-closed SSA form. */
882 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
883 rewrite_into_loop_closed_ssa (n_new_loops ? NULL : changed_bbs,
884 TODO_update_ssa);
886 BITMAP_FREE (changed_bbs);
888 checking_verify_loop_structure ();
889 scev_reset ();
891 timevar_pop (TV_REPAIR_LOOPS);
894 /* Cleanup cfg and repair loop structures. */
896 bool
897 cleanup_tree_cfg (void)
899 bool changed = cleanup_tree_cfg_noloop ();
901 if (current_loops != NULL
902 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
903 repair_loop_structures ();
905 return changed;
908 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
909 Returns true if successful. */
911 static bool
912 remove_forwarder_block_with_phi (basic_block bb)
914 edge succ = single_succ_edge (bb);
915 basic_block dest = succ->dest;
916 gimple *label;
917 basic_block dombb, domdest, dom;
919 /* We check for infinite loops already in tree_forwarder_block_p.
920 However it may happen that the infinite loop is created
921 afterwards due to removal of forwarders. */
922 if (dest == bb)
923 return false;
925 /* Removal of forwarders may expose new natural loops and thus
926 a block may turn into a loop header. */
927 if (current_loops && bb_loop_header_p (bb))
928 return false;
930 /* If the destination block consists of a nonlocal label, do not
931 merge it. */
932 label = first_stmt (dest);
933 if (label)
934 if (glabel *label_stmt = dyn_cast <glabel *> (label))
935 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
936 return false;
938 /* Record BB's single pred in case we need to update the father
939 loop's latch information later. */
940 basic_block pred = NULL;
941 if (single_pred_p (bb))
942 pred = single_pred (bb);
944 /* Redirect each incoming edge to BB to DEST. */
945 while (EDGE_COUNT (bb->preds) > 0)
947 edge e = EDGE_PRED (bb, 0), s;
948 gphi_iterator gsi;
950 s = find_edge (e->src, dest);
951 if (s)
953 /* We already have an edge S from E->src to DEST. If S and
954 E->dest's sole successor edge have the same PHI arguments
955 at DEST, redirect S to DEST. */
956 if (phi_alternatives_equal (dest, s, succ))
958 e = redirect_edge_and_branch (e, dest);
959 redirect_edge_var_map_clear (e);
960 continue;
963 /* PHI arguments are different. Create a forwarder block by
964 splitting E so that we can merge PHI arguments on E to
965 DEST. */
966 e = single_succ_edge (split_edge (e));
968 else
970 /* If we merge the forwarder into a loop header verify if we
971 are creating another loop latch edge. If so, reset
972 number of iteration information of the loop. */
973 if (dest->loop_father->header == dest
974 && dominated_by_p (CDI_DOMINATORS, e->src, dest))
976 dest->loop_father->any_upper_bound = false;
977 dest->loop_father->any_likely_upper_bound = false;
978 free_numbers_of_iterations_estimates (dest->loop_father);
982 s = redirect_edge_and_branch (e, dest);
984 /* redirect_edge_and_branch must not create a new edge. */
985 gcc_assert (s == e);
987 /* Add to the PHI nodes at DEST each PHI argument removed at the
988 destination of E. */
989 for (gsi = gsi_start_phis (dest);
990 !gsi_end_p (gsi);
991 gsi_next (&gsi))
993 gphi *phi = gsi.phi ();
994 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
995 source_location locus = gimple_phi_arg_location_from_edge (phi, succ);
997 if (TREE_CODE (def) == SSA_NAME)
999 /* If DEF is one of the results of PHI nodes removed during
1000 redirection, replace it with the PHI argument that used
1001 to be on E. */
1002 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
1003 size_t length = head ? head->length () : 0;
1004 for (size_t i = 0; i < length; i++)
1006 edge_var_map *vm = &(*head)[i];
1007 tree old_arg = redirect_edge_var_map_result (vm);
1008 tree new_arg = redirect_edge_var_map_def (vm);
1010 if (def == old_arg)
1012 def = new_arg;
1013 locus = redirect_edge_var_map_location (vm);
1014 break;
1019 add_phi_arg (phi, def, s, locus);
1022 redirect_edge_var_map_clear (e);
1025 /* Update the dominators. */
1026 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
1027 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
1028 if (domdest == bb)
1030 /* Shortcut to avoid calling (relatively expensive)
1031 nearest_common_dominator unless necessary. */
1032 dom = dombb;
1034 else
1035 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
1037 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
1039 /* Adjust latch infomation of BB's parent loop as otherwise
1040 the cfg hook has a hard time not to kill the loop. */
1041 if (current_loops && bb->loop_father->latch == bb)
1042 bb->loop_father->latch = pred;
1044 /* Remove BB since all of BB's incoming edges have been redirected
1045 to DEST. */
1046 delete_basic_block (bb);
1048 return true;
1051 /* This pass merges PHI nodes if one feeds into another. For example,
1052 suppose we have the following:
1054 goto <bb 9> (<L9>);
1056 <L8>:;
1057 tem_17 = foo ();
1059 # tem_6 = PHI <tem_17(8), tem_23(7)>;
1060 <L9>:;
1062 # tem_3 = PHI <tem_6(9), tem_2(5)>;
1063 <L10>:;
1065 Then we merge the first PHI node into the second one like so:
1067 goto <bb 9> (<L10>);
1069 <L8>:;
1070 tem_17 = foo ();
1072 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
1073 <L10>:;
1076 namespace {
1078 const pass_data pass_data_merge_phi =
1080 GIMPLE_PASS, /* type */
1081 "mergephi", /* name */
1082 OPTGROUP_NONE, /* optinfo_flags */
1083 TV_TREE_MERGE_PHI, /* tv_id */
1084 ( PROP_cfg | PROP_ssa ), /* properties_required */
1085 0, /* properties_provided */
1086 0, /* properties_destroyed */
1087 0, /* todo_flags_start */
1088 0, /* todo_flags_finish */
1091 class pass_merge_phi : public gimple_opt_pass
1093 public:
1094 pass_merge_phi (gcc::context *ctxt)
1095 : gimple_opt_pass (pass_data_merge_phi, ctxt)
1098 /* opt_pass methods: */
1099 opt_pass * clone () { return new pass_merge_phi (m_ctxt); }
1100 virtual unsigned int execute (function *);
1102 }; // class pass_merge_phi
1104 unsigned int
1105 pass_merge_phi::execute (function *fun)
1107 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
1108 basic_block *current = worklist;
1109 basic_block bb;
1111 calculate_dominance_info (CDI_DOMINATORS);
1113 /* Find all PHI nodes that we may be able to merge. */
1114 FOR_EACH_BB_FN (bb, fun)
1116 basic_block dest;
1118 /* Look for a forwarder block with PHI nodes. */
1119 if (!tree_forwarder_block_p (bb, true))
1120 continue;
1122 dest = single_succ (bb);
1124 /* We have to feed into another basic block with PHI
1125 nodes. */
1126 if (gimple_seq_empty_p (phi_nodes (dest))
1127 /* We don't want to deal with a basic block with
1128 abnormal edges. */
1129 || bb_has_abnormal_pred (bb))
1130 continue;
1132 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1134 /* If BB does not dominate DEST, then the PHI nodes at
1135 DEST must be the only users of the results of the PHI
1136 nodes at BB. */
1137 *current++ = bb;
1139 else
1141 gphi_iterator gsi;
1142 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1144 /* BB dominates DEST. There may be many users of the PHI
1145 nodes in BB. However, there is still a trivial case we
1146 can handle. If the result of every PHI in BB is used
1147 only by a PHI in DEST, then we can trivially merge the
1148 PHI nodes from BB into DEST. */
1149 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1150 gsi_next (&gsi))
1152 gphi *phi = gsi.phi ();
1153 tree result = gimple_phi_result (phi);
1154 use_operand_p imm_use;
1155 gimple *use_stmt;
1157 /* If the PHI's result is never used, then we can just
1158 ignore it. */
1159 if (has_zero_uses (result))
1160 continue;
1162 /* Get the single use of the result of this PHI node. */
1163 if (!single_imm_use (result, &imm_use, &use_stmt)
1164 || gimple_code (use_stmt) != GIMPLE_PHI
1165 || gimple_bb (use_stmt) != dest
1166 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1167 break;
1170 /* If the loop above iterated through all the PHI nodes
1171 in BB, then we can merge the PHIs from BB into DEST. */
1172 if (gsi_end_p (gsi))
1173 *current++ = bb;
1177 /* Now let's drain WORKLIST. */
1178 bool changed = false;
1179 while (current != worklist)
1181 bb = *--current;
1182 changed |= remove_forwarder_block_with_phi (bb);
1184 free (worklist);
1186 /* Removing forwarder blocks can cause formerly irreducible loops
1187 to become reducible if we merged two entry blocks. */
1188 if (changed
1189 && current_loops)
1190 loops_state_set (LOOPS_NEED_FIXUP);
1192 return 0;
1195 } // anon namespace
1197 gimple_opt_pass *
1198 make_pass_merge_phi (gcc::context *ctxt)
1200 return new pass_merge_phi (ctxt);
1203 /* Pass: cleanup the CFG just before expanding trees to RTL.
1204 This is just a round of label cleanups and case node grouping
1205 because after the tree optimizers have run such cleanups may
1206 be necessary. */
1208 static unsigned int
1209 execute_cleanup_cfg_post_optimizing (void)
1211 unsigned int todo = execute_fixup_cfg ();
1212 if (cleanup_tree_cfg ())
1214 todo &= ~TODO_cleanup_cfg;
1215 todo |= TODO_update_ssa;
1217 maybe_remove_unreachable_handlers ();
1218 cleanup_dead_labels ();
1219 if (group_case_labels ())
1220 todo |= TODO_cleanup_cfg;
1221 if ((flag_compare_debug_opt || flag_compare_debug)
1222 && flag_dump_final_insns)
1224 FILE *final_output = fopen (flag_dump_final_insns, "a");
1226 if (!final_output)
1228 error ("could not open final insn dump file %qs: %m",
1229 flag_dump_final_insns);
1230 flag_dump_final_insns = NULL;
1232 else
1234 int save_unnumbered = flag_dump_unnumbered;
1235 int save_noaddr = flag_dump_noaddr;
1237 flag_dump_noaddr = flag_dump_unnumbered = 1;
1238 fprintf (final_output, "\n");
1239 dump_enumerated_decls (final_output, dump_flags | TDF_NOUID);
1240 flag_dump_noaddr = save_noaddr;
1241 flag_dump_unnumbered = save_unnumbered;
1242 if (fclose (final_output))
1244 error ("could not close final insn dump file %qs: %m",
1245 flag_dump_final_insns);
1246 flag_dump_final_insns = NULL;
1250 return todo;
1253 namespace {
1255 const pass_data pass_data_cleanup_cfg_post_optimizing =
1257 GIMPLE_PASS, /* type */
1258 "optimized", /* name */
1259 OPTGROUP_NONE, /* optinfo_flags */
1260 TV_TREE_CLEANUP_CFG, /* tv_id */
1261 PROP_cfg, /* properties_required */
1262 0, /* properties_provided */
1263 0, /* properties_destroyed */
1264 0, /* todo_flags_start */
1265 TODO_remove_unused_locals, /* todo_flags_finish */
1268 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1270 public:
1271 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1272 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1275 /* opt_pass methods: */
1276 virtual unsigned int execute (function *)
1278 return execute_cleanup_cfg_post_optimizing ();
1281 }; // class pass_cleanup_cfg_post_optimizing
1283 } // anon namespace
1285 gimple_opt_pass *
1286 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1288 return new pass_cleanup_cfg_post_optimizing (ctxt);