d: Merge upstream dmd d579c467c1, phobos 88aa69b14.
[official-gcc.git] / gcc / tree-cfgcleanup.cc
blobb4869aee78d100559e060bfefb41d49896bf7199
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2022 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"
46 #include "cgraph.h"
47 #include "tree-into-ssa.h"
48 #include "tree-cfgcleanup.h"
51 /* The set of blocks in that at least one of the following changes happened:
52 -- the statement at the end of the block was changed
53 -- the block was newly created
54 -- the set of the predecessors of the block changed
55 -- the set of the successors of the block changed
56 ??? Maybe we could track these changes separately, since they determine
57 what cleanups it makes sense to try on the block. */
58 bitmap cfgcleanup_altered_bbs;
60 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
62 static bool
63 remove_fallthru_edge (vec<edge, va_gc> *ev)
65 edge_iterator ei;
66 edge e;
68 FOR_EACH_EDGE (e, ei, ev)
69 if ((e->flags & EDGE_FALLTHRU) != 0)
71 if (e->flags & EDGE_COMPLEX)
72 e->flags &= ~EDGE_FALLTHRU;
73 else
74 remove_edge_and_dominated_blocks (e);
75 return true;
77 return false;
80 /* Convert a SWTCH with single non-default case to gcond and replace it
81 at GSI. */
83 static bool
84 convert_single_case_switch (gswitch *swtch, gimple_stmt_iterator &gsi)
86 if (gimple_switch_num_labels (swtch) != 2)
87 return false;
89 tree index = gimple_switch_index (swtch);
90 tree label = gimple_switch_label (swtch, 1);
91 tree low = CASE_LOW (label);
92 tree high = CASE_HIGH (label);
94 basic_block default_bb = gimple_switch_default_bb (cfun, swtch);
95 basic_block case_bb = label_to_block (cfun, CASE_LABEL (label));
97 basic_block bb = gimple_bb (swtch);
98 gcond *cond;
100 /* Replace switch statement with condition statement. */
101 if (high)
103 tree lhs, rhs;
104 if (range_check_type (TREE_TYPE (index)) == NULL_TREE)
105 return false;
106 generate_range_test (bb, index, low, high, &lhs, &rhs);
107 cond = gimple_build_cond (LE_EXPR, lhs, rhs, NULL_TREE, NULL_TREE);
109 else
110 cond = gimple_build_cond (EQ_EXPR, index,
111 fold_convert (TREE_TYPE (index), low),
112 NULL_TREE, NULL_TREE);
114 gsi_replace (&gsi, cond, true);
116 /* Update edges. */
117 edge case_edge = find_edge (bb, case_bb);
118 edge default_edge = find_edge (bb, default_bb);
120 case_edge->flags |= EDGE_TRUE_VALUE;
121 default_edge->flags |= EDGE_FALSE_VALUE;
122 return true;
125 /* Disconnect an unreachable block in the control expression starting
126 at block BB. */
128 static bool
129 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi)
131 edge taken_edge;
132 bool retval = false;
133 gimple *stmt = gsi_stmt (gsi);
135 if (!single_succ_p (bb))
137 edge e;
138 edge_iterator ei;
139 bool warned;
140 tree val = NULL_TREE;
142 /* Try to convert a switch with just a single non-default case to
143 GIMPLE condition. */
144 if (gimple_code (stmt) == GIMPLE_SWITCH
145 && convert_single_case_switch (as_a<gswitch *> (stmt), gsi))
146 stmt = gsi_stmt (gsi);
148 fold_defer_overflow_warnings ();
149 switch (gimple_code (stmt))
151 case GIMPLE_COND:
153 gimple_match_op res_op;
154 if (gimple_simplify (stmt, &res_op, NULL, no_follow_ssa_edges,
155 no_follow_ssa_edges)
156 && res_op.code == INTEGER_CST)
157 val = res_op.ops[0];
159 break;
161 case GIMPLE_SWITCH:
162 val = gimple_switch_index (as_a <gswitch *> (stmt));
163 break;
165 default:
168 taken_edge = find_taken_edge (bb, val);
169 if (!taken_edge)
171 fold_undefer_and_ignore_overflow_warnings ();
172 return false;
175 /* Remove all the edges except the one that is always executed. */
176 warned = false;
177 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
179 if (e != taken_edge)
181 if (!warned)
183 fold_undefer_overflow_warnings
184 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
185 warned = true;
188 taken_edge->probability += e->probability;
189 remove_edge_and_dominated_blocks (e);
190 retval = true;
192 else
193 ei_next (&ei);
195 if (!warned)
196 fold_undefer_and_ignore_overflow_warnings ();
198 else
199 taken_edge = single_succ_edge (bb);
201 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
202 gsi_remove (&gsi, true);
203 taken_edge->flags = EDGE_FALLTHRU;
205 return retval;
208 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
209 to updated gimple_call_flags. */
211 static void
212 cleanup_call_ctrl_altering_flag (basic_block bb, gimple *bb_end)
214 if (!is_gimple_call (bb_end)
215 || !gimple_call_ctrl_altering_p (bb_end)
216 || (/* IFN_UNIQUE should be the last insn, to make checking for it
217 as cheap as possible. */
218 gimple_call_internal_p (bb_end)
219 && gimple_call_internal_unique_p (bb_end)))
220 return;
222 int flags = gimple_call_flags (bb_end);
223 if (!(flags & ECF_NORETURN)
224 && (((flags & (ECF_CONST | ECF_PURE))
225 && !(flags & ECF_LOOPING_CONST_OR_PURE))
226 || (flags & ECF_LEAF)))
227 gimple_call_set_ctrl_altering (bb_end, false);
228 else
230 edge_iterator ei;
231 edge e;
232 bool found = false;
233 FOR_EACH_EDGE (e, ei, bb->succs)
234 if (e->flags & EDGE_FALLTHRU)
235 found = true;
236 else if (e->flags & EDGE_ABNORMAL)
238 found = false;
239 break;
241 /* If there's no abnormal edge and a fallthru edge the call
242 isn't control-altering anymore. */
243 if (found)
244 gimple_call_set_ctrl_altering (bb_end, false);
248 /* Try to remove superfluous control structures in basic block BB. Returns
249 true if anything changes. */
251 static bool
252 cleanup_control_flow_bb (basic_block bb)
254 gimple_stmt_iterator gsi;
255 bool retval = false;
256 gimple *stmt;
258 /* If the last statement of the block could throw and now cannot,
259 we need to prune cfg. */
260 retval |= gimple_purge_dead_eh_edges (bb);
262 gsi = gsi_last_nondebug_bb (bb);
263 if (gsi_end_p (gsi))
264 return retval;
266 stmt = gsi_stmt (gsi);
268 /* Try to cleanup ctrl altering flag for call which ends bb. */
269 cleanup_call_ctrl_altering_flag (bb, stmt);
271 if (gimple_code (stmt) == GIMPLE_COND
272 || gimple_code (stmt) == GIMPLE_SWITCH)
274 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
275 retval |= cleanup_control_expr_graph (bb, gsi);
277 else if (gimple_code (stmt) == GIMPLE_GOTO
278 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
279 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
280 == LABEL_DECL))
282 /* If we had a computed goto which has a compile-time determinable
283 destination, then we can eliminate the goto. */
284 edge e;
285 tree label;
286 edge_iterator ei;
287 basic_block target_block;
289 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
290 /* First look at all the outgoing edges. Delete any outgoing
291 edges which do not go to the right block. For the one
292 edge which goes to the right block, fix up its flags. */
293 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
294 if (DECL_CONTEXT (label) != cfun->decl)
295 return retval;
296 target_block = label_to_block (cfun, label);
297 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
299 if (e->dest != target_block)
300 remove_edge_and_dominated_blocks (e);
301 else
303 /* Turn off the EDGE_ABNORMAL flag. */
304 e->flags &= ~EDGE_ABNORMAL;
306 /* And set EDGE_FALLTHRU. */
307 e->flags |= EDGE_FALLTHRU;
308 ei_next (&ei);
312 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
313 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
315 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
316 relevant information we need. */
317 gsi_remove (&gsi, true);
318 retval = true;
321 /* Check for indirect calls that have been turned into
322 noreturn calls. */
323 else if (is_gimple_call (stmt)
324 && gimple_call_noreturn_p (stmt))
326 /* If there are debug stmts after the noreturn call, remove them
327 now, they should be all unreachable anyway. */
328 for (gsi_next (&gsi); !gsi_end_p (gsi); )
329 gsi_remove (&gsi, true);
330 if (remove_fallthru_edge (bb->succs))
331 retval = true;
332 tree lhs = gimple_call_lhs (stmt);
333 if (!lhs
334 || !should_remove_lhs_p (lhs))
335 gimple_call_set_ctrl_altering (stmt, true);
338 return retval;
341 /* Return true if basic block BB does nothing except pass control
342 flow to another block and that we can safely insert a label at
343 the start of the successor block.
345 As a precondition, we require that BB be not equal to
346 the entry block. */
348 static bool
349 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
351 gimple_stmt_iterator gsi;
352 location_t locus;
354 /* BB must have a single outgoing edge. */
355 if (single_succ_p (bb) != 1
356 /* If PHI_WANTED is false, BB must not have any PHI nodes.
357 Otherwise, BB must have PHI nodes. */
358 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
359 /* BB may not be a predecessor of the exit block. */
360 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
361 /* Nor should this be an infinite loop. */
362 || single_succ (bb) == bb
363 /* BB may not have an abnormal outgoing edge. */
364 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
365 return false;
367 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
369 locus = single_succ_edge (bb)->goto_locus;
371 /* There should not be an edge coming from entry, or an EH edge. */
373 edge_iterator ei;
374 edge e;
376 FOR_EACH_EDGE (e, ei, bb->preds)
377 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
378 return false;
379 /* If goto_locus of any of the edges differs, prevent removing
380 the forwarder block when not optimizing. */
381 else if (!optimize
382 && (LOCATION_LOCUS (e->goto_locus) != UNKNOWN_LOCATION
383 || LOCATION_LOCUS (locus) != UNKNOWN_LOCATION)
384 && e->goto_locus != locus)
385 return false;
388 /* Now walk through the statements backward. We can ignore labels,
389 anything else means this is not a forwarder block. */
390 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
392 gimple *stmt = gsi_stmt (gsi);
394 switch (gimple_code (stmt))
396 case GIMPLE_LABEL:
397 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
398 return false;
399 if (!optimize
400 && (gimple_has_location (stmt)
401 || LOCATION_LOCUS (locus) != UNKNOWN_LOCATION)
402 && gimple_location (stmt) != locus)
403 return false;
404 break;
406 /* ??? For now, hope there's a corresponding debug
407 assignment at the destination. */
408 case GIMPLE_DEBUG:
409 break;
411 default:
412 return false;
416 if (current_loops)
418 basic_block dest;
419 /* Protect loop headers. */
420 if (bb_loop_header_p (bb))
421 return false;
423 dest = EDGE_SUCC (bb, 0)->dest;
424 /* Protect loop preheaders and latches if requested. */
425 if (dest->loop_father->header == dest)
427 if (bb->loop_father == dest->loop_father)
429 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
430 return false;
431 /* If bb doesn't have a single predecessor we'd make this
432 loop have multiple latches. Don't do that if that
433 would in turn require disambiguating them. */
434 return (single_pred_p (bb)
435 || loops_state_satisfies_p
436 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
438 else if (bb->loop_father == loop_outer (dest->loop_father))
439 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
440 /* Always preserve other edges into loop headers that are
441 not simple latches or preheaders. */
442 return false;
446 return true;
449 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
450 those alternatives are equal in each of the PHI nodes, then return
451 true, else return false. */
453 static bool
454 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
456 int n1 = e1->dest_idx;
457 int n2 = e2->dest_idx;
458 gphi_iterator gsi;
460 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
462 gphi *phi = gsi.phi ();
463 tree val1 = gimple_phi_arg_def (phi, n1);
464 tree val2 = gimple_phi_arg_def (phi, n2);
466 gcc_assert (val1 != NULL_TREE);
467 gcc_assert (val2 != NULL_TREE);
469 if (!operand_equal_for_phi_arg_p (val1, val2))
470 return false;
473 return true;
476 /* Move debug stmts from the forwarder block SRC to DEST or PRED. */
478 static void
479 move_debug_stmts_from_forwarder (basic_block src,
480 basic_block dest, bool dest_single_pred_p,
481 basic_block pred, bool pred_single_succ_p)
483 if (!MAY_HAVE_DEBUG_STMTS)
484 return;
486 /* If we cannot move to the destination but to the predecessor do that. */
487 if (!dest_single_pred_p && pred_single_succ_p)
489 gimple_stmt_iterator gsi_to = gsi_last_bb (pred);
490 if (gsi_end_p (gsi_to) || !stmt_ends_bb_p (gsi_stmt (gsi_to)))
492 for (gimple_stmt_iterator gsi = gsi_after_labels (src);
493 !gsi_end_p (gsi);)
495 gimple *debug = gsi_stmt (gsi);
496 gcc_assert (is_gimple_debug (debug));
497 gsi_move_after (&gsi, &gsi_to);
499 return;
503 /* Else move to DEST or drop/reset them. */
504 gimple_stmt_iterator gsi_to = gsi_after_labels (dest);
505 for (gimple_stmt_iterator gsi = gsi_after_labels (src); !gsi_end_p (gsi);)
507 gimple *debug = gsi_stmt (gsi);
508 gcc_assert (is_gimple_debug (debug));
509 /* Move debug binds anyway, but not anything else like begin-stmt
510 markers unless they are always valid at the destination. */
511 if (dest_single_pred_p
512 || gimple_debug_bind_p (debug))
514 gsi_move_before (&gsi, &gsi_to);
515 /* Reset debug-binds that are not always valid at the destination.
516 Simply dropping them can cause earlier values to become live,
517 generating wrong debug information.
518 ??? There are several things we could improve here. For
519 one we might be able to move stmts to the predecessor.
520 For anther, if the debug stmt is immediately followed by a
521 (debug) definition in the destination (on a post-dominated path?)
522 we can elide it without any bad effects. */
523 if (!dest_single_pred_p)
525 gimple_debug_bind_reset_value (debug);
526 update_stmt (debug);
529 else
530 gsi_next (&gsi);
534 /* Removes forwarder block BB. Returns false if this failed. */
536 static bool
537 remove_forwarder_block (basic_block bb)
539 edge succ = single_succ_edge (bb), e, s;
540 basic_block dest = succ->dest;
541 gimple *stmt;
542 edge_iterator ei;
543 gimple_stmt_iterator gsi, gsi_to;
545 /* We check for infinite loops already in tree_forwarder_block_p.
546 However it may happen that the infinite loop is created
547 afterwards due to removal of forwarders. */
548 if (dest == bb)
549 return false;
551 /* If the destination block consists of a nonlocal label or is a
552 EH landing pad, do not merge it. */
553 stmt = first_stmt (dest);
554 if (stmt)
555 if (glabel *label_stmt = dyn_cast <glabel *> (stmt))
556 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
557 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
558 return false;
560 /* If there is an abnormal edge to basic block BB, but not into
561 dest, problems might occur during removal of the phi node at out
562 of ssa due to overlapping live ranges of registers.
564 If there is an abnormal edge in DEST, the problems would occur
565 anyway since cleanup_dead_labels would then merge the labels for
566 two different eh regions, and rest of exception handling code
567 does not like it.
569 So if there is an abnormal edge to BB, proceed only if there is
570 no abnormal edge to DEST and there are no phi nodes in DEST. */
571 if (bb_has_abnormal_pred (bb)
572 && (bb_has_abnormal_pred (dest)
573 || !gimple_seq_empty_p (phi_nodes (dest))))
574 return false;
576 /* If there are phi nodes in DEST, and some of the blocks that are
577 predecessors of BB are also predecessors of DEST, check that the
578 phi node arguments match. */
579 if (!gimple_seq_empty_p (phi_nodes (dest)))
581 FOR_EACH_EDGE (e, ei, bb->preds)
583 s = find_edge (e->src, dest);
584 if (!s)
585 continue;
587 if (!phi_alternatives_equal (dest, succ, s))
588 return false;
592 basic_block pred = NULL;
593 if (single_pred_p (bb))
594 pred = single_pred (bb);
595 bool dest_single_pred_p = single_pred_p (dest);
597 /* Redirect the edges. */
598 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
600 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
602 if (e->flags & EDGE_ABNORMAL)
604 /* If there is an abnormal edge, redirect it anyway, and
605 move the labels to the new block to make it legal. */
606 s = redirect_edge_succ_nodup (e, dest);
608 else
609 s = redirect_edge_and_branch (e, dest);
611 if (s == e)
613 /* Create arguments for the phi nodes, since the edge was not
614 here before. */
615 for (gphi_iterator psi = gsi_start_phis (dest);
616 !gsi_end_p (psi);
617 gsi_next (&psi))
619 gphi *phi = psi.phi ();
620 location_t l = gimple_phi_arg_location_from_edge (phi, succ);
621 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
622 add_phi_arg (phi, unshare_expr (def), s, l);
627 /* Move nonlocal labels and computed goto targets as well as user
628 defined labels and labels with an EH landing pad number to the
629 new block, so that the redirection of the abnormal edges works,
630 jump targets end up in a sane place and debug information for
631 labels is retained. */
632 gsi_to = gsi_start_bb (dest);
633 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
635 stmt = gsi_stmt (gsi);
636 if (is_gimple_debug (stmt))
637 break;
639 /* Forwarder blocks can only contain labels and debug stmts, and
640 labels must come first, so if we get to this point, we know
641 we're looking at a label. */
642 tree decl = gimple_label_label (as_a <glabel *> (stmt));
643 if (EH_LANDING_PAD_NR (decl) != 0
644 || DECL_NONLOCAL (decl)
645 || FORCED_LABEL (decl)
646 || !DECL_ARTIFICIAL (decl))
647 gsi_move_before (&gsi, &gsi_to);
648 else
649 gsi_next (&gsi);
652 /* Move debug statements. Reset them if the destination does not
653 have a single predecessor. */
654 move_debug_stmts_from_forwarder (bb, dest, dest_single_pred_p,
655 pred, pred && single_succ_p (pred));
657 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
659 /* Update the dominators. */
660 if (dom_info_available_p (CDI_DOMINATORS))
662 basic_block dom, dombb, domdest;
664 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
665 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
666 if (domdest == bb)
668 /* Shortcut to avoid calling (relatively expensive)
669 nearest_common_dominator unless necessary. */
670 dom = dombb;
672 else
673 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
675 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
678 /* Adjust latch infomation of BB's parent loop as otherwise
679 the cfg hook has a hard time not to kill the loop. */
680 if (current_loops && bb->loop_father->latch == bb)
681 bb->loop_father->latch = pred;
683 /* And kill the forwarder block. */
684 delete_basic_block (bb);
686 return true;
689 /* STMT is a call that has been discovered noreturn. Split the
690 block to prepare fixing up the CFG and remove LHS.
691 Return true if cleanup-cfg needs to run. */
693 bool
694 fixup_noreturn_call (gimple *stmt)
696 basic_block bb = gimple_bb (stmt);
697 bool changed = false;
699 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
700 return false;
702 /* First split basic block if stmt is not last. */
703 if (stmt != gsi_stmt (gsi_last_bb (bb)))
705 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
707 /* Don't split if there are only debug stmts
708 after stmt, that can result in -fcompare-debug
709 failures. Remove the debug stmts instead,
710 they should be all unreachable anyway. */
711 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
712 for (gsi_next (&gsi); !gsi_end_p (gsi); )
713 gsi_remove (&gsi, true);
715 else
717 split_block (bb, stmt);
718 changed = true;
722 /* If there is an LHS, remove it, but only if its type has fixed size.
723 The LHS will need to be recreated during RTL expansion and creating
724 temporaries of variable-sized types is not supported. Also don't
725 do this with TREE_ADDRESSABLE types, as assign_temp will abort.
726 Drop LHS regardless of TREE_ADDRESSABLE, if the function call
727 has been changed into a call that does not return a value, like
728 __builtin_unreachable or __cxa_pure_virtual. */
729 tree lhs = gimple_call_lhs (stmt);
730 if (lhs
731 && (should_remove_lhs_p (lhs)
732 || VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))))
734 gimple_call_set_lhs (stmt, NULL_TREE);
736 /* We need to fix up the SSA name to avoid checking errors. */
737 if (TREE_CODE (lhs) == SSA_NAME)
739 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
740 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
741 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
742 set_ssa_default_def (cfun, new_var, lhs);
745 update_stmt (stmt);
748 /* Mark the call as altering control flow. */
749 if (!gimple_call_ctrl_altering_p (stmt))
751 gimple_call_set_ctrl_altering (stmt, true);
752 changed = true;
755 return changed;
758 /* Return true if we want to merge BB1 and BB2 into a single block. */
760 static bool
761 want_merge_blocks_p (basic_block bb1, basic_block bb2)
763 if (!can_merge_blocks_p (bb1, bb2))
764 return false;
765 gimple_stmt_iterator gsi = gsi_last_nondebug_bb (bb1);
766 if (gsi_end_p (gsi) || !stmt_can_terminate_bb_p (gsi_stmt (gsi)))
767 return true;
768 return bb1->count.ok_for_merging (bb2->count);
772 /* Tries to cleanup cfg in basic block BB by merging blocks. Returns
773 true if anything changes. */
775 static bool
776 cleanup_tree_cfg_bb (basic_block bb)
778 if (tree_forwarder_block_p (bb, false)
779 && remove_forwarder_block (bb))
780 return true;
782 /* If there is a merge opportunity with the predecessor
783 do nothing now but wait until we process the predecessor.
784 This happens when we visit BBs in a non-optimal order and
785 avoids quadratic behavior with adjusting stmts BB pointer. */
786 if (single_pred_p (bb)
787 && want_merge_blocks_p (single_pred (bb), bb))
788 /* But make sure we _do_ visit it. When we remove unreachable paths
789 ending in a backedge we fail to mark the destinations predecessors
790 as changed. */
791 bitmap_set_bit (cfgcleanup_altered_bbs, single_pred (bb)->index);
793 /* Merging the blocks may create new opportunities for folding
794 conditional branches (due to the elimination of single-valued PHI
795 nodes). */
796 else if (single_succ_p (bb)
797 && want_merge_blocks_p (bb, single_succ (bb)))
799 merge_blocks (bb, single_succ (bb));
800 return true;
803 return false;
806 /* Return true if E is an EDGE_ABNORMAL edge for returns_twice calls,
807 i.e. one going from .ABNORMAL_DISPATCHER to basic block which doesn't
808 start with a forced or nonlocal label. Calls which return twice can return
809 the second time only if they are called normally the first time, so basic
810 blocks which can be only entered through these abnormal edges but not
811 normally are effectively unreachable as well. Additionally ignore
812 __builtin_setjmp_receiver starting blocks, which have one FORCED_LABEL
813 and which are always only reachable through EDGE_ABNORMAL edge. They are
814 handled in cleanup_control_flow_pre. */
816 static bool
817 maybe_dead_abnormal_edge_p (edge e)
819 if ((e->flags & (EDGE_ABNORMAL | EDGE_EH)) != EDGE_ABNORMAL)
820 return false;
822 gimple_stmt_iterator gsi = gsi_start_nondebug_after_labels_bb (e->src);
823 gimple *g = gsi_stmt (gsi);
824 if (!g || !gimple_call_internal_p (g, IFN_ABNORMAL_DISPATCHER))
825 return false;
827 tree target = NULL_TREE;
828 for (gsi = gsi_start_bb (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
829 if (glabel *label_stmt = dyn_cast <glabel *> (gsi_stmt (gsi)))
831 tree this_target = gimple_label_label (label_stmt);
832 if (DECL_NONLOCAL (this_target))
833 return false;
834 if (FORCED_LABEL (this_target))
836 if (target)
837 return false;
838 target = this_target;
841 else
842 break;
844 if (target)
846 /* If there was a single FORCED_LABEL, check for
847 __builtin_setjmp_receiver with address of that label. */
848 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
849 gsi_next_nondebug (&gsi);
850 if (gsi_end_p (gsi))
851 return false;
852 if (!gimple_call_builtin_p (gsi_stmt (gsi), BUILT_IN_SETJMP_RECEIVER))
853 return false;
855 tree arg = gimple_call_arg (gsi_stmt (gsi), 0);
856 if (TREE_CODE (arg) != ADDR_EXPR || TREE_OPERAND (arg, 0) != target)
857 return false;
859 return true;
862 /* If BB is a basic block ending with __builtin_setjmp_setup, return edge
863 from .ABNORMAL_DISPATCHER basic block to corresponding
864 __builtin_setjmp_receiver basic block, otherwise return NULL. */
865 static edge
866 builtin_setjmp_setup_bb (basic_block bb)
868 if (EDGE_COUNT (bb->succs) != 2
869 || ((EDGE_SUCC (bb, 0)->flags
870 & (EDGE_ABNORMAL | EDGE_EH)) != EDGE_ABNORMAL
871 && (EDGE_SUCC (bb, 1)->flags
872 & (EDGE_ABNORMAL | EDGE_EH)) != EDGE_ABNORMAL))
873 return NULL;
875 gimple_stmt_iterator gsi = gsi_last_nondebug_bb (bb);
876 if (gsi_end_p (gsi)
877 || !gimple_call_builtin_p (gsi_stmt (gsi), BUILT_IN_SETJMP_SETUP))
878 return NULL;
880 tree arg = gimple_call_arg (gsi_stmt (gsi), 1);
881 if (TREE_CODE (arg) != ADDR_EXPR
882 || TREE_CODE (TREE_OPERAND (arg, 0)) != LABEL_DECL)
883 return NULL;
885 basic_block recv_bb = label_to_block (cfun, TREE_OPERAND (arg, 0));
886 if (EDGE_COUNT (recv_bb->preds) != 1
887 || (EDGE_PRED (recv_bb, 0)->flags
888 & (EDGE_ABNORMAL | EDGE_EH)) != EDGE_ABNORMAL
889 || (EDGE_SUCC (bb, 0)->dest != EDGE_PRED (recv_bb, 0)->src
890 && EDGE_SUCC (bb, 1)->dest != EDGE_PRED (recv_bb, 0)->src))
891 return NULL;
893 /* EDGE_PRED (recv_bb, 0)->src should be the .ABNORMAL_DISPATCHER bb. */
894 return EDGE_PRED (recv_bb, 0);
897 /* Do cleanup_control_flow_bb in PRE order. */
899 static bool
900 cleanup_control_flow_pre ()
902 bool retval = false;
904 /* We want remove_edge_and_dominated_blocks to only remove edges,
905 not dominated blocks which it does when dom info isn't available.
906 Pretend so. */
907 dom_state saved_state = dom_info_state (CDI_DOMINATORS);
908 set_dom_info_availability (CDI_DOMINATORS, DOM_NONE);
910 auto_vec<edge_iterator, 20> stack (n_basic_blocks_for_fn (cfun) + 2);
911 auto_sbitmap visited (last_basic_block_for_fn (cfun));
912 bitmap_clear (visited);
914 vec<edge, va_gc> *setjmp_vec = NULL;
915 auto_vec<basic_block, 4> abnormal_dispatchers;
917 stack.quick_push (ei_start (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs));
919 while (! stack.is_empty ())
921 /* Look at the edge on the top of the stack. */
922 edge_iterator ei = stack.last ();
923 basic_block dest = ei_edge (ei)->dest;
925 if (dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
926 && !bitmap_bit_p (visited, dest->index)
927 && (ei_container (ei) == setjmp_vec
928 || !maybe_dead_abnormal_edge_p (ei_edge (ei))))
930 bitmap_set_bit (visited, dest->index);
931 /* We only possibly remove edges from DEST here, leaving
932 possibly unreachable code in the IL. */
933 retval |= cleanup_control_flow_bb (dest);
935 /* Check for __builtin_setjmp_setup. Edges from .ABNORMAL_DISPATCH
936 to __builtin_setjmp_receiver will be normally ignored by
937 maybe_dead_abnormal_edge_p. If DEST is a visited
938 __builtin_setjmp_setup, queue edge from .ABNORMAL_DISPATCH
939 to __builtin_setjmp_receiver, so that it will be visited too. */
940 if (edge e = builtin_setjmp_setup_bb (dest))
942 vec_safe_push (setjmp_vec, e);
943 if (vec_safe_length (setjmp_vec) == 1)
944 stack.quick_push (ei_start (setjmp_vec));
947 if ((ei_edge (ei)->flags
948 & (EDGE_ABNORMAL | EDGE_EH)) == EDGE_ABNORMAL)
950 gimple_stmt_iterator gsi
951 = gsi_start_nondebug_after_labels_bb (dest);
952 gimple *g = gsi_stmt (gsi);
953 if (g && gimple_call_internal_p (g, IFN_ABNORMAL_DISPATCHER))
954 abnormal_dispatchers.safe_push (dest);
957 if (EDGE_COUNT (dest->succs) > 0)
958 stack.quick_push (ei_start (dest->succs));
960 else
962 if (!ei_one_before_end_p (ei))
963 ei_next (&stack.last ());
964 else
966 if (ei_container (ei) == setjmp_vec)
967 vec_safe_truncate (setjmp_vec, 0);
968 stack.pop ();
973 vec_free (setjmp_vec);
975 /* If we've marked .ABNORMAL_DISPATCHER basic block(s) as visited
976 above, but haven't marked any of their successors as visited,
977 unmark them now, so that they can be removed as useless. */
978 for (basic_block dispatcher_bb : abnormal_dispatchers)
980 edge e;
981 edge_iterator ei;
982 FOR_EACH_EDGE (e, ei, dispatcher_bb->succs)
983 if (bitmap_bit_p (visited, e->dest->index))
984 break;
985 if (e == NULL)
986 bitmap_clear_bit (visited, dispatcher_bb->index);
989 set_dom_info_availability (CDI_DOMINATORS, saved_state);
991 /* We are deleting BBs in non-reverse dominator order, make sure
992 insert_debug_temps_for_defs is prepared for that. */
993 if (retval)
994 free_dominance_info (CDI_DOMINATORS);
996 /* Remove all now (and previously) unreachable blocks. */
997 for (int i = NUM_FIXED_BLOCKS; i < last_basic_block_for_fn (cfun); ++i)
999 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
1000 if (bb && !bitmap_bit_p (visited, bb->index))
1002 if (!retval)
1003 free_dominance_info (CDI_DOMINATORS);
1004 delete_basic_block (bb);
1005 retval = true;
1009 return retval;
1012 static bool
1013 mfb_keep_latches (edge e)
1015 return !((dom_info_available_p (CDI_DOMINATORS)
1016 && dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1017 || (e->flags & EDGE_DFS_BACK));
1020 /* Remove unreachable blocks and other miscellaneous clean up work.
1021 Return true if the flowgraph was modified, false otherwise. */
1023 static bool
1024 cleanup_tree_cfg_noloop (unsigned ssa_update_flags)
1026 timevar_push (TV_TREE_CLEANUP_CFG);
1028 /* Ensure that we have single entries into loop headers. Otherwise
1029 if one of the entries is becoming a latch due to CFG cleanup
1030 (from formerly being part of an irreducible region) then we mess
1031 up loop fixup and associate the old loop with a different region
1032 which makes niter upper bounds invalid. See for example PR80549.
1033 This needs to be done before we remove trivially dead edges as
1034 we need to capture the dominance state before the pending transform. */
1035 if (current_loops)
1037 /* This needs backedges or dominators. */
1038 if (!dom_info_available_p (CDI_DOMINATORS))
1039 mark_dfs_back_edges ();
1041 for (loop_p loop : *get_loops (cfun))
1042 if (loop && loop->header)
1044 basic_block bb = loop->header;
1045 edge_iterator ei;
1046 edge e;
1047 bool found_latch = false;
1048 bool any_abnormal = false;
1049 unsigned n = 0;
1050 /* We are only interested in preserving existing loops, but
1051 we need to check whether they are still real and of course
1052 if we need to add a preheader at all. */
1053 FOR_EACH_EDGE (e, ei, bb->preds)
1055 if (e->flags & EDGE_ABNORMAL)
1057 any_abnormal = true;
1058 break;
1060 if ((dom_info_available_p (CDI_DOMINATORS)
1061 && dominated_by_p (CDI_DOMINATORS, e->src, bb))
1062 || (e->flags & EDGE_DFS_BACK))
1064 found_latch = true;
1065 continue;
1067 n++;
1069 /* If we have more than one entry to the loop header
1070 create a forwarder. */
1071 if (found_latch && ! any_abnormal && n > 1)
1073 edge fallthru = make_forwarder_block (bb, mfb_keep_latches,
1074 NULL);
1075 loop->header = fallthru->dest;
1076 if (! loops_state_satisfies_p (LOOPS_NEED_FIXUP))
1078 /* The loop updating from the CFG hook is incomplete
1079 when we have multiple latches, fixup manually. */
1080 remove_bb_from_loops (fallthru->src);
1081 loop_p cloop = loop;
1082 FOR_EACH_EDGE (e, ei, fallthru->src->preds)
1083 cloop = find_common_loop (cloop, e->src->loop_father);
1084 add_bb_to_loop (fallthru->src, cloop);
1090 /* Prepare the worklists of altered blocks. */
1091 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
1093 /* Start by iterating over all basic blocks in PRE order looking for
1094 edge removal opportunities. Do this first because incoming SSA form
1095 may be invalid and we want to avoid performing SSA related tasks such
1096 as propgating out a PHI node during BB merging in that state. This
1097 also gets rid of unreachable blocks. */
1098 bool changed = cleanup_control_flow_pre ();
1100 /* After doing the above SSA form should be valid (or an update SSA
1101 should be required). */
1102 if (ssa_update_flags)
1104 timevar_pop (TV_TREE_CLEANUP_CFG);
1105 update_ssa (ssa_update_flags);
1106 timevar_push (TV_TREE_CLEANUP_CFG);
1109 /* Compute dominator info which we need for the iterative process below. */
1110 if (!dom_info_available_p (CDI_DOMINATORS))
1111 calculate_dominance_info (CDI_DOMINATORS);
1112 else
1113 checking_verify_dominators (CDI_DOMINATORS);
1115 /* During forwarder block cleanup, we may redirect edges out of
1116 SWITCH_EXPRs, which can get expensive. So we want to enable
1117 recording of edge to CASE_LABEL_EXPR. */
1118 start_recording_case_labels ();
1120 /* Continue by iterating over all basic blocks looking for BB merging
1121 opportunities. We cannot use FOR_EACH_BB_FN for the BB iteration
1122 since the basic blocks may get removed. */
1123 unsigned n = last_basic_block_for_fn (cfun);
1124 for (unsigned i = NUM_FIXED_BLOCKS; i < n; i++)
1126 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
1127 if (bb)
1128 changed |= cleanup_tree_cfg_bb (bb);
1131 /* Now process the altered blocks, as long as any are available. */
1132 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
1134 unsigned i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
1135 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
1136 if (i < NUM_FIXED_BLOCKS)
1137 continue;
1139 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
1140 if (!bb)
1141 continue;
1143 /* BB merging done by cleanup_tree_cfg_bb can end up propagating
1144 out single-argument PHIs which in turn can expose
1145 cleanup_control_flow_bb opportunities so we have to repeat
1146 that here. */
1147 changed |= cleanup_control_flow_bb (bb);
1148 changed |= cleanup_tree_cfg_bb (bb);
1151 end_recording_case_labels ();
1152 BITMAP_FREE (cfgcleanup_altered_bbs);
1154 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
1156 /* Do not renumber blocks if the SCEV cache is active, it is indexed by
1157 basic-block numbers. */
1158 if (! scev_initialized_p ())
1159 compact_blocks ();
1161 checking_verify_flow_info ();
1163 timevar_pop (TV_TREE_CLEANUP_CFG);
1165 if (changed && current_loops)
1167 /* Removing edges and/or blocks may make recorded bounds refer
1168 to stale GIMPLE stmts now, so clear them. */
1169 free_numbers_of_iterations_estimates (cfun);
1170 loops_state_set (LOOPS_NEED_FIXUP);
1173 return changed;
1176 /* Repairs loop structures. */
1178 static void
1179 repair_loop_structures (void)
1181 bitmap changed_bbs;
1182 unsigned n_new_or_deleted_loops;
1184 calculate_dominance_info (CDI_DOMINATORS);
1186 timevar_push (TV_REPAIR_LOOPS);
1187 changed_bbs = BITMAP_ALLOC (NULL);
1188 n_new_or_deleted_loops = fix_loop_structure (changed_bbs);
1190 /* This usually does nothing. But sometimes parts of cfg that originally
1191 were inside a loop get out of it due to edge removal (since they
1192 become unreachable by back edges from latch). Also a former
1193 irreducible loop can become reducible - in this case force a full
1194 rewrite into loop-closed SSA form. */
1195 if (loops_state_satisfies_p (LOOP_CLOSED_SSA)
1196 && (!bitmap_empty_p (changed_bbs) || n_new_or_deleted_loops))
1197 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1199 BITMAP_FREE (changed_bbs);
1201 checking_verify_loop_structure ();
1202 scev_reset ();
1204 timevar_pop (TV_REPAIR_LOOPS);
1207 /* Cleanup cfg and repair loop structures. */
1209 bool
1210 cleanup_tree_cfg (unsigned ssa_update_flags)
1212 bool changed = cleanup_tree_cfg_noloop (ssa_update_flags);
1214 if (current_loops != NULL
1215 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
1216 repair_loop_structures ();
1218 return changed;
1221 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
1222 Returns true if successful. */
1224 static bool
1225 remove_forwarder_block_with_phi (basic_block bb)
1227 edge succ = single_succ_edge (bb);
1228 basic_block dest = succ->dest;
1229 gimple *label;
1230 basic_block dombb, domdest, dom;
1232 /* We check for infinite loops already in tree_forwarder_block_p.
1233 However it may happen that the infinite loop is created
1234 afterwards due to removal of forwarders. */
1235 if (dest == bb)
1236 return false;
1238 /* Removal of forwarders may expose new natural loops and thus
1239 a block may turn into a loop header. */
1240 if (current_loops && bb_loop_header_p (bb))
1241 return false;
1243 /* If the destination block consists of a nonlocal label, do not
1244 merge it. */
1245 label = first_stmt (dest);
1246 if (label)
1247 if (glabel *label_stmt = dyn_cast <glabel *> (label))
1248 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
1249 return false;
1251 /* Record BB's single pred in case we need to update the father
1252 loop's latch information later. */
1253 basic_block pred = NULL;
1254 if (single_pred_p (bb))
1255 pred = single_pred (bb);
1256 bool dest_single_pred_p = single_pred_p (dest);
1258 /* Redirect each incoming edge to BB to DEST. */
1259 while (EDGE_COUNT (bb->preds) > 0)
1261 edge e = EDGE_PRED (bb, 0), s;
1262 gphi_iterator gsi;
1264 s = find_edge (e->src, dest);
1265 if (s)
1267 /* We already have an edge S from E->src to DEST. If S and
1268 E->dest's sole successor edge have the same PHI arguments
1269 at DEST, redirect S to DEST. */
1270 if (phi_alternatives_equal (dest, s, succ))
1272 e = redirect_edge_and_branch (e, dest);
1273 redirect_edge_var_map_clear (e);
1274 continue;
1277 /* PHI arguments are different. Create a forwarder block by
1278 splitting E so that we can merge PHI arguments on E to
1279 DEST. */
1280 e = single_succ_edge (split_edge (e));
1282 else
1284 /* If we merge the forwarder into a loop header verify if we
1285 are creating another loop latch edge. If so, reset
1286 number of iteration information of the loop. */
1287 if (dest->loop_father->header == dest
1288 && dominated_by_p (CDI_DOMINATORS, e->src, dest))
1290 dest->loop_father->any_upper_bound = false;
1291 dest->loop_father->any_likely_upper_bound = false;
1292 free_numbers_of_iterations_estimates (dest->loop_father);
1296 s = redirect_edge_and_branch (e, dest);
1298 /* redirect_edge_and_branch must not create a new edge. */
1299 gcc_assert (s == e);
1301 /* Add to the PHI nodes at DEST each PHI argument removed at the
1302 destination of E. */
1303 for (gsi = gsi_start_phis (dest);
1304 !gsi_end_p (gsi);
1305 gsi_next (&gsi))
1307 gphi *phi = gsi.phi ();
1308 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
1309 location_t locus = gimple_phi_arg_location_from_edge (phi, succ);
1311 if (TREE_CODE (def) == SSA_NAME)
1313 /* If DEF is one of the results of PHI nodes removed during
1314 redirection, replace it with the PHI argument that used
1315 to be on E. */
1316 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
1317 size_t length = head ? head->length () : 0;
1318 for (size_t i = 0; i < length; i++)
1320 edge_var_map *vm = &(*head)[i];
1321 tree old_arg = redirect_edge_var_map_result (vm);
1322 tree new_arg = redirect_edge_var_map_def (vm);
1324 if (def == old_arg)
1326 def = new_arg;
1327 locus = redirect_edge_var_map_location (vm);
1328 break;
1333 add_phi_arg (phi, def, s, locus);
1336 redirect_edge_var_map_clear (e);
1339 /* Move debug statements. Reset them if the destination does not
1340 have a single predecessor. */
1341 move_debug_stmts_from_forwarder (bb, dest, dest_single_pred_p,
1342 pred, pred && single_succ_p (pred));
1344 /* Update the dominators. */
1345 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
1346 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
1347 if (domdest == bb)
1349 /* Shortcut to avoid calling (relatively expensive)
1350 nearest_common_dominator unless necessary. */
1351 dom = dombb;
1353 else
1354 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
1356 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
1358 /* Adjust latch infomation of BB's parent loop as otherwise
1359 the cfg hook has a hard time not to kill the loop. */
1360 if (current_loops && bb->loop_father->latch == bb)
1361 bb->loop_father->latch = pred;
1363 /* Remove BB since all of BB's incoming edges have been redirected
1364 to DEST. */
1365 delete_basic_block (bb);
1367 return true;
1370 /* This pass merges PHI nodes if one feeds into another. For example,
1371 suppose we have the following:
1373 goto <bb 9> (<L9>);
1375 <L8>:;
1376 tem_17 = foo ();
1378 # tem_6 = PHI <tem_17(8), tem_23(7)>;
1379 <L9>:;
1381 # tem_3 = PHI <tem_6(9), tem_2(5)>;
1382 <L10>:;
1384 Then we merge the first PHI node into the second one like so:
1386 goto <bb 9> (<L10>);
1388 <L8>:;
1389 tem_17 = foo ();
1391 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
1392 <L10>:;
1395 namespace {
1397 const pass_data pass_data_merge_phi =
1399 GIMPLE_PASS, /* type */
1400 "mergephi", /* name */
1401 OPTGROUP_NONE, /* optinfo_flags */
1402 TV_TREE_MERGE_PHI, /* tv_id */
1403 ( PROP_cfg | PROP_ssa ), /* properties_required */
1404 0, /* properties_provided */
1405 0, /* properties_destroyed */
1406 0, /* todo_flags_start */
1407 0, /* todo_flags_finish */
1410 class pass_merge_phi : public gimple_opt_pass
1412 public:
1413 pass_merge_phi (gcc::context *ctxt)
1414 : gimple_opt_pass (pass_data_merge_phi, ctxt)
1417 /* opt_pass methods: */
1418 opt_pass * clone () final override { return new pass_merge_phi (m_ctxt); }
1419 unsigned int execute (function *) final override;
1421 }; // class pass_merge_phi
1423 unsigned int
1424 pass_merge_phi::execute (function *fun)
1426 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
1427 basic_block *current = worklist;
1428 basic_block bb;
1430 calculate_dominance_info (CDI_DOMINATORS);
1432 /* Find all PHI nodes that we may be able to merge. */
1433 FOR_EACH_BB_FN (bb, fun)
1435 basic_block dest;
1437 /* Look for a forwarder block with PHI nodes. */
1438 if (!tree_forwarder_block_p (bb, true))
1439 continue;
1441 dest = single_succ (bb);
1443 /* We have to feed into another basic block with PHI
1444 nodes. */
1445 if (gimple_seq_empty_p (phi_nodes (dest))
1446 /* We don't want to deal with a basic block with
1447 abnormal edges. */
1448 || bb_has_abnormal_pred (bb))
1449 continue;
1451 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1453 /* If BB does not dominate DEST, then the PHI nodes at
1454 DEST must be the only users of the results of the PHI
1455 nodes at BB. */
1456 *current++ = bb;
1458 else
1460 gphi_iterator gsi;
1461 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1463 /* BB dominates DEST. There may be many users of the PHI
1464 nodes in BB. However, there is still a trivial case we
1465 can handle. If the result of every PHI in BB is used
1466 only by a PHI in DEST, then we can trivially merge the
1467 PHI nodes from BB into DEST. */
1468 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1469 gsi_next (&gsi))
1471 gphi *phi = gsi.phi ();
1472 tree result = gimple_phi_result (phi);
1473 use_operand_p imm_use;
1474 gimple *use_stmt;
1476 /* If the PHI's result is never used, then we can just
1477 ignore it. */
1478 if (has_zero_uses (result))
1479 continue;
1481 /* Get the single use of the result of this PHI node. */
1482 if (!single_imm_use (result, &imm_use, &use_stmt)
1483 || gimple_code (use_stmt) != GIMPLE_PHI
1484 || gimple_bb (use_stmt) != dest
1485 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1486 break;
1489 /* If the loop above iterated through all the PHI nodes
1490 in BB, then we can merge the PHIs from BB into DEST. */
1491 if (gsi_end_p (gsi))
1492 *current++ = bb;
1496 /* Now let's drain WORKLIST. */
1497 bool changed = false;
1498 while (current != worklist)
1500 bb = *--current;
1501 changed |= remove_forwarder_block_with_phi (bb);
1503 free (worklist);
1505 /* Removing forwarder blocks can cause formerly irreducible loops
1506 to become reducible if we merged two entry blocks. */
1507 if (changed
1508 && current_loops)
1509 loops_state_set (LOOPS_NEED_FIXUP);
1511 return 0;
1514 } // anon namespace
1516 gimple_opt_pass *
1517 make_pass_merge_phi (gcc::context *ctxt)
1519 return new pass_merge_phi (ctxt);
1522 /* Pass: cleanup the CFG just before expanding trees to RTL.
1523 This is just a round of label cleanups and case node grouping
1524 because after the tree optimizers have run such cleanups may
1525 be necessary. */
1527 static unsigned int
1528 execute_cleanup_cfg_post_optimizing (void)
1530 unsigned int todo = execute_fixup_cfg ();
1531 if (cleanup_tree_cfg ())
1533 todo &= ~TODO_cleanup_cfg;
1534 todo |= TODO_update_ssa;
1536 maybe_remove_unreachable_handlers ();
1537 cleanup_dead_labels ();
1538 if (group_case_labels ())
1539 todo |= TODO_cleanup_cfg;
1540 if ((flag_compare_debug_opt || flag_compare_debug)
1541 && flag_dump_final_insns)
1543 FILE *final_output = fopen (flag_dump_final_insns, "a");
1545 if (!final_output)
1547 error ("could not open final insn dump file %qs: %m",
1548 flag_dump_final_insns);
1549 flag_dump_final_insns = NULL;
1551 else
1553 int save_unnumbered = flag_dump_unnumbered;
1554 int save_noaddr = flag_dump_noaddr;
1556 flag_dump_noaddr = flag_dump_unnumbered = 1;
1557 fprintf (final_output, "\n");
1558 dump_enumerated_decls (final_output,
1559 dump_flags | TDF_SLIM | TDF_NOUID);
1560 flag_dump_noaddr = save_noaddr;
1561 flag_dump_unnumbered = save_unnumbered;
1562 if (fclose (final_output))
1564 error ("could not close final insn dump file %qs: %m",
1565 flag_dump_final_insns);
1566 flag_dump_final_insns = NULL;
1570 return todo;
1573 namespace {
1575 const pass_data pass_data_cleanup_cfg_post_optimizing =
1577 GIMPLE_PASS, /* type */
1578 "optimized", /* name */
1579 OPTGROUP_NONE, /* optinfo_flags */
1580 TV_TREE_CLEANUP_CFG, /* tv_id */
1581 PROP_cfg, /* properties_required */
1582 0, /* properties_provided */
1583 0, /* properties_destroyed */
1584 0, /* todo_flags_start */
1585 TODO_remove_unused_locals, /* todo_flags_finish */
1588 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1590 public:
1591 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1592 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1595 /* opt_pass methods: */
1596 unsigned int execute (function *) final override
1598 return execute_cleanup_cfg_post_optimizing ();
1601 }; // class pass_cleanup_cfg_post_optimizing
1603 } // anon namespace
1605 gimple_opt_pass *
1606 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1608 return new pass_cleanup_cfg_post_optimizing (ctxt);
1612 /* Delete all unreachable basic blocks and update callgraph.
1613 Doing so is somewhat nontrivial because we need to update all clones and
1614 remove inline function that become unreachable. */
1616 bool
1617 delete_unreachable_blocks_update_callgraph (cgraph_node *dst_node,
1618 bool update_clones)
1620 bool changed = false;
1621 basic_block b, next_bb;
1623 find_unreachable_blocks ();
1625 /* Delete all unreachable basic blocks. */
1627 for (b = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; b
1628 != EXIT_BLOCK_PTR_FOR_FN (cfun); b = next_bb)
1630 next_bb = b->next_bb;
1632 if (!(b->flags & BB_REACHABLE))
1634 gimple_stmt_iterator bsi;
1636 for (bsi = gsi_start_bb (b); !gsi_end_p (bsi); gsi_next (&bsi))
1638 struct cgraph_edge *e;
1639 struct cgraph_node *node;
1641 dst_node->remove_stmt_references (gsi_stmt (bsi));
1643 if (gimple_code (gsi_stmt (bsi)) == GIMPLE_CALL
1644 &&(e = dst_node->get_edge (gsi_stmt (bsi))) != NULL)
1646 if (!e->inline_failed)
1647 e->callee->remove_symbol_and_inline_clones (dst_node);
1648 else
1649 cgraph_edge::remove (e);
1651 if (update_clones && dst_node->clones)
1652 for (node = dst_node->clones; node != dst_node;)
1654 node->remove_stmt_references (gsi_stmt (bsi));
1655 if (gimple_code (gsi_stmt (bsi)) == GIMPLE_CALL
1656 && (e = node->get_edge (gsi_stmt (bsi))) != NULL)
1658 if (!e->inline_failed)
1659 e->callee->remove_symbol_and_inline_clones (dst_node);
1660 else
1661 cgraph_edge::remove (e);
1664 if (node->clones)
1665 node = node->clones;
1666 else if (node->next_sibling_clone)
1667 node = node->next_sibling_clone;
1668 else
1670 while (node != dst_node && !node->next_sibling_clone)
1671 node = node->clone_of;
1672 if (node != dst_node)
1673 node = node->next_sibling_clone;
1677 delete_basic_block (b);
1678 changed = true;
1682 return changed;