xref: /llvm-project/llvm/examples/IRTransforms/SimplifyCFG.cpp (revision 304a99091c84f303ff5037dc6bf5455e4cfde7a1)
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 //  * Preserve LoopInfo.
310bb22b91SFlorian Hahn //  * Add fixed point iteration to delete all dead blocks
320bb22b91SFlorian Hahn //  * Add implementation using reachability to discover dead blocks.
330bb22b91SFlorian Hahn //===----------------------------------------------------------------------===//
340bb22b91SFlorian Hahn 
350bb22b91SFlorian Hahn #include "llvm/Analysis/DomTreeUpdater.h"
360bb22b91SFlorian Hahn #include "llvm/IR/Dominators.h"
370bb22b91SFlorian Hahn #include "llvm/IR/Function.h"
380bb22b91SFlorian Hahn #include "llvm/IR/PassManager.h"
390bb22b91SFlorian Hahn #include "llvm/IR/PatternMatch.h"
40d291f1fdSSebastian Peryt #include "llvm/Passes/PassBuilder.h"
41d291f1fdSSebastian Peryt #include "llvm/Passes/PassPlugin.h"
420bb22b91SFlorian Hahn #include "llvm/Support/CommandLine.h"
430bb22b91SFlorian Hahn 
440bb22b91SFlorian Hahn using namespace llvm;
450bb22b91SFlorian Hahn using namespace PatternMatch;
460bb22b91SFlorian Hahn 
470bb22b91SFlorian Hahn enum TutorialVersion { V1, V2, V3 };
480bb22b91SFlorian Hahn static cl::opt<TutorialVersion>
490bb22b91SFlorian Hahn     Version("tut-simplifycfg-version", cl::desc("Select tutorial version"),
500bb22b91SFlorian Hahn             cl::Hidden, cl::ValueOptional, cl::init(V1),
510bb22b91SFlorian Hahn             cl::values(clEnumValN(V1, "v1", "version 1"),
520bb22b91SFlorian Hahn                        clEnumValN(V2, "v2", "version 2"),
530bb22b91SFlorian Hahn                        clEnumValN(V3, "v3", "version 3"),
540bb22b91SFlorian Hahn                        // Sentinel value for unspecified option.
550bb22b91SFlorian Hahn                        clEnumValN(V3, "", "")));
560bb22b91SFlorian Hahn 
570bb22b91SFlorian Hahn #define DEBUG_TYPE "tut-simplifycfg"
580bb22b91SFlorian Hahn 
590bb22b91SFlorian Hahn // Remove trivially dead blocks. First version, not preserving the
600bb22b91SFlorian Hahn // DominatorTree.
610bb22b91SFlorian Hahn static bool removeDeadBlocks_v1(Function &F) {
620bb22b91SFlorian Hahn   bool Changed = false;
630bb22b91SFlorian Hahn 
640bb22b91SFlorian Hahn   // Remove trivially dead blocks.
650bb22b91SFlorian Hahn   for (BasicBlock &BB : make_early_inc_range(F)) {
660bb22b91SFlorian Hahn     // Skip blocks we know to not be trivially dead. We know a block is
670bb22b91SFlorian Hahn     // guaranteed to be dead, iff it is neither the entry block nor
680bb22b91SFlorian Hahn     // has any predecessors.
690bb22b91SFlorian Hahn     if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
700bb22b91SFlorian Hahn       continue;
710bb22b91SFlorian Hahn 
720bb22b91SFlorian Hahn     // Notify successors of BB that BB is going to be removed. This removes
730bb22b91SFlorian Hahn     // incoming values from BB from PHIs in the successors. Note that this will
740bb22b91SFlorian Hahn     // not actually remove BB from the predecessor lists of its successors.
750bb22b91SFlorian Hahn     for (BasicBlock *Succ : successors(&BB))
760bb22b91SFlorian Hahn       Succ->removePredecessor(&BB);
770bb22b91SFlorian Hahn     // TODO: Find a better place to put such small variations.
780bb22b91SFlorian Hahn     // Alternatively, we can update the PHI nodes manually:
790bb22b91SFlorian Hahn     // for (PHINode &PN : make_early_inc_range(Succ->phis()))
800bb22b91SFlorian Hahn     //  PN.removeIncomingValue(&BB);
810bb22b91SFlorian Hahn 
8262ec8e94SNikita Popov     // Replace all instructions in BB with a poison constant. The block is
830bb22b91SFlorian Hahn     // unreachable, so the results of the instructions should never get used.
840bb22b91SFlorian Hahn     while (!BB.empty()) {
850bb22b91SFlorian Hahn       Instruction &I = BB.back();
8662ec8e94SNikita Popov       I.replaceAllUsesWith(PoisonValue::get(I.getType()));
870bb22b91SFlorian Hahn       I.eraseFromParent();
880bb22b91SFlorian Hahn     }
890bb22b91SFlorian Hahn 
900bb22b91SFlorian Hahn     // Finally remove the basic block.
910bb22b91SFlorian Hahn     BB.eraseFromParent();
920bb22b91SFlorian Hahn     Changed = true;
930bb22b91SFlorian Hahn   }
940bb22b91SFlorian Hahn 
950bb22b91SFlorian Hahn   return Changed;
960bb22b91SFlorian Hahn }
970bb22b91SFlorian Hahn 
980bb22b91SFlorian Hahn // Remove trivially dead blocks. This is the second version and preserves the
990bb22b91SFlorian Hahn // dominator tree.
1000bb22b91SFlorian Hahn static bool removeDeadBlocks_v2(Function &F, DominatorTree &DT) {
1010bb22b91SFlorian Hahn   bool Changed = false;
1020bb22b91SFlorian Hahn   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1030bb22b91SFlorian Hahn   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1040bb22b91SFlorian Hahn 
1050bb22b91SFlorian Hahn   // Remove trivially dead blocks.
1060bb22b91SFlorian Hahn   for (BasicBlock &BB : make_early_inc_range(F)) {
1070bb22b91SFlorian Hahn     // Skip blocks we know to not be trivially dead. We know a block is
1080bb22b91SFlorian Hahn     // guaranteed to be dead, iff it is neither the entry block nor
1090bb22b91SFlorian Hahn     // has any predecessors.
1100bb22b91SFlorian Hahn     if (&F.getEntryBlock() == &BB || !pred_empty(&BB))
1110bb22b91SFlorian Hahn       continue;
1120bb22b91SFlorian Hahn 
1130bb22b91SFlorian Hahn     // Notify successors of BB that BB is going to be removed. This removes
1140bb22b91SFlorian Hahn     // incoming values from BB from PHIs in the successors. Note that this will
1150bb22b91SFlorian Hahn     // not actually remove BB from the predecessor lists of its successors.
1160bb22b91SFlorian Hahn     for (BasicBlock *Succ : successors(&BB)) {
1170bb22b91SFlorian Hahn       Succ->removePredecessor(&BB);
1180bb22b91SFlorian Hahn 
1190bb22b91SFlorian Hahn       // Collect updates that need to be applied to the dominator tree.
1200bb22b91SFlorian Hahn       DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
1210bb22b91SFlorian Hahn     }
1220bb22b91SFlorian Hahn 
1230bb22b91SFlorian Hahn     // Remove BB via the DomTreeUpdater. DomTreeUpdater::deleteBB conveniently
1240bb22b91SFlorian Hahn     // removes the instructions in BB as well.
1250bb22b91SFlorian Hahn     DTU.deleteBB(&BB);
1260bb22b91SFlorian Hahn     Changed = true;
1270bb22b91SFlorian Hahn   }
1280bb22b91SFlorian Hahn 
1290bb22b91SFlorian Hahn   // Apply updates permissively, to remove duplicates.
1300bb22b91SFlorian Hahn   DTU.applyUpdatesPermissive(DTUpdates);
1310bb22b91SFlorian Hahn 
1320bb22b91SFlorian Hahn   return Changed;
1330bb22b91SFlorian Hahn }
1340bb22b91SFlorian Hahn 
1350bb22b91SFlorian Hahn // Eliminate branches with constant conditionals. This is the first version,
1360bb22b91SFlorian Hahn // which *does not* preserve the dominator tree.
1370bb22b91SFlorian Hahn static bool eliminateCondBranches_v1(Function &F) {
1380bb22b91SFlorian Hahn   bool Changed = false;
1390bb22b91SFlorian Hahn 
1400bb22b91SFlorian Hahn   // Eliminate branches with constant conditionals.
1410bb22b91SFlorian Hahn   for (BasicBlock &BB : F) {
1420bb22b91SFlorian Hahn     // Skip blocks without conditional branches as terminators.
1430bb22b91SFlorian Hahn     BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
1440bb22b91SFlorian Hahn     if (!BI || !BI->isConditional())
1450bb22b91SFlorian Hahn       continue;
1460bb22b91SFlorian Hahn 
1470bb22b91SFlorian Hahn     // Skip blocks with conditional branches without ConstantInt conditions.
1480bb22b91SFlorian Hahn     ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
1490bb22b91SFlorian Hahn     if (!CI)
1500bb22b91SFlorian Hahn       continue;
1510bb22b91SFlorian Hahn 
1520bb22b91SFlorian Hahn     // We use the branch condition (CI), to select the successor we remove:
1530bb22b91SFlorian Hahn     // if CI == 1 (true), we remove the second successor, otherwise the first.
1540bb22b91SFlorian Hahn     BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
1550bb22b91SFlorian Hahn     // Tell RemovedSucc we will remove BB from its predecessors.
1560bb22b91SFlorian Hahn     RemovedSucc->removePredecessor(&BB);
1570bb22b91SFlorian Hahn 
1580bb22b91SFlorian Hahn     // Replace the conditional branch with an unconditional one, by creating
1590bb22b91SFlorian Hahn     // a new unconditional branch to the selected successor and removing the
1600bb22b91SFlorian Hahn     // conditional one.
1612f50b280SJeremy Morse     BranchInst::Create(BI->getSuccessor(CI->isZero()), BI->getIterator());
1620bb22b91SFlorian Hahn     BI->eraseFromParent();
1630bb22b91SFlorian Hahn     Changed = true;
1640bb22b91SFlorian Hahn   }
1650bb22b91SFlorian Hahn 
1660bb22b91SFlorian Hahn   return Changed;
1670bb22b91SFlorian Hahn }
1680bb22b91SFlorian Hahn 
1690bb22b91SFlorian Hahn // Eliminate branches with constant conditionals. This is the second
1700bb22b91SFlorian Hahn // version, which *does* preserve the dominator tree.
1710bb22b91SFlorian Hahn static bool eliminateCondBranches_v2(Function &F, DominatorTree &DT) {
1720bb22b91SFlorian Hahn   bool Changed = false;
1730bb22b91SFlorian Hahn 
1740bb22b91SFlorian Hahn   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1750bb22b91SFlorian Hahn   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1760bb22b91SFlorian Hahn   // Eliminate branches with constant conditionals.
1770bb22b91SFlorian Hahn   for (BasicBlock &BB : F) {
1780bb22b91SFlorian Hahn     // Skip blocks without conditional branches as terminators.
1790bb22b91SFlorian Hahn     BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator());
1800bb22b91SFlorian Hahn     if (!BI || !BI->isConditional())
1810bb22b91SFlorian Hahn       continue;
1820bb22b91SFlorian Hahn 
1830bb22b91SFlorian Hahn     // Skip blocks with conditional branches without ConstantInt conditions.
1840bb22b91SFlorian Hahn     ConstantInt *CI = dyn_cast<ConstantInt>(BI->getCondition());
1850bb22b91SFlorian Hahn     if (!CI)
1860bb22b91SFlorian Hahn       continue;
1870bb22b91SFlorian Hahn 
1880bb22b91SFlorian Hahn     // We use the branch condition (CI), to select the successor we remove:
1890bb22b91SFlorian Hahn     // if CI == 1 (true), we remove the second successor, otherwise the first.
1900bb22b91SFlorian Hahn     BasicBlock *RemovedSucc = BI->getSuccessor(CI->isOne());
1910bb22b91SFlorian Hahn     // Tell RemovedSucc we will remove BB from its predecessors.
1920bb22b91SFlorian Hahn     RemovedSucc->removePredecessor(&BB);
1930bb22b91SFlorian Hahn 
1940bb22b91SFlorian Hahn     // Replace the conditional branch with an unconditional one, by creating
1950bb22b91SFlorian Hahn     // a new unconditional branch to the selected successor and removing the
1960bb22b91SFlorian Hahn     // conditional one.
1970bb22b91SFlorian Hahn     BranchInst *NewBranch =
1982f50b280SJeremy Morse         BranchInst::Create(BI->getSuccessor(CI->isZero()), BI->getIterator());
1990bb22b91SFlorian Hahn     BI->eraseFromParent();
2000bb22b91SFlorian Hahn 
2010bb22b91SFlorian Hahn     // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
2020bb22b91SFlorian Hahn     // the conditional branch did not use RemovedSucc as both the true and false
2030bb22b91SFlorian Hahn     // branches.
2040bb22b91SFlorian Hahn     if (NewBranch->getSuccessor(0) != RemovedSucc)
2050bb22b91SFlorian Hahn       DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
2060bb22b91SFlorian Hahn     Changed = true;
2070bb22b91SFlorian Hahn   }
2080bb22b91SFlorian Hahn 
2090bb22b91SFlorian Hahn   // Apply updates permissively, to remove duplicates.
2100bb22b91SFlorian Hahn   DTU.applyUpdatesPermissive(DTUpdates);
2110bb22b91SFlorian Hahn 
2120bb22b91SFlorian Hahn   return Changed;
2130bb22b91SFlorian Hahn }
2140bb22b91SFlorian Hahn 
2150bb22b91SFlorian Hahn // Eliminate branches with constant conditionals. This is the third
2160bb22b91SFlorian Hahn // version, which uses PatternMatch.h.
2170bb22b91SFlorian Hahn static bool eliminateCondBranches_v3(Function &F, DominatorTree &DT) {
2180bb22b91SFlorian Hahn   bool Changed = false;
2190bb22b91SFlorian Hahn   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2200bb22b91SFlorian Hahn   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
2210bb22b91SFlorian Hahn 
2220bb22b91SFlorian Hahn   // Eliminate branches with constant conditionals.
2230bb22b91SFlorian Hahn   for (BasicBlock &BB : F) {
2240bb22b91SFlorian Hahn     ConstantInt *CI = nullptr;
2250bb22b91SFlorian Hahn     BasicBlock *TakenSucc, *RemovedSucc;
2260bb22b91SFlorian Hahn     // Check if the terminator is a conditional branch, with constant integer
2270bb22b91SFlorian Hahn     // condition and also capture the successor blocks as TakenSucc and
2280bb22b91SFlorian Hahn     // RemovedSucc.
2290bb22b91SFlorian Hahn     if (!match(BB.getTerminator(),
2300bb22b91SFlorian Hahn                m_Br(m_ConstantInt(CI), m_BasicBlock(TakenSucc),
2310bb22b91SFlorian Hahn                     m_BasicBlock(RemovedSucc))))
2320bb22b91SFlorian Hahn       continue;
2330bb22b91SFlorian Hahn 
2340bb22b91SFlorian Hahn     // If the condition is false, swap TakenSucc and RemovedSucc.
2350bb22b91SFlorian Hahn     if (CI->isZero())
2360bb22b91SFlorian Hahn       std::swap(TakenSucc, RemovedSucc);
2370bb22b91SFlorian Hahn 
2380bb22b91SFlorian Hahn     // Tell RemovedSucc we will remove BB from its predecessors.
2390bb22b91SFlorian Hahn     RemovedSucc->removePredecessor(&BB);
2400bb22b91SFlorian Hahn 
2410bb22b91SFlorian Hahn     // Replace the conditional branch with an unconditional one, by creating
2420bb22b91SFlorian Hahn     // a new unconditional branch to the selected successor and removing the
2430bb22b91SFlorian Hahn     // conditional one.
2440bb22b91SFlorian Hahn 
2452f50b280SJeremy Morse     BranchInst *NewBranch =
2462f50b280SJeremy Morse         BranchInst::Create(TakenSucc, BB.getTerminator()->getIterator());
2470bb22b91SFlorian Hahn     BB.getTerminator()->eraseFromParent();
2480bb22b91SFlorian Hahn 
2490bb22b91SFlorian Hahn     // Delete the edge between BB and RemovedSucc in the DominatorTree, iff
2500bb22b91SFlorian Hahn     // the conditional branch did not use RemovedSucc as both the true and false
2510bb22b91SFlorian Hahn     // branches.
2520bb22b91SFlorian Hahn     if (NewBranch->getSuccessor(0) != RemovedSucc)
2530bb22b91SFlorian Hahn       DTUpdates.push_back({DominatorTree::Delete, &BB, RemovedSucc});
2540bb22b91SFlorian Hahn     Changed = true;
2550bb22b91SFlorian Hahn   }
2560bb22b91SFlorian Hahn 
2570bb22b91SFlorian Hahn   // Apply updates permissively, to remove duplicates.
2580bb22b91SFlorian Hahn   DTU.applyUpdatesPermissive(DTUpdates);
2590bb22b91SFlorian Hahn   return Changed;
2600bb22b91SFlorian Hahn }
2610bb22b91SFlorian Hahn 
2620bb22b91SFlorian Hahn // Merge basic blocks into their single predecessor, if their predecessor has a
2630bb22b91SFlorian Hahn // single successor. This is the first version and does not preserve the
2640bb22b91SFlorian Hahn // DominatorTree.
2650bb22b91SFlorian Hahn static bool mergeIntoSinglePredecessor_v1(Function &F) {
2660bb22b91SFlorian Hahn   bool Changed = false;
2670bb22b91SFlorian Hahn 
2680bb22b91SFlorian Hahn   // Merge blocks with single predecessors.
2690bb22b91SFlorian Hahn   for (BasicBlock &BB : make_early_inc_range(F)) {
2700bb22b91SFlorian Hahn     BasicBlock *Pred = BB.getSinglePredecessor();
2710bb22b91SFlorian Hahn     // Make sure  BB has a single predecessor Pred and BB is the single
2720bb22b91SFlorian Hahn     // successor of Pred.
2730bb22b91SFlorian Hahn     if (!Pred || Pred->getSingleSuccessor() != &BB)
2740bb22b91SFlorian Hahn       continue;
2750bb22b91SFlorian Hahn 
2760bb22b91SFlorian Hahn     // Do not try to merge self loops. That can happen in dead blocks.
2770bb22b91SFlorian Hahn     if (Pred == &BB)
2780bb22b91SFlorian Hahn       continue;
2790bb22b91SFlorian Hahn 
2800bb22b91SFlorian Hahn     // Need to replace it before nuking the branch.
2810bb22b91SFlorian Hahn     BB.replaceAllUsesWith(Pred);
2820bb22b91SFlorian Hahn     // PHI nodes in BB can only have a single incoming value. Remove them.
2830bb22b91SFlorian Hahn     for (PHINode &PN : make_early_inc_range(BB.phis())) {
2840bb22b91SFlorian Hahn       PN.replaceAllUsesWith(PN.getIncomingValue(0));
2850bb22b91SFlorian Hahn       PN.eraseFromParent();
2860bb22b91SFlorian Hahn     }
2870bb22b91SFlorian Hahn     // Move all instructions from BB to Pred.
2880bb22b91SFlorian Hahn     for (Instruction &I : make_early_inc_range(BB))
289*304a9909SJeremy Morse       I.moveBefore(Pred->getTerminator()->getIterator());
2900bb22b91SFlorian Hahn 
2910bb22b91SFlorian Hahn     // Remove the Pred's terminator (which jumped to BB). BB's terminator
2920bb22b91SFlorian Hahn     // will become Pred's terminator.
2930bb22b91SFlorian Hahn     Pred->getTerminator()->eraseFromParent();
2940bb22b91SFlorian Hahn     BB.eraseFromParent();
2950bb22b91SFlorian Hahn 
2960bb22b91SFlorian Hahn     Changed = true;
2970bb22b91SFlorian Hahn   }
2980bb22b91SFlorian Hahn 
2990bb22b91SFlorian Hahn   return Changed;
3000bb22b91SFlorian Hahn }
3010bb22b91SFlorian Hahn 
3020bb22b91SFlorian Hahn // Merge basic blocks into their single predecessor, if their predecessor has a
3030bb22b91SFlorian Hahn // single successor. This is the second version and does preserve the
3040bb22b91SFlorian Hahn // DominatorTree.
3050bb22b91SFlorian Hahn static bool mergeIntoSinglePredecessor_v2(Function &F, DominatorTree &DT) {
3060bb22b91SFlorian Hahn   bool Changed = false;
3070bb22b91SFlorian Hahn   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3080bb22b91SFlorian Hahn   SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
3090bb22b91SFlorian Hahn 
3100bb22b91SFlorian Hahn   // Merge blocks with single predecessors.
3110bb22b91SFlorian Hahn   for (BasicBlock &BB : make_early_inc_range(F)) {
3120bb22b91SFlorian Hahn     BasicBlock *Pred = BB.getSinglePredecessor();
3130bb22b91SFlorian Hahn     // Make sure  BB has a single predecessor Pred and BB is the single
3140bb22b91SFlorian Hahn     // successor of Pred.
3150bb22b91SFlorian Hahn     if (!Pred || Pred->getSingleSuccessor() != &BB)
3160bb22b91SFlorian Hahn       continue;
3170bb22b91SFlorian Hahn 
3180bb22b91SFlorian Hahn     // Do not try to merge self loops. That can happen in dead blocks.
3190bb22b91SFlorian Hahn     if (Pred == &BB)
3200bb22b91SFlorian Hahn       continue;
3210bb22b91SFlorian Hahn 
3220bb22b91SFlorian Hahn     // Tell DTU about the changes to the CFG: All edges from BB to its
3230bb22b91SFlorian Hahn     // successors get removed and we add edges between Pred and BB's successors.
3240bb22b91SFlorian Hahn     for (BasicBlock *Succ : successors(&BB)) {
3250bb22b91SFlorian Hahn       DTUpdates.push_back({DominatorTree::Delete, &BB, Succ});
3260bb22b91SFlorian Hahn       DTUpdates.push_back({DominatorTree::Insert, Pred, Succ});
3270bb22b91SFlorian Hahn     }
3280bb22b91SFlorian Hahn     // Also remove the edge between Pred and BB.
3290bb22b91SFlorian Hahn     DTUpdates.push_back({DominatorTree::Delete, Pred, &BB});
3300bb22b91SFlorian Hahn 
3310bb22b91SFlorian Hahn     // Need to replace it before nuking the branch.
3320bb22b91SFlorian Hahn     BB.replaceAllUsesWith(Pred);
3330bb22b91SFlorian Hahn     // PHI nodes in BB can only have a single incoming value. Remove them.
3340bb22b91SFlorian Hahn     for (PHINode &PN : make_early_inc_range(BB.phis())) {
3350bb22b91SFlorian Hahn       PN.replaceAllUsesWith(PN.getIncomingValue(0));
3360bb22b91SFlorian Hahn       PN.eraseFromParent();
3370bb22b91SFlorian Hahn     }
3380bb22b91SFlorian Hahn     // Move all instructions from BB to Pred.
3390bb22b91SFlorian Hahn     for (Instruction &I : make_early_inc_range(BB))
340*304a9909SJeremy Morse       I.moveBefore(Pred->getTerminator()->getIterator());
3410bb22b91SFlorian Hahn 
3420bb22b91SFlorian Hahn     // Remove the Pred's terminator (which jumped to BB). BB's terminator
3430bb22b91SFlorian Hahn     // will become Pred's terminator.
3440bb22b91SFlorian Hahn     Pred->getTerminator()->eraseFromParent();
3450bb22b91SFlorian Hahn     DTU.deleteBB(&BB);
3460bb22b91SFlorian Hahn 
3470bb22b91SFlorian Hahn     Changed = true;
3480bb22b91SFlorian Hahn   }
3490bb22b91SFlorian Hahn 
3500bb22b91SFlorian Hahn   // Apply updates permissively, to remove duplicates.
3510bb22b91SFlorian Hahn   DTU.applyUpdatesPermissive(DTUpdates);
3520bb22b91SFlorian Hahn   return Changed;
3530bb22b91SFlorian Hahn }
3540bb22b91SFlorian Hahn 
3550bb22b91SFlorian Hahn static bool doSimplify_v1(Function &F) {
3567cf1fef4SDavid Blaikie   return (int)eliminateCondBranches_v1(F) | mergeIntoSinglePredecessor_v1(F) |
3570bb22b91SFlorian Hahn          removeDeadBlocks_v1(F);
3580bb22b91SFlorian Hahn }
3590bb22b91SFlorian Hahn 
3600bb22b91SFlorian Hahn static bool doSimplify_v2(Function &F, DominatorTree &DT) {
3617cf1fef4SDavid Blaikie   return (int)eliminateCondBranches_v2(F, DT) |
3626dadf7cbSJon Roelofs          mergeIntoSinglePredecessor_v2(F, DT) | removeDeadBlocks_v2(F, DT);
3630bb22b91SFlorian Hahn }
3640bb22b91SFlorian Hahn 
3650bb22b91SFlorian Hahn static bool doSimplify_v3(Function &F, DominatorTree &DT) {
3667cf1fef4SDavid Blaikie   return (int)eliminateCondBranches_v3(F, DT) |
3676dadf7cbSJon Roelofs          mergeIntoSinglePredecessor_v2(F, DT) | removeDeadBlocks_v2(F, DT);
3680bb22b91SFlorian Hahn }
3690bb22b91SFlorian Hahn 
3700bb22b91SFlorian Hahn namespace {
371d291f1fdSSebastian Peryt struct SimplifyCFGPass : public PassInfoMixin<SimplifyCFGPass> {
372d291f1fdSSebastian Peryt   PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM) {
3730bb22b91SFlorian Hahn     switch (Version) {
3740bb22b91SFlorian Hahn     case V1:
375d291f1fdSSebastian Peryt       doSimplify_v1(F);
376d291f1fdSSebastian Peryt       break;
3770bb22b91SFlorian Hahn     case V2: {
378d291f1fdSSebastian Peryt       DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
379d291f1fdSSebastian Peryt       doSimplify_v2(F, DT);
380d291f1fdSSebastian Peryt       break;
3810bb22b91SFlorian Hahn     }
3820bb22b91SFlorian Hahn     case V3: {
383d291f1fdSSebastian Peryt       DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
384d291f1fdSSebastian Peryt       doSimplify_v3(F, DT);
385d291f1fdSSebastian Peryt       break;
3860bb22b91SFlorian Hahn     }
3870bb22b91SFlorian Hahn     }
3880bb22b91SFlorian Hahn 
389d291f1fdSSebastian Peryt     return PreservedAnalyses::none();
3900bb22b91SFlorian Hahn   }
3910bb22b91SFlorian Hahn };
3920bb22b91SFlorian Hahn } // namespace
3930bb22b91SFlorian Hahn 
394d291f1fdSSebastian Peryt /* New PM Registration */
395d291f1fdSSebastian Peryt llvm::PassPluginLibraryInfo getExampleIRTransformsPluginInfo() {
396d291f1fdSSebastian Peryt   return {LLVM_PLUGIN_API_VERSION, "SimplifyCFG", LLVM_VERSION_STRING,
397d291f1fdSSebastian Peryt           [](PassBuilder &PB) {
398d291f1fdSSebastian Peryt             PB.registerPipelineParsingCallback(
399d291f1fdSSebastian Peryt                 [](StringRef Name, llvm::FunctionPassManager &PM,
400d291f1fdSSebastian Peryt                    ArrayRef<llvm::PassBuilder::PipelineElement>) {
401d291f1fdSSebastian Peryt                   if (Name == "tut-simplifycfg") {
402d291f1fdSSebastian Peryt                     PM.addPass(SimplifyCFGPass());
403d291f1fdSSebastian Peryt                     return true;
404d291f1fdSSebastian Peryt                   }
405d291f1fdSSebastian Peryt                   return false;
406d291f1fdSSebastian Peryt                 });
407d291f1fdSSebastian Peryt           }};
408d291f1fdSSebastian Peryt }
409d291f1fdSSebastian Peryt 
410d291f1fdSSebastian Peryt #ifndef LLVM_SIMPLIFYCFG_LINK_INTO_TOOLS
411d291f1fdSSebastian Peryt extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
412d291f1fdSSebastian Peryt llvmGetPassPluginInfo() {
413d291f1fdSSebastian Peryt   return getExampleIRTransformsPluginInfo();
414d291f1fdSSebastian Peryt }
415d291f1fdSSebastian Peryt #endif
416