LLVM 20.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 {
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>();
95}
96
97bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
99 bool ModifiedPHI = false;
100
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(&F, 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(&BB)) {
118 DeadBlocks.push_back(&BB);
119
120 // Update dominator and loop info.
121 if (MLI) MLI->removeBlock(&BB);
122 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&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(i);
132 Phi.removeOperand(i - 1);
133 }
134 }
135 }
136
137 BB.removeSuccessor(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(&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(BB.phis())) {
158 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
159 if (!preds.count(Phi.getOperand(i).getMBB())) {
160 Phi.removeOperand(i);
161 Phi.removeOperand(i - 1);
162 ModifiedPHI = true;
163 }
164 }
165
166 if (Phi.getNumOperands() == 3) {
167 const MachineOperand &Input = Phi.getOperand(1);
168 const MachineOperand &Output = Phi.getOperand(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(InputReg, MRI.getRegClass(OutputReg)) &&
179 !Input.isUndef()) {
180 MRI.replaceRegWith(OutputReg, 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, BB.getFirstNonPHI(), Phi.getDebugLoc(),
188 TII->get(TargetOpcode::COPY), OutputReg)
189 .addReg(InputReg, getRegState(Input), InputSub);
190 }
191 Phi.eraseFromParent();
192 }
193 }
194 }
195 }
196
197 F.RenumberBlocks();
198 if (MDT)
199 MDT->updateBlockNumbers();
200
201 return (!DeadBlocks.empty() || ModifiedPHI);
202}
unsigned const MachineRegisterInfo * MRI
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:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
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:279
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:317
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
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.
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:69
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 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:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:131
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:452
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
TargetInstrInfo - Interface to description of machine instruction set.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &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)
FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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:657
void initializeUnreachableBlockElimLegacyPassPass(PassRegistry &)
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.
char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.