LLVM 22.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
30#include "llvm/CodeGen/Passes.h"
32#include "llvm/IR/Dominators.h"
34#include "llvm/Pass.h"
36using namespace llvm;
37
38namespace {
39class UnreachableBlockElimLegacyPass : public FunctionPass {
40 bool runOnFunction(Function &F) override {
42 }
43
44public:
45 static char ID; // Pass identification, replacement for typeid
46 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
49 }
50
51 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 }
54};
55}
56char UnreachableBlockElimLegacyPass::ID = 0;
57INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
58 "Remove unreachable blocks from the CFG", false, false)
59
61 return new UnreachableBlockElimLegacyPass();
62}
63
66 bool Changed = llvm::EliminateUnreachableBlocks(F);
67 if (!Changed)
71 return PA;
72}
73
74namespace {
75class UnreachableMachineBlockElim {
77 MachineLoopInfo *MLI;
78
79public:
80 UnreachableMachineBlockElim(MachineDominatorTree *MDT, MachineLoopInfo *MLI)
81 : MDT(MDT), MLI(MLI) {}
82 bool run(MachineFunction &MF);
83};
84
85class UnreachableMachineBlockElimLegacy : public MachineFunctionPass {
86 bool runOnMachineFunction(MachineFunction &F) override;
87 void getAnalysisUsage(AnalysisUsage &AU) const override;
88
89public:
90 static char ID; // Pass identification, replacement for typeid
91 UnreachableMachineBlockElimLegacy() : MachineFunctionPass(ID) {}
92};
93} // namespace
94
95char UnreachableMachineBlockElimLegacy::ID = 0;
96
97INITIALIZE_PASS(UnreachableMachineBlockElimLegacy,
98 "unreachable-mbb-elimination",
99 "Remove unreachable machine basic blocks", false, false)
100
102 UnreachableMachineBlockElimLegacy::ID;
103
104void UnreachableMachineBlockElimLegacy::getAnalysisUsage(
105 AnalysisUsage &AU) const {
106 AU.addPreserved<MachineLoopInfoWrapperPass>();
107 AU.addPreserved<MachineDominatorTreeWrapperPass>();
109}
110
115 auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(MF);
116
117 if (!UnreachableMachineBlockElim(MDT, MLI).run(MF))
118 return PreservedAnalyses::all();
119
122 .preserve<MachineDominatorTreeAnalysis>();
123}
124
125bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
126 MachineFunction &MF) {
128 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
129 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
130 MachineLoopInfoWrapperPass *MLIWrapper =
131 getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
132 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
133
134 return UnreachableMachineBlockElim(MDT, MLI).run(MF);
135}
136
137bool UnreachableMachineBlockElim::run(MachineFunction &F) {
139 bool ModifiedPHI = false;
140
141 // Mark all reachable blocks.
142 for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
143 (void)BB/* Mark all reachable blocks */;
144
145 // Loop over all dead blocks, remembering them and deleting all instructions
146 // in them.
147 std::vector<MachineBasicBlock*> DeadBlocks;
148 for (MachineBasicBlock &BB : F) {
149 // Test for deadness.
150 if (!Reachable.count(&BB)) {
151 DeadBlocks.push_back(&BB);
152
153 // Update dominator and loop info.
154 if (MLI) MLI->removeBlock(&BB);
155 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
156
157 while (!BB.succ_empty()) {
158 MachineBasicBlock* succ = *BB.succ_begin();
159
160 for (MachineInstr &Phi : succ->phis()) {
161 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
162 if (Phi.getOperand(i).isMBB() &&
163 Phi.getOperand(i).getMBB() == &BB) {
164 Phi.removeOperand(i);
165 Phi.removeOperand(i - 1);
166 }
167 }
168 }
169
170 BB.removeSuccessor(BB.succ_begin());
171 }
172 }
173 }
174
175 // Actually remove the blocks now.
176 for (MachineBasicBlock *BB : DeadBlocks) {
177 // Remove any call information for calls in the block.
178 for (auto &I : BB->instrs())
179 if (I.shouldUpdateAdditionalCallInfo())
180 BB->getParent()->eraseAdditionalCallInfo(&I);
181
182 BB->eraseFromParent();
183 }
184
185 // Cleanup PHI nodes.
186 for (MachineBasicBlock &BB : F) {
187 // Prune unneeded PHI entries.
189 BB.predecessors());
190 for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
191 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
192 if (!preds.count(Phi.getOperand(i).getMBB())) {
193 Phi.removeOperand(i);
194 Phi.removeOperand(i - 1);
195 ModifiedPHI = true;
196 }
197 }
198
199 if (Phi.getNumOperands() == 3) {
200 const MachineOperand &Input = Phi.getOperand(1);
201 const MachineOperand &Output = Phi.getOperand(0);
202 Register InputReg = Input.getReg();
203 Register OutputReg = Output.getReg();
204 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
205 ModifiedPHI = true;
206
207 if (InputReg != OutputReg) {
208 MachineRegisterInfo &MRI = F.getRegInfo();
209 unsigned InputSub = Input.getSubReg();
210 if (InputSub == 0 &&
211 MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
212 !Input.isUndef()) {
213 MRI.replaceRegWith(OutputReg, InputReg);
214 } else {
215 // The input register to the PHI has a subregister or it can't be
216 // constrained to the proper register class or it is undef:
217 // insert a COPY instead of simply replacing the output
218 // with the input.
219 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
220 BuildMI(BB, BB.getFirstNonPHI(), Phi.getDebugLoc(),
221 TII->get(TargetOpcode::COPY), OutputReg)
222 .addReg(InputReg, getRegState(Input), InputSub);
223 }
224 Phi.eraseFromParent();
225 }
226 }
227 }
228 }
229
230 F.RenumberBlocks();
231 if (MDT)
232 MDT->updateBlockNumbers();
233
234 return (!DeadBlocks.empty() || ModifiedPHI);
235}
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.
const HexagonInstrInfo * TII
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
This file defines the SmallPtrSet class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:431
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:284
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.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:322
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
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.
Definition: MachineInstr.h:72
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.
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...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:112
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:19
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:470
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
TargetInstrInfo - Interface to description of machine instruction set.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(MachineFunction &F, MachineFunctionAnalysisManager &AM)
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: AddressRanges.h:18
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:663
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.
LLVM_ABI FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...