LLVM  10.0.0svn
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 
24 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/IR/CFG.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/Pass.h"
41 using namespace llvm;
42 
43 namespace {
44 class UnreachableBlockElimLegacyPass : public FunctionPass {
45  bool runOnFunction(Function &F) override {
47  }
48 
49 public:
50  static char ID; // Pass identification, replacement for typeid
51  UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
54  }
55 
56  void getAnalysisUsage(AnalysisUsage &AU) const override {
58  }
59 };
60 }
62 INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
63  "Remove unreachable blocks from the CFG", false, false)
64 
66  return new UnreachableBlockElimLegacyPass();
67 }
68 
71  bool Changed = llvm::EliminateUnreachableBlocks(F);
72  if (!Changed)
73  return PreservedAnalyses::all();
76  return PA;
77 }
78 
79 namespace {
80  class UnreachableMachineBlockElim : public MachineFunctionPass {
81  bool runOnMachineFunction(MachineFunction &F) override;
82  void getAnalysisUsage(AnalysisUsage &AU) const override;
83  MachineModuleInfo *MMI;
84  public:
85  static char ID; // Pass identification, replacement for typeid
86  UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
87  };
88 }
90 
91 INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
92  "Remove unreachable machine basic blocks", false, false)
93 
95 
96 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
100 }
101 
102 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
104  bool ModifiedPHI = false;
105 
106  auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
107  MMI = MMIWP ? &MMIWP->getMMI() : nullptr;
108  MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
109  MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
110 
111  // Mark all reachable blocks.
112  for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
113  (void)BB/* Mark all reachable blocks */;
114 
115  // Loop over all dead blocks, remembering them and deleting all instructions
116  // in them.
117  std::vector<MachineBasicBlock*> DeadBlocks;
118  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
119  MachineBasicBlock *BB = &*I;
120 
121  // Test for deadness.
122  if (!Reachable.count(BB)) {
123  DeadBlocks.push_back(BB);
124 
125  // Update dominator and loop info.
126  if (MLI) MLI->removeBlock(BB);
127  if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB);
128 
129  while (BB->succ_begin() != BB->succ_end()) {
130  MachineBasicBlock* succ = *BB->succ_begin();
131 
132  MachineBasicBlock::iterator start = succ->begin();
133  while (start != succ->end() && start->isPHI()) {
134  for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
135  if (start->getOperand(i).isMBB() &&
136  start->getOperand(i).getMBB() == BB) {
137  start->RemoveOperand(i);
138  start->RemoveOperand(i-1);
139  }
140 
141  start++;
142  }
143 
144  BB->removeSuccessor(BB->succ_begin());
145  }
146  }
147  }
148 
149  // Actually remove the blocks now.
150  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) {
151  // Remove any call site information for calls in the block.
152  for (auto &I : DeadBlocks[i]->instrs())
153  if (I.isCall(MachineInstr::IgnoreBundle))
154  DeadBlocks[i]->getParent()->eraseCallSiteInfo(&I);
155 
156  DeadBlocks[i]->eraseFromParent();
157  }
158 
159  // Cleanup PHI nodes.
160  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
161  MachineBasicBlock *BB = &*I;
162  // Prune unneeded PHI entries.
164  BB->pred_end());
166  while (phi != BB->end() && phi->isPHI()) {
167  for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
168  if (!preds.count(phi->getOperand(i).getMBB())) {
169  phi->RemoveOperand(i);
170  phi->RemoveOperand(i-1);
171  ModifiedPHI = true;
172  }
173 
174  if (phi->getNumOperands() == 3) {
175  const MachineOperand &Input = phi->getOperand(1);
176  const MachineOperand &Output = phi->getOperand(0);
177  Register InputReg = Input.getReg();
178  Register OutputReg = Output.getReg();
179  assert(Output.getSubReg() == 0 && "Cannot have output subregister");
180  ModifiedPHI = true;
181 
182  if (InputReg != OutputReg) {
184  unsigned InputSub = Input.getSubReg();
185  if (InputSub == 0 &&
186  MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
187  !Input.isUndef()) {
188  MRI.replaceRegWith(OutputReg, InputReg);
189  } else {
190  // The input register to the PHI has a subregister or it can't be
191  // constrained to the proper register class or it is undef:
192  // insert a COPY instead of simply replacing the output
193  // with the input.
195  BuildMI(*BB, BB->getFirstNonPHI(), phi->getDebugLoc(),
196  TII->get(TargetOpcode::COPY), OutputReg)
197  .addReg(InputReg, getRegState(Input), InputSub);
198  }
199  phi++->eraseFromParent();
200  }
201  continue;
202  }
203 
204  ++phi;
205  }
206  }
207 
208  F.RenumberBlocks();
209 
210  return (!DeadBlocks.empty() || ModifiedPHI);
211 }
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...
MachineDomTreeNode * getNode(MachineBasicBlock *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
unsigned getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
unsigned getSubReg() const
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:230
F(f)
void initializeUnreachableBlockElimLegacyPassPass(PassRegistry &)
void eraseNode(MachineBasicBlock *BB)
eraseNode - Removes a node from the dominator tree.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
constexpr double phi
Definition: MathExtras.h:71
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...
virtual const TargetInstrInfo * getInstrInfo() const
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...
TargetInstrInfo - Interface to description of machine instruction set.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static bool runOnFunction(Function &F, bool PostInlining)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
Represent the analysis usage information of a pass.
constexpr double e
Definition: MathExtras.h:57
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
MachineOperand class - Representation of each machine instruction operand.
bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
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.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
#define I(x, y, z)
Definition: MD5.cpp:58
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:174
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Function.cpp:226
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const Function * getParent(const Value *V)
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
Register getReg() const
getReg - Returns the register number.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim", "Remove unreachable blocks from the CFG", false, false) FunctionPass *llvm
This class contains meta information specific to a module.