10bb22b91SFlorian Hahn //===- SimplifyCFG.cpp ----------------------------------------------------===//
20bb22b91SFlorian Hahn //
30bb22b91SFlorian Hahn //
40bb22b91SFlorian Hahn // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
50bb22b91SFlorian Hahn // See https://llvm.org/LICENSE.txt for license information.
60bb22b91SFlorian Hahn // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
70bb22b91SFlorian Hahn //
80bb22b91SFlorian Hahn //===----------------------------------------------------------------------===//
90bb22b91SFlorian Hahn //
100bb22b91SFlorian Hahn // This file implements the control flow graph (CFG) simplifications
110bb22b91SFlorian Hahn // presented as part of the 'Getting Started With LLVM: Basics' tutorial at the
120bb22b91SFlorian Hahn // US LLVM Developers Meeting 2019. It also contains additional material.
130bb22b91SFlorian Hahn //
140bb22b91SFlorian Hahn // The current file contains three different CFG simplifications. There are
150bb22b91SFlorian Hahn // multiple versions of each implementation (e.g. _v1 and _v2), which implement
160bb22b91SFlorian Hahn // additional functionality (e.g. preserving analysis like the DominatorTree) or
170bb22b91SFlorian Hahn // use additional utilities to simplify the code (e.g. LLVM's PatternMatch.h).
180bb22b91SFlorian Hahn // The available simplifications are:
190bb22b91SFlorian Hahn // 1. Trivially Dead block Removal (removeDeadBlocks_v[1,2]).
200bb22b91SFlorian Hahn // This simplifications removes all blocks without predecessors in the CFG
210bb22b91SFlorian Hahn // from a function.
220bb22b91SFlorian Hahn // 2. Conditional Branch Elimination (eliminateCondBranches_v[1,2,3])
230bb22b91SFlorian Hahn // This simplification replaces conditional branches with constant integer
240bb22b91SFlorian Hahn // conditions with unconditional branches.
250bb22b91SFlorian Hahn // 3. Single Predecessor Block Merging (mergeIntoSinglePredecessor_v[1,2])
260bb22b91SFlorian Hahn // This simplification merges blocks with a single predecessor into the
270bb22b91SFlorian Hahn // predecessor, if that block has a single successor.
280bb22b91SFlorian Hahn //
290bb22b91SFlorian Hahn // TODOs
300bb22b91SFlorian Hahn // * Hook up pass to the new pass manager.
310bb22b91SFlorian Hahn // * Preserve LoopInfo.
320bb22b91SFlorian Hahn // * Add fixed point iteration to delete all dead blocks
330bb22b91SFlorian Hahn // * Add implementation using reachability to discover dead blocks.
340bb22b91SFlorian Hahn //===----------------------------------------------------------------------===//
350bb22b91SFlorian Hahn
360bb22b91SFlorian Hahn #include "SimplifyCFG.h"
370bb22b91SFlorian Hahn #include "InitializePasses.h"
380bb22b91SFlorian Hahn #include "llvm/Analysis/DomTreeUpdater.h"
390bb22b91SFlorian Hahn #include "llvm/IR/Dominators.h"
400bb22b91SFlorian Hahn #include "llvm/IR/Function.h"
410bb22b91SFlorian Hahn #include "llvm/IR/PassManager.h"
420bb22b91SFlorian Hahn #include "llvm/IR/PatternMatch.h"
430bb22b91SFlorian Hahn #include "llvm/InitializePasses.h"
440bb22b91SFlorian Hahn #include "llvm/Support/CommandLine.h"
450bb22b91SFlorian Hahn
460bb22b91SFlorian Hahn using namespace llvm;
470bb22b91SFlorian Hahn using namespace PatternMatch;
480bb22b91SFlorian Hahn
490bb22b91SFlorian Hahn enum TutorialVersion { V1, V2, V3 };
500bb22b91SFlorian Hahn static cl::opt<TutorialVersion>
510bb22b91SFlorian Hahn Version("tut-simplifycfg-version", cl::desc("Select tutorial version"),
520bb22b91SFlorian Hahn cl::Hidden, cl::ValueOptional, cl::init(V1),
530bb22b91SFlorian Hahn cl::values(clEnumValN(V1, "v1", "version 1"),
540bb22b91SFlorian Hahn clEnumValN(V2, "v2", "version 2"),
550bb22b91SFlorian Hahn clEnumValN(V3, "v3", "version 3"),
560bb22b91SFlorian Hahn // Sentinel value for unspecified option.
570bb22b91SFlorian Hahn clEnumValN(V3, "", "")));
580bb22b91SFlorian Hahn
590bb22b91SFlorian Hahn #define DEBUG_TYPE "tut-simplifycfg"
600bb22b91SFlorian Hahn
610bb22b91SFlorian Hahn // Remove trivially dead blocks. First version, not preserving the
620bb22b91SFlorian Hahn // DominatorTree.
removeDeadBlocks_v1(Function & F)630bb22b91SFlorian Hahn static bool removeDeadBlocks_v1(Function &F) {
640bb22b91SFlorian Hahn bool Changed = false;
650bb22b91SFlorian Hahn
660bb22b91SFlorian Hahn // Remove trivially dead blocks.
670bb22b91SFlorian Hahn for (BasicBlock &BB : make_early_inc_range(F)) {
680bb22b91SFlorian Hahn // Skip blocks we know to not be trivially dead. We know a block is
690bb22b91SFlorian Hahn // guaranteed to be dead, iff it is neither the entry block nor
700bb22b91SFlorian Hahn // has any predecessors.
710bb22b91SFlorian Hahn if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
720bb22b91SFlorian Hahn continue;
730bb22b91SFlorian Hahn
740bb22b91SFlorian Hahn // Notify successors of BB that BB is going to be removed. This removes
750bb22b91SFlorian Hahn // incoming values from BB from PHIs in the successors. Note that this will
760bb22b91SFlorian Hahn // not actually remove BB from the predecessor lists of its successors.
770bb22b91SFlorian Hahn for (BasicBlock *Succ : successors(&BB))
780bb22b91SFlorian Hahn Succ->removePredecessor(&BB);
790bb22b91SFlorian Hahn // TODO: Find a better place to put such small variations.
800bb22b91SFlorian Hahn // Alternatively, we can update the PHI nodes manually:
810bb22b91SFlorian Hahn // for (PHINode &PN : make_early_inc_range(Succ->phis()))
820bb22b91SFlorian Hahn // PN.removeIncomingValue(&BB);
830bb22b91SFlorian Hahn
840bb22b91SFlorian Hahn // Replace all instructions in BB with an undef constant. The block is
850bb22b91SFlorian Hahn // unreachable, so the results of the instructions should never get used.
860bb22b91SFlorian Hahn while (!BB.empty()) {
870bb22b91SFlorian Hahn Instruction &I = BB.back();
880bb22b91SFlorian Hahn I.replaceAllUsesWith(UndefValue::get(I.getType()));
890bb22b91SFlorian Hahn I.eraseFromParent();
900bb22b91SFlorian Hahn }
910bb22b91SFlorian Hahn
920bb22b91SFlorian Hahn // Finally remove the basic block.
930bb22b91SFlorian Hahn BB.eraseFromParent();
940bb22b91SFlorian Hahn Changed = true;
950bb22b91SFlorian Hahn }
960bb22b91SFlorian Hahn
970bb22b91SFlorian Hahn return Changed;
980bb22b91SFlorian Hahn }
990bb22b91SFlorian Hahn
1000bb22b91SFlorian Hahn // Remove trivially dead blocks. This is the second version and preserves the
1010bb22b91SFlorian Hahn // dominator tree.
removeDeadBlocks_v2(Function & F,DominatorTree & DT)1020bb22b91SFlorian Hahn static bool removeDeadBlocks_v2(Function &F, DominatorTree &DT) {
1030bb22b91SFlorian Hahn bool Changed = false;
1040bb22b91SFlorian Hahn DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1050bb22b91SFlorian Hahn SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1060bb22b91SFlorian Hahn
1070bb22b91SFlorian Hahn // Remove trivially dead blocks.
1080bb22b91SFlorian Hahn for (BasicBlock &BB : make_early_inc_range(F)) {
1090bb22b91SFlorian Hahn // Skip blocks we know to not be trivially dead. We know a block is
1100bb22b91SFlorian Hahn // guaranteed to be dead, iff it is neither the entry block nor
1110bb22b91SFlorian Hahn // has any predecessors.
1120bb22b91SFlorian Hahn if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
1130bb22b91SFlorian Hahn continue;
1140bb22b91SFlorian Hahn
1150bb22b91SFlorian Hahn // Notify successors of BB that BB is going to be removed. This removes
1160bb22b91SFlorian Hahn // incoming values from BB from PHIs in the successors. Note that this will
1170bb22b91SFlorian Hahn // not actually remove BB from the predecessor lists of its successors.
1180bb22b91SFlorian Hahn for (BasicBlock *Succ : successors(&BB)) {
1190bb22b91SFlorian Hahn Succ->removePredecessor(&BB);
1200bb22b91SFlorian Hahn
1210bb22b91SFlorian Hahn // Collect updates that need to be applied to the dominator tree.
1220bb22b91SFlorian Hahn DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
1230bb22b91SFlorian Hahn }
1240bb22b91SFlorian Hahn
1250bb22b91SFlorian Hahn // Remove BB via the DomTreeUpdater. DomTreeUpdater::deleteBB conveniently
1260bb22b91SFlorian Hahn // removes the instructions in BB as well.
1270bb22b91SFlorian Hahn DTU.deleteBB(&BB);
1280bb22b91SFlorian Hahn Changed = true;
1290bb22b91SFlorian Hahn }
1300bb22b91SFlorian Hahn
1310bb22b91SFlorian Hahn // Apply updates permissively, to remove duplicates.
1320bb22b91SFlorian Hahn DTU.applyUpdatesPermissive(DTUpdates);
1330bb22b91SFlorian Hahn
1340bb22b91SFlorian Hahn return Changed;
1350bb22b91SFlorian Hahn }
1360bb22b91SFlorian Hahn
1370bb22b91SFlorian Hahn // Eliminate branches with constant conditionals. This is the first version,
1380bb22b91SFlorian Hahn // which *does not* preserve the dominator tree.
eliminateCondBranches_v1(Function & F)1390bb22b91SFlorian Hahn static bool eliminateCondBranches_v1(Function &F) {
1400bb22b91SFlorian Hahn bool Changed = false;
1410bb22b91SFlorian Hahn
1420bb22b91SFlorian Hahn // Eliminate branches with constant conditionals.
1430bb22b91SFlorian Hahn for (BasicBlock &BB : F) {
1440bb22b91SFlorian Hahn // Skip blocks without conditional branches as terminators.
1450bb22b91SFlorian Hahn BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
1460bb22b91SFlorian Hahn if (!BI || !BI->isConditional())
1470bb22b91SFlorian Hahn continue;
1480bb22b91SFlorian Hahn
1490bb22b91SFlorian Hahn // Skip blocks with conditional branches without ConstantInt conditions.
1500bb22b91SFlorian Hahn ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
1510bb22b91SFlorian Hahn if (!CI)
1520bb22b91SFlorian Hahn continue;
1530bb22b91SFlorian Hahn
1540bb22b91SFlorian Hahn // We use the branch condition (CI), to select the successor we remove:
1550bb22b91SFlorian Hahn // if CI == 1 (true), we remove the second successor, otherwise the first.
1560bb22b91SFlorian Hahn BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
1570bb22b91SFlorian Hahn // Tell RemovedSucc we will remove BB from its predecessors.
1580bb22b91SFlorian Hahn RemovedSucc->removePredecessor(&BB);
1590bb22b91SFlorian Hahn
1600bb22b91SFlorian Hahn // Replace the conditional branch with an unconditional one, by creating
1610bb22b91SFlorian Hahn // a new unconditional branch to the selected successor and removing the
1620bb22b91SFlorian Hahn // conditional one.
1630bb22b91SFlorian Hahn BranchInst::Create(BI->getSuccessor(CI->isZero()), BI);
1640bb22b91SFlorian Hahn BI->eraseFromParent();
1650bb22b91SFlorian Hahn Changed = true;
1660bb22b91SFlorian Hahn }
1670bb22b91SFlorian Hahn
1680bb22b91SFlorian Hahn return Changed;
1690bb22b91SFlorian Hahn }
1700bb22b91SFlorian Hahn
1710bb22b91SFlorian Hahn // Eliminate branches with constant conditionals. This is the second
1720bb22b91SFlorian Hahn // version, which *does* preserve the dominator tree.
eliminateCondBranches_v2(Function & F,DominatorTree & DT)1730bb22b91SFlorian Hahn static bool eliminateCondBranches_v2(Function &F, DominatorTree &DT) {
1740bb22b91SFlorian Hahn bool Changed = false;
1750bb22b91SFlorian Hahn
1760bb22b91SFlorian Hahn DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1770bb22b91SFlorian Hahn SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1780bb22b91SFlorian Hahn // Eliminate branches with constant conditionals.
1790bb22b91SFlorian Hahn for (BasicBlock &BB : F) {
1800bb22b91SFlorian Hahn // Skip blocks without conditional branches as terminators.
1810bb22b91SFlorian Hahn BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
1820bb22b91SFlorian Hahn if (!BI || !BI->isConditional())
1830bb22b91SFlorian Hahn continue;
1840bb22b91SFlorian Hahn
1850bb22b91SFlorian Hahn // Skip blocks with conditional branches without ConstantInt conditions.
1860bb22b91SFlorian Hahn ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
1870bb22b91SFlorian Hahn if (!CI)
1880bb22b91SFlorian Hahn continue;
1890bb22b91SFlorian Hahn
1900bb22b91SFlorian Hahn // We use the branch condition (CI), to select the successor we remove:
1910bb22b91SFlorian Hahn // if CI == 1 (true), we remove the second successor, otherwise the first.
1920bb22b91SFlorian Hahn BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
1930bb22b91SFlorian Hahn // Tell RemovedSucc we will remove BB from its predecessors.
1940bb22b91SFlorian Hahn RemovedSucc->removePredecessor(&BB);
1950bb22b91SFlorian Hahn
1960bb22b91SFlorian Hahn // Replace the conditional branch with an unconditional one, by creating
1970bb22b91SFlorian Hahn // a new unconditional branch to the selected successor and removing the
1980bb22b91SFlorian Hahn // conditional one.
1990bb22b91SFlorian Hahn BranchInst *NewBranch =
2000bb22b91SFlorian Hahn BranchInst::Create(BI->getSuccessor(CI->isZero()), BI);
2010bb22b91SFlorian Hahn BI->eraseFromParent();
2020bb22b91SFlorian Hahn
2030bb22b91SFlorian Hahn // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
2040bb22b91SFlorian Hahn // the conditional branch did not use RemovedSucc as both the true and false
2050bb22b91SFlorian Hahn // branches.
2060bb22b91SFlorian Hahn if (NewBranch->getSuccessor(0) != RemovedSucc)
2070bb22b91SFlorian Hahn DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
2080bb22b91SFlorian Hahn Changed = true;
2090bb22b91SFlorian Hahn }
2100bb22b91SFlorian Hahn
2110bb22b91SFlorian Hahn // Apply updates permissively, to remove duplicates.
2120bb22b91SFlorian Hahn DTU.applyUpdatesPermissive(DTUpdates);
2130bb22b91SFlorian Hahn
2140bb22b91SFlorian Hahn return Changed;
2150bb22b91SFlorian Hahn }
2160bb22b91SFlorian Hahn
2170bb22b91SFlorian Hahn // Eliminate branches with constant conditionals. This is the third
2180bb22b91SFlorian Hahn // version, which uses PatternMatch.h.
eliminateCondBranches_v3(Function & F,DominatorTree & DT)2190bb22b91SFlorian Hahn static bool eliminateCondBranches_v3(Function &F, DominatorTree &DT) {
2200bb22b91SFlorian Hahn bool Changed = false;
2210bb22b91SFlorian Hahn DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2220bb22b91SFlorian Hahn SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
2230bb22b91SFlorian Hahn
2240bb22b91SFlorian Hahn // Eliminate branches with constant conditionals.
2250bb22b91SFlorian Hahn for (BasicBlock &BB : F) {
2260bb22b91SFlorian Hahn ConstantInt *CI = nullptr;
2270bb22b91SFlorian Hahn BasicBlock *TakenSucc, *RemovedSucc;
2280bb22b91SFlorian Hahn // Check if the terminator is a conditional branch, with constant integer
2290bb22b91SFlorian Hahn // condition and also capture the successor blocks as TakenSucc and
2300bb22b91SFlorian Hahn // RemovedSucc.
2310bb22b91SFlorian Hahn if (!match(BB.getTerminator(),
2320bb22b91SFlorian Hahn m_Br(m_ConstantInt(CI), m_BasicBlock(TakenSucc),
2330bb22b91SFlorian Hahn m_BasicBlock(RemovedSucc))))
2340bb22b91SFlorian Hahn continue;
2350bb22b91SFlorian Hahn
2360bb22b91SFlorian Hahn // If the condition is false, swap TakenSucc and RemovedSucc.
2370bb22b91SFlorian Hahn if (CI->isZero())
2380bb22b91SFlorian Hahn std::swap(TakenSucc, RemovedSucc);
2390bb22b91SFlorian Hahn
2400bb22b91SFlorian Hahn // Tell RemovedSucc we will remove BB from its predecessors.
2410bb22b91SFlorian Hahn RemovedSucc->removePredecessor(&BB);
2420bb22b91SFlorian Hahn
2430bb22b91SFlorian Hahn // Replace the conditional branch with an unconditional one, by creating
2440bb22b91SFlorian Hahn // a new unconditional branch to the selected successor and removing the
2450bb22b91SFlorian Hahn // conditional one.
2460bb22b91SFlorian Hahn
2470bb22b91SFlorian Hahn BranchInst *NewBranch = BranchInst::Create(TakenSucc, BB.getTerminator());
2480bb22b91SFlorian Hahn BB.getTerminator()->eraseFromParent();
2490bb22b91SFlorian Hahn
2500bb22b91SFlorian Hahn // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
2510bb22b91SFlorian Hahn // the conditional branch did not use RemovedSucc as both the true and false
2520bb22b91SFlorian Hahn // branches.
2530bb22b91SFlorian Hahn if (NewBranch->getSuccessor(0) != RemovedSucc)
2540bb22b91SFlorian Hahn DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
2550bb22b91SFlorian Hahn Changed = true;
2560bb22b91SFlorian Hahn }
2570bb22b91SFlorian Hahn
2580bb22b91SFlorian Hahn // Apply updates permissively, to remove duplicates.
2590bb22b91SFlorian Hahn DTU.applyUpdatesPermissive(DTUpdates);
2600bb22b91SFlorian Hahn return Changed;
2610bb22b91SFlorian Hahn }
2620bb22b91SFlorian Hahn
2630bb22b91SFlorian Hahn // Merge basic blocks into their single predecessor, if their predecessor has a
2640bb22b91SFlorian Hahn // single successor. This is the first version and does not preserve the
2650bb22b91SFlorian Hahn // DominatorTree.
mergeIntoSinglePredecessor_v1(Function & F)2660bb22b91SFlorian Hahn static bool mergeIntoSinglePredecessor_v1(Function &F) {
2670bb22b91SFlorian Hahn bool Changed = false;
2680bb22b91SFlorian Hahn
2690bb22b91SFlorian Hahn // Merge blocks with single predecessors.
2700bb22b91SFlorian Hahn for (BasicBlock &BB : make_early_inc_range(F)) {
2710bb22b91SFlorian Hahn BasicBlock *Pred = BB.getSinglePredecessor();
2720bb22b91SFlorian Hahn // Make sure BB has a single predecessor Pred and BB is the single
2730bb22b91SFlorian Hahn // successor of Pred.
2740bb22b91SFlorian Hahn if (!Pred || Pred->getSingleSuccessor() != &BB)
2750bb22b91SFlorian Hahn continue;
2760bb22b91SFlorian Hahn
2770bb22b91SFlorian Hahn // Do not try to merge self loops. That can happen in dead blocks.
2780bb22b91SFlorian Hahn if (Pred == &BB)
2790bb22b91SFlorian Hahn continue;
2800bb22b91SFlorian Hahn
2810bb22b91SFlorian Hahn // Need to replace it before nuking the branch.
2820bb22b91SFlorian Hahn BB.replaceAllUsesWith(Pred);
2830bb22b91SFlorian Hahn // PHI nodes in BB can only have a single incoming value. Remove them.
2840bb22b91SFlorian Hahn for (PHINode &PN : make_early_inc_range(BB.phis())) {
2850bb22b91SFlorian Hahn PN.replaceAllUsesWith(PN.getIncomingValue(0));
2860bb22b91SFlorian Hahn PN.eraseFromParent();
2870bb22b91SFlorian Hahn }
2880bb22b91SFlorian Hahn // Move all instructions from BB to Pred.
2890bb22b91SFlorian Hahn for (Instruction &I : make_early_inc_range(BB))
2900bb22b91SFlorian Hahn I.moveBefore(Pred->getTerminator());
2910bb22b91SFlorian Hahn
2920bb22b91SFlorian Hahn // Remove the Pred's terminator (which jumped to BB). BB's terminator
2930bb22b91SFlorian Hahn // will become Pred's terminator.
2940bb22b91SFlorian Hahn Pred->getTerminator()->eraseFromParent();
2950bb22b91SFlorian Hahn BB.eraseFromParent();
2960bb22b91SFlorian Hahn
2970bb22b91SFlorian Hahn Changed = true;
2980bb22b91SFlorian Hahn }
2990bb22b91SFlorian Hahn
3000bb22b91SFlorian Hahn return Changed;
3010bb22b91SFlorian Hahn }
3020bb22b91SFlorian Hahn
3030bb22b91SFlorian Hahn // Merge basic blocks into their single predecessor, if their predecessor has a
3040bb22b91SFlorian Hahn // single successor. This is the second version and does preserve the
3050bb22b91SFlorian Hahn // DominatorTree.
mergeIntoSinglePredecessor_v2(Function & F,DominatorTree & DT)3060bb22b91SFlorian Hahn static bool mergeIntoSinglePredecessor_v2(Function &F, DominatorTree &DT) {
3070bb22b91SFlorian Hahn bool Changed = false;
3080bb22b91SFlorian Hahn DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3090bb22b91SFlorian Hahn SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
3100bb22b91SFlorian Hahn
3110bb22b91SFlorian Hahn // Merge blocks with single predecessors.
3120bb22b91SFlorian Hahn for (BasicBlock &BB : make_early_inc_range(F)) {
3130bb22b91SFlorian Hahn BasicBlock *Pred = BB.getSinglePredecessor();
3140bb22b91SFlorian Hahn // Make sure BB has a single predecessor Pred and BB is the single
3150bb22b91SFlorian Hahn // successor of Pred.
3160bb22b91SFlorian Hahn if (!Pred || Pred->getSingleSuccessor() != &BB)
3170bb22b91SFlorian Hahn continue;
3180bb22b91SFlorian Hahn
3190bb22b91SFlorian Hahn // Do not try to merge self loops. That can happen in dead blocks.
3200bb22b91SFlorian Hahn if (Pred == &BB)
3210bb22b91SFlorian Hahn continue;
3220bb22b91SFlorian Hahn
3230bb22b91SFlorian Hahn // Tell DTU about the changes to the CFG: All edges from BB to its
3240bb22b91SFlorian Hahn // successors get removed and we add edges between Pred and BB's successors.
3250bb22b91SFlorian Hahn for (BasicBlock *Succ : successors(&BB)) {
3260bb22b91SFlorian Hahn DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
3270bb22b91SFlorian Hahn DTUpdates.push_back({DominatorTree::Insert, Pred, Succ});
3280bb22b91SFlorian Hahn }
3290bb22b91SFlorian Hahn // Also remove the edge between Pred and BB.
3300bb22b91SFlorian Hahn DTUpdates.push_back({DominatorTree::Delete, Pred, &BB});
3310bb22b91SFlorian Hahn
3320bb22b91SFlorian Hahn // Need to replace it before nuking the branch.
3330bb22b91SFlorian Hahn BB.replaceAllUsesWith(Pred);
3340bb22b91SFlorian Hahn // PHI nodes in BB can only have a single incoming value. Remove them.
3350bb22b91SFlorian Hahn for (PHINode &PN : make_early_inc_range(BB.phis())) {
3360bb22b91SFlorian Hahn PN.replaceAllUsesWith(PN.getIncomingValue(0));
3370bb22b91SFlorian Hahn PN.eraseFromParent();
3380bb22b91SFlorian Hahn }
3390bb22b91SFlorian Hahn // Move all instructions from BB to Pred.
3400bb22b91SFlorian Hahn for (Instruction &I : make_early_inc_range(BB))
3410bb22b91SFlorian Hahn I.moveBefore(Pred->getTerminator());
3420bb22b91SFlorian Hahn
3430bb22b91SFlorian Hahn // Remove the Pred's terminator (which jumped to BB). BB's terminator
3440bb22b91SFlorian Hahn // will become Pred's terminator.
3450bb22b91SFlorian Hahn Pred->getTerminator()->eraseFromParent();
3460bb22b91SFlorian Hahn DTU.deleteBB(&BB);
3470bb22b91SFlorian Hahn
3480bb22b91SFlorian Hahn Changed = true;
3490bb22b91SFlorian Hahn }
3500bb22b91SFlorian Hahn
3510bb22b91SFlorian Hahn // Apply updates permissively, to remove duplicates.
3520bb22b91SFlorian Hahn DTU.applyUpdatesPermissive(DTUpdates);
3530bb22b91SFlorian Hahn return Changed;
3540bb22b91SFlorian Hahn }
3550bb22b91SFlorian Hahn
doSimplify_v1(Function & F)3560bb22b91SFlorian Hahn static bool doSimplify_v1(Function &F) {
357*7cf1fef4SDavid Blaikie return (int)eliminateCondBranches_v1(F) | mergeIntoSinglePredecessor_v1(F) |
3580bb22b91SFlorian Hahn removeDeadBlocks_v1(F);
3590bb22b91SFlorian Hahn }
3600bb22b91SFlorian Hahn
doSimplify_v2(Function & F,DominatorTree & DT)3610bb22b91SFlorian Hahn static bool doSimplify_v2(Function &F, DominatorTree &DT) {
362*7cf1fef4SDavid Blaikie return (int)eliminateCondBranches_v2(F, DT) |
3636dadf7cbSJon Roelofs mergeIntoSinglePredecessor_v2(F, DT) | removeDeadBlocks_v2(F, DT);
3640bb22b91SFlorian Hahn }
3650bb22b91SFlorian Hahn
doSimplify_v3(Function & F,DominatorTree & DT)3660bb22b91SFlorian Hahn static bool doSimplify_v3(Function &F, DominatorTree &DT) {
367*7cf1fef4SDavid Blaikie return (int)eliminateCondBranches_v3(F, DT) |
3686dadf7cbSJon Roelofs mergeIntoSinglePredecessor_v2(F, DT) | removeDeadBlocks_v2(F, DT);
3690bb22b91SFlorian Hahn }
3700bb22b91SFlorian Hahn
3710bb22b91SFlorian Hahn namespace {
3720bb22b91SFlorian Hahn struct SimplifyCFGLegacyPass : public FunctionPass {
3730bb22b91SFlorian Hahn static char ID;
SimplifyCFGLegacyPass__anonb55afe5e0111::SimplifyCFGLegacyPass3740bb22b91SFlorian Hahn SimplifyCFGLegacyPass() : FunctionPass(ID) {
3750bb22b91SFlorian Hahn initializeSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
3760bb22b91SFlorian Hahn }
3770bb22b91SFlorian Hahn
getAnalysisUsage__anonb55afe5e0111::SimplifyCFGLegacyPass3780bb22b91SFlorian Hahn void getAnalysisUsage(AnalysisUsage &AU) const override {
3790bb22b91SFlorian Hahn AU.addRequired<DominatorTreeWrapperPass>();
3800bb22b91SFlorian Hahn // Version 1 of the implementation does not preserve the dominator tree.
3810bb22b91SFlorian Hahn if (Version != V1)
3820bb22b91SFlorian Hahn AU.addPreserved<DominatorTreeWrapperPass>();
3830bb22b91SFlorian Hahn
3840bb22b91SFlorian Hahn FunctionPass::getAnalysisUsage(AU);
3850bb22b91SFlorian Hahn }
3860bb22b91SFlorian Hahn
runOnFunction__anonb55afe5e0111::SimplifyCFGLegacyPass3870bb22b91SFlorian Hahn bool runOnFunction(Function &F) override {
3880bb22b91SFlorian Hahn if (skipFunction(F))
3890bb22b91SFlorian Hahn return false;
3900bb22b91SFlorian Hahn
3910bb22b91SFlorian Hahn switch (Version) {
3920bb22b91SFlorian Hahn case V1:
3930bb22b91SFlorian Hahn return doSimplify_v1(F);
3940bb22b91SFlorian Hahn case V2: {
3950bb22b91SFlorian Hahn auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3960bb22b91SFlorian Hahn return doSimplify_v2(F, DT);
3970bb22b91SFlorian Hahn }
3980bb22b91SFlorian Hahn case V3: {
3990bb22b91SFlorian Hahn auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4000bb22b91SFlorian Hahn return doSimplify_v3(F, DT);
4010bb22b91SFlorian Hahn }
4020bb22b91SFlorian Hahn }
4030bb22b91SFlorian Hahn
4040bb22b91SFlorian Hahn llvm_unreachable("Unsupported version");
4050bb22b91SFlorian Hahn }
4060bb22b91SFlorian Hahn };
4070bb22b91SFlorian Hahn } // namespace
4080bb22b91SFlorian Hahn
4090bb22b91SFlorian Hahn char SimplifyCFGLegacyPass::ID = 0;
4100bb22b91SFlorian Hahn INITIALIZE_PASS_BEGIN(SimplifyCFGLegacyPass, DEBUG_TYPE,
4110bb22b91SFlorian Hahn "Tutorial CFG simplification", false, false)
4120bb22b91SFlorian Hahn INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4130bb22b91SFlorian Hahn INITIALIZE_PASS_END(SimplifyCFGLegacyPass, DEBUG_TYPE,
4140bb22b91SFlorian Hahn "Tutorial CFG simplifications", false, false)
415