LLVM  3.7.0
UnreachableBlockElim.cpp
Go to the documentation of this file.
1 //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is an extremely simple version of the SimplifyCFG pass. Its sole
11 // job is to delete LLVM basic blocks that are not reachable from the entry
12 // node. To do this, it performs a simple depth first traversal of the CFG,
13 // then deletes any unvisited nodes.
14 //
15 // Note that this pass is really a hack. In particular, the instruction
16 // selectors for various targets should just not generate code for unreachable
17 // blocks. Until LLVM has a more systematic way of defining instruction
18 // selectors, however, we cannot really expect them to handle additional
19 // complexity.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/Pass.h"
39 using namespace llvm;
40 
41 namespace {
42  class UnreachableBlockElim : public FunctionPass {
43  bool runOnFunction(Function &F) override;
44  public:
45  static char ID; // Pass identification, replacement for typeid
46  UnreachableBlockElim() : FunctionPass(ID) {
48  }
49 
50  void getAnalysisUsage(AnalysisUsage &AU) const override {
52  }
53  };
54 }
56 INITIALIZE_PASS(UnreachableBlockElim, "unreachableblockelim",
57  "Remove unreachable blocks from the CFG", false, false)
58 
60  return new UnreachableBlockElim();
61 }
62 
63 bool UnreachableBlockElim::runOnFunction(Function &F) {
65 
66  // Mark all reachable blocks.
67  for (BasicBlock *BB : depth_first_ext(&F, Reachable))
68  (void)BB/* Mark all reachable blocks */;
69 
70  // Loop over all dead blocks, remembering them and deleting all instructions
71  // in them.
72  std::vector<BasicBlock*> DeadBlocks;
73  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
74  if (!Reachable.count(I)) {
75  BasicBlock *BB = I;
76  DeadBlocks.push_back(BB);
77  while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
78  PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
79  BB->getInstList().pop_front();
80  }
81  for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
82  (*SI)->removePredecessor(BB);
83  BB->dropAllReferences();
84  }
85 
86  // Actually remove the blocks now.
87  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) {
88  DeadBlocks[i]->eraseFromParent();
89  }
90 
91  return !DeadBlocks.empty();
92 }
93 
94 
95 namespace {
96  class UnreachableMachineBlockElim : public MachineFunctionPass {
97  bool runOnMachineFunction(MachineFunction &F) override;
98  void getAnalysisUsage(AnalysisUsage &AU) const override;
99  MachineModuleInfo *MMI;
100  public:
101  static char ID; // Pass identification, replacement for typeid
102  UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
103  };
104 }
106 
107 INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
108  "Remove unreachable machine basic blocks", false, false)
109 
110 char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
111 
112 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
113  AU.addPreserved<MachineLoopInfo>();
114  AU.addPreserved<MachineDominatorTree>();
116 }
117 
118 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
120  bool ModifiedPHI = false;
121 
122  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
123  MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
124  MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
125 
126  // Mark all reachable blocks.
127  for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
128  (void)BB/* Mark all reachable blocks */;
129 
130  // Loop over all dead blocks, remembering them and deleting all instructions
131  // in them.
132  std::vector<MachineBasicBlock*> DeadBlocks;
133  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
134  MachineBasicBlock *BB = I;
135 
136  // Test for deadness.
137  if (!Reachable.count(BB)) {
138  DeadBlocks.push_back(BB);
139 
140  // Update dominator and loop info.
141  if (MLI) MLI->removeBlock(BB);
142  if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB);
143 
144  while (BB->succ_begin() != BB->succ_end()) {
145  MachineBasicBlock* succ = *BB->succ_begin();
146 
147  MachineBasicBlock::iterator start = succ->begin();
148  while (start != succ->end() && start->isPHI()) {
149  for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
150  if (start->getOperand(i).isMBB() &&
151  start->getOperand(i).getMBB() == BB) {
152  start->RemoveOperand(i);
153  start->RemoveOperand(i-1);
154  }
155 
156  start++;
157  }
158 
159  BB->removeSuccessor(BB->succ_begin());
160  }
161  }
162  }
163 
164  // Actually remove the blocks now.
165  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
166  DeadBlocks[i]->eraseFromParent();
167 
168  // Cleanup PHI nodes.
169  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
170  MachineBasicBlock *BB = I;
171  // Prune unneeded PHI entries.
173  BB->pred_end());
175  while (phi != BB->end() && phi->isPHI()) {
176  for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
177  if (!preds.count(phi->getOperand(i).getMBB())) {
178  phi->RemoveOperand(i);
179  phi->RemoveOperand(i-1);
180  ModifiedPHI = true;
181  }
182 
183  if (phi->getNumOperands() == 3) {
184  unsigned Input = phi->getOperand(1).getReg();
185  unsigned Output = phi->getOperand(0).getReg();
186 
187  MachineInstr* temp = phi;
188  ++phi;
189  temp->eraseFromParent();
190  ModifiedPHI = true;
191 
192  if (Input != Output) {
193  MachineRegisterInfo &MRI = F.getRegInfo();
194  MRI.constrainRegClass(Input, MRI.getRegClass(Output));
195  MRI.replaceRegWith(Output, Input);
196  }
197 
198  continue;
199  }
200 
201  ++phi;
202  }
203  }
204 
205  F.RenumberBlocks();
206 
207  return (!DeadBlocks.empty() || ModifiedPHI);
208 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
iterator end()
Definition: Function.h:459
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:276
F(f)
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:178
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const TargetRegisterClass * getRegClass(unsigned Reg) const
getRegClass - Return the register class of the specified virtual register.
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:104
char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...
iterator begin()
Definition: Function.h:457
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:107
bundle_iterator< MachineInstr, instr_iterator > iterator
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
Represent the analysis usage information of a pass.
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:252
void initializeUnreachableBlockElimPass(PassRegistry &)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
void removeSuccessor(MachineBasicBlock *succ)
removeSuccessor - Remove successor from the successors list of this MachineBasicBlock.
INITIALIZE_PASS(UnreachableBlockElim,"unreachableblockelim","Remove unreachable blocks from the CFG", false, false) FunctionPass *llvm
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:51
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:54
void pop_front()
Definition: ilist.h:555
BasicBlockListType::iterator iterator
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:203
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
Definition: BasicBlock.cpp:204
MachineModuleInfo - This class contains meta information specific to a module.