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/MachineBasicBlock.h"
26#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27#include "llvm/CodeGen/MachineDominators.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineLoopInfo.h"
31#include "llvm/CodeGen/MachinePostDominators.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/CodeGen/RegisterClassInfo.h"
35#include "llvm/CodeGen/TargetInstrInfo.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/InitializePasses.h"
38#include "llvm/Pass.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40using namespace llvm;
41
42namespace {
43class UnreachableBlockElimLegacyPass : public FunctionPass {
44 bool runOnFunction(Function &F) override {
45 return llvm::EliminateUnreachableBlocks(F);
46 }
47
48public:
49 static char ID; // Pass identification, replacement for typeid
50 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {}
51
52 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 AU.addPreserved<DominatorTreeWrapperPass>();
54 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
55 }
56};
57}
58char UnreachableBlockElimLegacyPass::ID = 0;
59INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
60 "Remove unreachable blocks from the CFG", false, false)
61
62FunctionPass *llvm::createUnreachableBlockEliminationPass() {
63 return new UnreachableBlockElimLegacyPass();
64}
65
66PreservedAnalyses UnreachableBlockElimPass::run(Function &F,
67 FunctionAnalysisManager &AM) {
68 bool Changed = llvm::EliminateUnreachableBlocks(F);
69 if (!Changed)
70 return PreservedAnalyses::all();
71 PreservedAnalyses PA;
72 PA.preserve<DominatorTreeAnalysis>();
73 PA.preserve<MachineBlockFrequencyAnalysis>();
74 return PA;
75}
76
77namespace {
78class UnreachableMachineBlockElim {
79 MachineDominatorTree *MDT;
80 MachinePostDominatorTree *MPDT;
81 MachineLoopInfo *MLI;
82
83public:
84 UnreachableMachineBlockElim(MachineDominatorTree *MDT,
85 MachinePostDominatorTree *MPDT,
86 MachineLoopInfo *MLI)
87 : MDT(MDT), MPDT(MPDT), MLI(MLI) {}
88 bool run(MachineFunction &MF);
89};
90
91class UnreachableMachineBlockElimLegacy : public MachineFunctionPass {
92 bool runOnMachineFunction(MachineFunction &F) override;
93 void getAnalysisUsage(AnalysisUsage &AU) const override;
94
95public:
96 static char ID; // Pass identification, replacement for typeid
97 UnreachableMachineBlockElimLegacy() : MachineFunctionPass(ID) {}
98};
99} // namespace
100
101char UnreachableMachineBlockElimLegacy::ID = 0;
102
103INITIALIZE_PASS(UnreachableMachineBlockElimLegacy,
104 "unreachable-mbb-elimination",
105 "Remove unreachable machine basic blocks", false, false)
106
107char &llvm::UnreachableMachineBlockElimID =
108 UnreachableMachineBlockElimLegacy::ID;
109
110void UnreachableMachineBlockElimLegacy::getAnalysisUsage(
111 AnalysisUsage &AU) const {
112 AU.addPreserved<MachineLoopInfoWrapperPass>();
113 AU.addPreserved<MachineDominatorTreeWrapperPass>();
114 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
115 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
116 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
117 MachineFunctionPass::getAnalysisUsage(AU);
118}
119
120PreservedAnalyses
121UnreachableMachineBlockElimPass::run(MachineFunction &MF,
122 MachineFunctionAnalysisManager &AM) {
123 auto *MDT = AM.getCachedResult<MachineDominatorTreeAnalysis>(IR&: MF);
124 auto *MPDT = AM.getCachedResult<MachinePostDominatorTreeAnalysis>(IR&: MF);
125 auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(IR&: MF);
126
127 if (!UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF))
128 return PreservedAnalyses::all();
129
130 return getMachineFunctionPassPreservedAnalyses()
131 .preserve<MachineLoopAnalysis>()
132 .preserve<MachineDominatorTreeAnalysis>()
133 .preserve<MachinePostDominatorTreeAnalysis>()
134 .preserve<MachineBlockFrequencyAnalysis>();
135}
136
137bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
138 MachineFunction &MF) {
139 MachineDominatorTreeWrapperPass *MDTWrapper =
140 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
141 MachinePostDominatorTreeWrapperPass *MPDTWrapper =
142 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
143 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
144 MachinePostDominatorTree *MPDT =
145 MPDTWrapper ? &MPDTWrapper->getPostDomTree() : nullptr;
146 MachineLoopInfoWrapperPass *MLIWrapper =
147 getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
148 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
149
150 return UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF);
151}
152
153bool UnreachableMachineBlockElim::run(MachineFunction &F) {
154 df_iterator_default_set<MachineBasicBlock *> Reachable;
155 bool ModifiedPHI = false;
156
157 // Mark all reachable blocks.
158 for (MachineBasicBlock *BB : depth_first_ext(G: &F, S&: Reachable))
159 (void)BB/* Mark all reachable blocks */;
160
161 // Loop over all dead blocks, remembering them and deleting all instructions
162 // in them.
163 std::vector<MachineBasicBlock*> DeadBlocks;
164 for (MachineBasicBlock &BB : F) {
165 // Test for deadness.
166 if (!Reachable.count(Ptr: &BB)) {
167 DeadBlocks.push_back(x: &BB);
168
169 // Update dominator and loop info.
170 if (MLI) MLI->removeBlock(BB: &BB);
171 if (MDT && MDT->getNode(BB: &BB)) MDT->eraseNode(BB: &BB);
172 if (MPDT && MPDT->getNode(BB: &BB))
173 MPDT->eraseNode(BB: &BB);
174
175 while (!BB.succ_empty()) {
176 (*BB.succ_begin())->removePHIsIncomingValuesForPredecessor(PredMBB: BB);
177 BB.removeSuccessor(I: BB.succ_begin());
178 }
179 }
180 }
181
182 // Actually remove the blocks now.
183 for (MachineBasicBlock *BB : DeadBlocks) {
184 // Remove any call information for calls in the block.
185 for (auto &I : BB->instrs())
186 if (I.shouldUpdateAdditionalCallInfo())
187 BB->getParent()->eraseAdditionalCallInfo(MI: &I);
188
189 BB->eraseFromParent();
190 }
191
192 // Cleanup PHI nodes.
193 for (MachineBasicBlock &BB : F) {
194 // Prune unneeded PHI entries.
195 SmallPtrSet<MachineBasicBlock *, 8> preds(llvm::from_range,
196 BB.predecessors());
197 for (MachineInstr &Phi : make_early_inc_range(Range: BB.phis())) {
198 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
199 if (!preds.count(Ptr: Phi.getOperand(i).getMBB())) {
200 Phi.removeOperand(OpNo: i);
201 Phi.removeOperand(OpNo: i - 1);
202 ModifiedPHI = true;
203 }
204 }
205
206 if (Phi.getNumOperands() == 3) {
207 const MachineOperand &Input = Phi.getOperand(i: 1);
208 const MachineOperand &Output = Phi.getOperand(i: 0);
209 Register InputReg = Input.getReg();
210 Register OutputReg = Output.getReg();
211 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
212 ModifiedPHI = true;
213
214 if (InputReg != OutputReg) {
215 MachineRegisterInfo &MRI = F.getRegInfo();
216 unsigned InputSub = Input.getSubReg();
217 if (InputSub == 0 &&
218 MRI.constrainRegClass(Reg: InputReg, RC: MRI.getRegClass(Reg: OutputReg)) &&
219 !Input.isUndef()) {
220 MRI.replaceRegWith(FromReg: OutputReg, ToReg: InputReg);
221 } else {
222 // The input register to the PHI has a subregister or it can't be
223 // constrained to the proper register class or it is undef:
224 // insert a COPY instead of simply replacing the output
225 // with the input.
226 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
227 BuildMI(BB, I: BB.getFirstNonPHI(), MIMD: Phi.getDebugLoc(),
228 MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: OutputReg)
229 .addReg(RegNo: InputReg, Flags: getRegState(RegOp: Input), SubReg: InputSub);
230 }
231 Phi.eraseFromParent();
232 }
233 }
234 }
235 }
236
237 F.RenumberBlocks();
238
239 return (!DeadBlocks.empty() || ModifiedPHI);
240}
241