LLVM 23.0.0git
UnreachableBlockElim.cpp
Go to the documentation of this file.
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
33#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Dominators.h"
37#include "llvm/Pass.h"
39using namespace llvm;
40
41namespace {
42class UnreachableBlockElimLegacyPass : public FunctionPass {
43 bool runOnFunction(Function &F) override {
45 }
46
47public:
48 static char ID; // Pass identification, replacement for typeid
49 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
52 }
53
54 void getAnalysisUsage(AnalysisUsage &AU) const override {
55 AU.addPreserved<DominatorTreeWrapperPass>();
56 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
57 }
58};
59}
60char UnreachableBlockElimLegacyPass::ID = 0;
61INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
62 "Remove unreachable blocks from the CFG", false, false)
63
65 return new UnreachableBlockElimLegacyPass();
66}
67
78
79namespace {
80class UnreachableMachineBlockElim {
83 MachineLoopInfo *MLI;
84
85public:
86 UnreachableMachineBlockElim(MachineDominatorTree *MDT,
88 MachineLoopInfo *MLI)
89 : MDT(MDT), MPDT(MPDT), MLI(MLI) {}
90 bool run(MachineFunction &MF);
91};
92
93class UnreachableMachineBlockElimLegacy : public MachineFunctionPass {
94 bool runOnMachineFunction(MachineFunction &F) override;
95 void getAnalysisUsage(AnalysisUsage &AU) const override;
96
97public:
98 static char ID; // Pass identification, replacement for typeid
99 UnreachableMachineBlockElimLegacy() : MachineFunctionPass(ID) {}
100};
101} // namespace
102
103char UnreachableMachineBlockElimLegacy::ID = 0;
104
105INITIALIZE_PASS(UnreachableMachineBlockElimLegacy,
106 "unreachable-mbb-elimination",
107 "Remove unreachable machine basic blocks", false, false)
108
110 UnreachableMachineBlockElimLegacy::ID;
111
112void UnreachableMachineBlockElimLegacy::getAnalysisUsage(
113 AnalysisUsage &AU) const {
114 AU.addPreserved<MachineLoopInfoWrapperPass>();
115 AU.addPreserved<MachineDominatorTreeWrapperPass>();
116 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
117 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
119}
120
126 auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(MF);
127
128 if (!UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF))
129 return PreservedAnalyses::all();
130
133 .preserve<MachineDominatorTreeAnalysis>()
135 .preserve<MachineBlockFrequencyAnalysis>();
136}
137
138bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
139 MachineFunction &MF) {
141 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
143 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
144 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
146 MPDTWrapper ? &MPDTWrapper->getPostDomTree() : nullptr;
147 MachineLoopInfoWrapperPass *MLIWrapper =
148 getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
149 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
150
151 return UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF);
152}
153
154bool UnreachableMachineBlockElim::run(MachineFunction &F) {
156 bool ModifiedPHI = false;
157
158 // Mark all reachable blocks.
159 for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
160 (void)BB/* Mark all reachable blocks */;
161
162 // Loop over all dead blocks, remembering them and deleting all instructions
163 // in them.
164 std::vector<MachineBasicBlock*> DeadBlocks;
165 for (MachineBasicBlock &BB : F) {
166 // Test for deadness.
167 if (!Reachable.count(&BB)) {
168 DeadBlocks.push_back(&BB);
169
170 // Update dominator and loop info.
171 if (MLI) MLI->removeBlock(&BB);
172 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
173 if (MPDT && MPDT->getNode(&BB))
174 MPDT->eraseNode(&BB);
175
176 while (!BB.succ_empty()) {
177 (*BB.succ_begin())->removePHIsIncomingValuesForPredecessor(BB);
178 BB.removeSuccessor(BB.succ_begin());
179 }
180 }
181 }
182
183 // Actually remove the blocks now.
184 for (MachineBasicBlock *BB : DeadBlocks) {
185 // Remove any call information for calls in the block.
186 for (auto &I : BB->instrs())
187 if (I.shouldUpdateAdditionalCallInfo())
188 BB->getParent()->eraseAdditionalCallInfo(&I);
189
190 BB->eraseFromParent();
191 }
192
193 // Cleanup PHI nodes.
194 for (MachineBasicBlock &BB : F) {
195 // Prune unneeded PHI entries.
197 BB.predecessors());
198 for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
199 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
200 if (!preds.count(Phi.getOperand(i).getMBB())) {
201 Phi.removeOperand(i);
202 Phi.removeOperand(i - 1);
203 ModifiedPHI = true;
204 }
205 }
206
207 if (Phi.getNumOperands() == 3) {
208 const MachineOperand &Input = Phi.getOperand(1);
209 const MachineOperand &Output = Phi.getOperand(0);
210 Register InputReg = Input.getReg();
211 Register OutputReg = Output.getReg();
212 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
213 ModifiedPHI = true;
214
215 if (InputReg != OutputReg) {
216 MachineRegisterInfo &MRI = F.getRegInfo();
217 unsigned InputSub = Input.getSubReg();
218 if (InputSub == 0 &&
219 MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
220 !Input.isUndef()) {
221 MRI.replaceRegWith(OutputReg, InputReg);
222 } else {
223 // The input register to the PHI has a subregister or it can't be
224 // constrained to the proper register class or it is undef:
225 // insert a COPY instead of simply replacing the output
226 // with the input.
227 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
228 BuildMI(BB, BB.getFirstNonPHI(), Phi.getDebugLoc(),
229 TII->get(TargetOpcode::COPY), OutputReg)
230 .addReg(InputReg, getRegState(Input), InputSub);
231 }
232 Phi.eraseFromParent();
233 }
234 }
235 }
236 }
237
238 F.RenumberBlocks();
239 if (MDT)
240 MDT->updateBlockNumbers();
241
242 if (MPDT)
243 MPDT->updateBlockNumbers();
244
245 return (!DeadBlocks.empty() || ModifiedPHI);
246}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
const HexagonInstrInfo * TII
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the SmallPtrSet class.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
std::enable_if_t< GraphHasNodeNumbers< T * >, void > updateBlockNumbers()
Update dominator tree after renumbering blocks.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const MachineInstrBuilder & addReg(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
TargetInstrInfo - Interface to description of machine instruction set.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(MachineFunction &F, MachineFunctionAnalysisManager &AM)
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr from_range_t from_range
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI void initializeUnreachableBlockElimLegacyPassPass(PassRegistry &)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
LLVM_ABI bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
unsigned getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...