1//===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass is an extremely simple version of the SimplifyCFG pass. Its sole
10// job is to delete LLVM basic blocks that are not reachable from the entry
11// node. To do this, it performs a simple depth first traversal of the CFG,
12// then deletes any unvisited nodes.
13//
14// Note that this pass is really a hack. In particular, the instruction
15// selectors for various targets should just not generate code for unreachable
16// blocks. Until LLVM has a more systematic way of defining instruction
17// selectors, however, we cannot really expect them to handle additional
18// complexity.
19//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/CodeGen/UnreachableBlockElim.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/CodeGen/MachineDominators.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineLoopInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/Passes.h"
31#include "llvm/CodeGen/TargetInstrInfo.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/InitializePasses.h"
34#include "llvm/Pass.h"
35#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36using namespace llvm;
37
38namespace {
39class UnreachableBlockElimLegacyPass : public FunctionPass {
40 bool runOnFunction(Function &F) override {
41 return llvm::EliminateUnreachableBlocks(F);
42 }
43
44public:
45 static char ID; // Pass identification, replacement for typeid
46 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
47 initializeUnreachableBlockElimLegacyPassPass(
48 *PassRegistry::getPassRegistry());
49 }
50
51 void getAnalysisUsage(AnalysisUsage &AU) const override {
52 AU.addPreserved<DominatorTreeWrapperPass>();
53 }
54};
55}
56char UnreachableBlockElimLegacyPass::ID = 0;
57INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
58 "Remove unreachable blocks from the CFG", false, false)
59
60FunctionPass *llvm::createUnreachableBlockEliminationPass() {
61 return new UnreachableBlockElimLegacyPass();
62}
63
64PreservedAnalyses UnreachableBlockElimPass::run(Function &F,
65 FunctionAnalysisManager &AM) {
66 bool Changed = llvm::EliminateUnreachableBlocks(F);
67 if (!Changed)
68 return PreservedAnalyses::all();
69 PreservedAnalyses PA;
70 PA.preserve<DominatorTreeAnalysis>();
71 return PA;
72}
73
74namespace {
75 class UnreachableMachineBlockElim : public MachineFunctionPass {
76 bool runOnMachineFunction(MachineFunction &F) override;
77 void getAnalysisUsage(AnalysisUsage &AU) const override;
78
79 public:
80 static char ID; // Pass identification, replacement for typeid
81 UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
82 };
83}
84char UnreachableMachineBlockElim::ID = 0;
85
86INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
87 "Remove unreachable machine basic blocks", false, false)
88
89char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
90
91void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addPreserved<MachineLoopInfoWrapperPass>();
93 AU.addPreserved<MachineDominatorTreeWrapperPass>();
94 MachineFunctionPass::getAnalysisUsage(AU);
95}
96
97bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
98 df_iterator_default_set<MachineBasicBlock*> Reachable;
99 bool ModifiedPHI = false;
100
101 MachineDominatorTreeWrapperPass *MDTWrapper =
102 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
103 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
104 MachineLoopInfoWrapperPass *MLIWrapper =
105 getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
106 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
107
108 // Mark all reachable blocks.
109 for (MachineBasicBlock *BB : depth_first_ext(G: &F, S&: Reachable))
110 (void)BB/* Mark all reachable blocks */;
111
112 // Loop over all dead blocks, remembering them and deleting all instructions
113 // in them.
114 std::vector<MachineBasicBlock*> DeadBlocks;
115 for (MachineBasicBlock &BB : F) {
116 // Test for deadness.
117 if (!Reachable.count(Ptr: &BB)) {
118 DeadBlocks.push_back(x: &BB);
119
120 // Update dominator and loop info.
121 if (MLI) MLI->removeBlock(BB: &BB);
122 if (MDT && MDT->getNode(BB: &BB)) MDT->eraseNode(BB: &BB);
123
124 while (!BB.succ_empty()) {
125 MachineBasicBlock* succ = *BB.succ_begin();
126
127 for (MachineInstr &Phi : succ->phis()) {
128 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
129 if (Phi.getOperand(i).isMBB() &&
130 Phi.getOperand(i).getMBB() == &BB) {
131 Phi.removeOperand(OpNo: i);
132 Phi.removeOperand(OpNo: i - 1);
133 }
134 }
135 }
136
137 BB.removeSuccessor(I: BB.succ_begin());
138 }
139 }
140 }
141
142 // Actually remove the blocks now.
143 for (MachineBasicBlock *BB : DeadBlocks) {
144 // Remove any call site information for calls in the block.
145 for (auto &I : BB->instrs())
146 if (I.shouldUpdateCallSiteInfo())
147 BB->getParent()->eraseCallSiteInfo(MI: &I);
148
149 BB->eraseFromParent();
150 }
151
152 // Cleanup PHI nodes.
153 for (MachineBasicBlock &BB : F) {
154 // Prune unneeded PHI entries.
155 SmallPtrSet<MachineBasicBlock*, 8> preds(BB.pred_begin(),
156 BB.pred_end());
157 for (MachineInstr &Phi : make_early_inc_range(Range: BB.phis())) {
158 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
159 if (!preds.count(Ptr: Phi.getOperand(i).getMBB())) {
160 Phi.removeOperand(OpNo: i);
161 Phi.removeOperand(OpNo: i - 1);
162 ModifiedPHI = true;
163 }
164 }
165
166 if (Phi.getNumOperands() == 3) {
167 const MachineOperand &Input = Phi.getOperand(i: 1);
168 const MachineOperand &Output = Phi.getOperand(i: 0);
169 Register InputReg = Input.getReg();
170 Register OutputReg = Output.getReg();
171 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
172 ModifiedPHI = true;
173
174 if (InputReg != OutputReg) {
175 MachineRegisterInfo &MRI = F.getRegInfo();
176 unsigned InputSub = Input.getSubReg();
177 if (InputSub == 0 &&
178 MRI.constrainRegClass(Reg: InputReg, RC: MRI.getRegClass(Reg: OutputReg)) &&
179 !Input.isUndef()) {
180 MRI.replaceRegWith(FromReg: OutputReg, ToReg: InputReg);
181 } else {
182 // The input register to the PHI has a subregister or it can't be
183 // constrained to the proper register class or it is undef:
184 // insert a COPY instead of simply replacing the output
185 // with the input.
186 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
187 BuildMI(BB, I: BB.getFirstNonPHI(), MIMD: Phi.getDebugLoc(),
188 MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: OutputReg)
189 .addReg(RegNo: InputReg, flags: getRegState(RegOp: Input), SubReg: InputSub);
190 }
191 Phi.eraseFromParent();
192 }
193 }
194 }
195 }
196
197 F.RenumberBlocks();
198
199 return (!DeadBlocks.empty() || ModifiedPHI);
200}
201