LLVM 24.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"
36#include "llvm/IR/Dominators.h"
38#include "llvm/Pass.h"
40using namespace llvm;
41
42namespace {
43class UnreachableBlockElimLegacyPass : public FunctionPass {
44 bool runOnFunction(Function &F) override {
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
63 return new UnreachableBlockElimLegacyPass();
64}
65
76
77namespace {
78class UnreachableMachineBlockElim {
81 MachineLoopInfo *MLI;
82
83public:
84 UnreachableMachineBlockElim(MachineDominatorTree *MDT,
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
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>();
118}
119
125 auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(MF);
126
127 if (!UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF))
128 return PreservedAnalyses::all();
129
132 .preserve<MachineDominatorTreeAnalysis>()
134 .preserve<MachineBlockFrequencyAnalysis>();
135}
136
137bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
138 MachineFunction &MF) {
140 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
142 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
143 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
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) {
155 bool ModifiedPHI = false;
156
157 // Mark all reachable blocks.
158 for (MachineBasicBlock *BB : depth_first_ext(&F, 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(&BB)) {
167 DeadBlocks.push_back(&BB);
168
169 // Update dominator and loop info.
170 if (MLI) MLI->removeBlock(&BB);
171 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
172 if (MPDT && MPDT->getNode(&BB))
173 MPDT->eraseNode(&BB);
174
175 while (!BB.succ_empty()) {
176 (*BB.succ_begin())->removePHIsIncomingValuesForPredecessor(BB);
177 BB.removeSuccessor(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(&I);
188
189 BB->eraseFromParent();
190 }
191
192 // Cleanup PHI nodes.
193 for (MachineBasicBlock &BB : F) {
194 // Prune unneeded PHI entries.
196 BB.predecessors());
197 for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
198 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
199 if (!preds.count(Phi.getOperand(i).getMBB())) {
200 Phi.removeOperand(i);
201 Phi.removeOperand(i - 1);
202 ModifiedPHI = true;
203 }
204 }
205
206 if (Phi.getNumOperands() == 3) {
207 const MachineOperand &Input = Phi.getOperand(1);
208 const MachineOperand &Output = Phi.getOperand(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(InputReg, MRI.getRegClass(OutputReg)) &&
219 !Input.isUndef()) {
220 MRI.replaceRegWith(OutputReg, 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, BB.getFirstNonPHI(), Phi.getDebugLoc(),
228 TII->get(TargetOpcode::COPY), OutputReg)
229 .addReg(InputReg, getRegState(Input), InputSub);
230 }
231 Phi.eraseFromParent();
232 }
233 }
234 }
235 }
236
237 F.RenumberBlocks();
238
239 return (!DeadBlocks.empty() || ModifiedPHI);
240}
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:270
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, RegState Flags={}, 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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
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.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI 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.
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:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
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.
RegState 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...