LLVM  4.0.0
SimplifyCFGPass.cpp
Go to the documentation of this file.
1 //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
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 file implements dead code elimination and basic block merging, along
11 // with a collection of other peephole control flow optimizations. For example:
12 //
13 // * Removes basic blocks with no predecessors.
14 // * Merges a basic block into its predecessor if there is only one and the
15 // predecessor only has one successor.
16 // * Eliminates PHI nodes for basic blocks with a single predecessor.
17 // * Eliminates a basic block that only contains an unconditional branch.
18 // * Changes invoke instructions to nounwind functions to be calls.
19 // * Change things like "if (x) if (y)" into "if (x&y)".
20 // * etc..
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/CFG.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Pass.h"
40 #include "llvm/Transforms/Scalar.h"
43 #include <utility>
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "simplifycfg"
47 
48 static cl::opt<unsigned>
49 UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1),
50  cl::desc("Control the number of bonus instructions (default = 1)"));
51 
52 STATISTIC(NumSimpl, "Number of blocks simplified");
53 
54 /// If we have more than one empty (other than phi node) return blocks,
55 /// merge them together to promote recursive block merging.
57  bool Changed = false;
58 
59  BasicBlock *RetBlock = nullptr;
60 
61  // Scan all the blocks in the function, looking for empty return blocks.
62  for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
63  BasicBlock &BB = *BBI++;
64 
65  // Only look at return blocks.
67  if (!Ret) continue;
68 
69  // Only look at the block if it is empty or the only other thing in it is a
70  // single PHI node that is the operand to the return.
71  if (Ret != &BB.front()) {
72  // Check for something else in the block.
74  --I;
75  // Skip over debug info.
76  while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
77  --I;
78  if (!isa<DbgInfoIntrinsic>(I) &&
79  (!isa<PHINode>(I) || I != BB.begin() || Ret->getNumOperands() == 0 ||
80  Ret->getOperand(0) != &*I))
81  continue;
82  }
83 
84  // If this is the first returning block, remember it and keep going.
85  if (!RetBlock) {
86  RetBlock = &BB;
87  continue;
88  }
89 
90  // Otherwise, we found a duplicate return block. Merge the two.
91  Changed = true;
92 
93  // Case when there is no input to the return or when the returned values
94  // agree is trivial. Note that they can't agree if there are phis in the
95  // blocks.
96  if (Ret->getNumOperands() == 0 ||
97  Ret->getOperand(0) ==
98  cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
99  BB.replaceAllUsesWith(RetBlock);
100  BB.eraseFromParent();
101  continue;
102  }
103 
104  // If the canonical return block has no PHI node, create one now.
105  PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
106  if (!RetBlockPHI) {
107  Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
108  pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
109  RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
110  std::distance(PB, PE), "merge",
111  &RetBlock->front());
112 
113  for (pred_iterator PI = PB; PI != PE; ++PI)
114  RetBlockPHI->addIncoming(InVal, *PI);
115  RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
116  }
117 
118  // Turn BB into a block that just unconditionally branches to the return
119  // block. This handles the case when the two return blocks have a common
120  // predecessor but that return different things.
121  RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
123  BranchInst::Create(RetBlock, &BB);
124  }
125 
126  return Changed;
127 }
128 
129 /// Call SimplifyCFG on all the blocks in the function,
130 /// iterating until no more changes are made.
132  AssumptionCache *AC,
133  unsigned BonusInstThreshold) {
134  bool Changed = false;
135  bool LocalChange = true;
136 
138  FindFunctionBackedges(F, Edges);
139  SmallPtrSet<BasicBlock *, 16> LoopHeaders;
140  for (unsigned i = 0, e = Edges.size(); i != e; ++i)
141  LoopHeaders.insert(const_cast<BasicBlock *>(Edges[i].second));
142 
143  while (LocalChange) {
144  LocalChange = false;
145 
146  // Loop over all of the basic blocks and remove them if they are unneeded.
147  for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
148  if (SimplifyCFG(&*BBIt++, TTI, BonusInstThreshold, AC, &LoopHeaders)) {
149  LocalChange = true;
150  ++NumSimpl;
151  }
152  }
153  Changed |= LocalChange;
154  }
155  return Changed;
156 }
157 
159  AssumptionCache *AC, int BonusInstThreshold) {
160  bool EverChanged = removeUnreachableBlocks(F);
161  EverChanged |= mergeEmptyReturnBlocks(F);
162  EverChanged |= iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
163 
164  // If neither pass changed anything, we're done.
165  if (!EverChanged) return false;
166 
167  // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
168  // removeUnreachableBlocks is needed to nuke them, which means we should
169  // iterate between the two optimizations. We structure the code like this to
170  // avoid rerunning iterativelySimplifyCFG if the second pass of
171  // removeUnreachableBlocks doesn't do anything.
172  if (!removeUnreachableBlocks(F))
173  return true;
174 
175  do {
176  EverChanged = iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
177  EverChanged |= removeUnreachableBlocks(F);
178  } while (EverChanged);
179 
180  return true;
181 }
182 
184  : BonusInstThreshold(UserBonusInstThreshold) {}
185 
186 SimplifyCFGPass::SimplifyCFGPass(int BonusInstThreshold)
187  : BonusInstThreshold(BonusInstThreshold) {}
188 
191  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
192  auto &AC = AM.getResult<AssumptionAnalysis>(F);
193 
194  if (!simplifyFunctionCFG(F, TTI, &AC, BonusInstThreshold))
195  return PreservedAnalyses::all();
197  PA.preserve<GlobalsAA>();
198  return PA;
199 }
200 
201 namespace {
202 struct CFGSimplifyPass : public FunctionPass {
203  static char ID; // Pass identification, replacement for typeid
204  unsigned BonusInstThreshold;
205  std::function<bool(const Function &)> PredicateFtor;
206 
207  CFGSimplifyPass(int T = -1,
208  std::function<bool(const Function &)> Ftor = nullptr)
209  : FunctionPass(ID), PredicateFtor(std::move(Ftor)) {
210  BonusInstThreshold = (T == -1) ? UserBonusInstThreshold : unsigned(T);
212  }
213  bool runOnFunction(Function &F) override {
214  if (skipFunction(F) || (PredicateFtor && !PredicateFtor(F)))
215  return false;
216 
217  AssumptionCache *AC =
218  &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
219  const TargetTransformInfo &TTI =
220  getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
221  return simplifyFunctionCFG(F, TTI, AC, BonusInstThreshold);
222  }
223 
224  void getAnalysisUsage(AnalysisUsage &AU) const override {
228  }
229 };
230 }
231 
232 char CFGSimplifyPass::ID = 0;
233 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
234  false)
237 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
238  false)
239 
240 // Public interface to the CFGSimplification pass
241 FunctionPass *
243  std::function<bool(const Function &)> Ftor) {
244  return new CFGSimplifyPass(Threshold, std::move(Ftor));
245 }
Legacy wrapper pass to provide the GlobalsAAResult object.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:76
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, unsigned BonusInstThreshold, AssumptionCache *AC=nullptr, SmallPtrSetImpl< BasicBlock * > *LoopHeaders=nullptr)
This function is used to do simplification of a CFG.
STATISTIC(NumFunctions,"Total number of functions")
size_t i
This is the interface for a simple mod/ref and alias analysis over globals.
iterator end()
Definition: Function.h:537
unsigned getNumOperands() const
Definition: User.h:167
An immutable pass that tracks lazily created AssumptionCache objects.
static cl::opt< unsigned > UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1), cl::desc("Control the number of bonus instructions (default = 1)"))
static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI, AssumptionCache *AC, int BonusInstThreshold)
A cache of .assume calls within a function.
Analysis pass providing the TargetTransformInfo.
const Instruction & front() const
Definition: BasicBlock.h:240
Simplify the CFG
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:228
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:53
Simplify the false
This file contains the simple types necessary to represent the attributes associated with functions a...
#define F(x, y, z)
Definition: MD5.cpp:51
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:401
iterator begin()
Definition: Function.h:535
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
simplifycfg
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:653
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:368
FunctionPass * createCFGSimplificationPass(int Threshold=-1, std::function< bool(const Function &)> Ftor=nullptr)
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:116
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Value * getOperand(unsigned i) const
Definition: User.h:145
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:119
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
A function analysis which provides an AssumptionCache.
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:425
void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock * > > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them...
Definition: CFG.cpp:27
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:1648
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setOperand(unsigned i, Value *Val)
Definition: User.h:150
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
Definition: BasicBlock.cpp:97
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
INITIALIZE_PASS_BEGIN(CFGSimplifyPass,"simplifycfg","Simplify the CFG", false, false) INITIALIZE_PASS_END(CFGSimplifyPass
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:287
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:120
static bool mergeEmptyReturnBlocks(Function &F)
If we have more than one empty (other than phi node) return blocks, merge them together to promote re...
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
void initializeCFGSimplifyPassPass(PassRegistry &)
aarch64 promote const
SimplifyCFGPass()
Construct a pass with the default thresholds.
LLVM Value Representation.
Definition: Value.h:71
print Print MemDeps of function
A container for analyses that lazily runs them and caches their results.
This pass exposes codegen information to IR-level passes.
static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI, AssumptionCache *AC, unsigned BonusInstThreshold)
Call SimplifyCFG on all the blocks in the function, iterating until no more changes are made...