LLVM  3.7.0
LoopInstSimplify.cpp
Go to the documentation of this file.
1 //===- LoopInstSimplify.cpp - Loop Instruction 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 pass performs lightweight instruction simplification on loop bodies.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/Support/Debug.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "loop-instsimplify"
31 
32 STATISTIC(NumSimplified, "Number of redundant instructions simplified");
33 
34 namespace {
35  class LoopInstSimplify : public LoopPass {
36  public:
37  static char ID; // Pass ID, replacement for typeid
38  LoopInstSimplify() : LoopPass(ID) {
40  }
41 
42  bool runOnLoop(Loop*, LPPassManager&) override;
43 
44  void getAnalysisUsage(AnalysisUsage &AU) const override {
45  AU.setPreservesCFG();
53  }
54  };
55 }
56 
57 char LoopInstSimplify::ID = 0;
58 INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
59  "Simplify instructions in loops", false, false)
65 INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
66  "Simplify instructions in loops", false, false)
67 
69  return new LoopInstSimplify();
70 }
71 
72 bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
73  if (skipOptnoneFunction(L))
74  return false;
75 
77  getAnalysisIfAvailable<DominatorTreeWrapperPass>();
78  DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
79  LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
80  const TargetLibraryInfo *TLI =
81  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
82  auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
83  *L->getHeader()->getParent());
84 
85  SmallVector<BasicBlock*, 8> ExitBlocks;
86  L->getUniqueExitBlocks(ExitBlocks);
87  array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
88 
89  SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
90 
91  // The bit we are stealing from the pointer represents whether this basic
92  // block is the header of a subloop, in which case we only process its phis.
93  typedef PointerIntPair<BasicBlock*, 1> WorklistItem;
96 
97  bool Changed = false;
98  bool LocalChanged;
99  do {
100  LocalChanged = false;
101 
102  VisitStack.clear();
103  Visited.clear();
104 
105  VisitStack.push_back(WorklistItem(L->getHeader(), false));
106 
107  while (!VisitStack.empty()) {
108  WorklistItem Item = VisitStack.pop_back_val();
109  BasicBlock *BB = Item.getPointer();
110  bool IsSubloopHeader = Item.getInt();
111  const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
112 
113  // Simplify instructions in the current basic block.
114  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
115  Instruction *I = BI++;
116 
117  // The first time through the loop ToSimplify is empty and we try to
118  // simplify all instructions. On later iterations ToSimplify is not
119  // empty and we only bother simplifying instructions that are in it.
120  if (!ToSimplify->empty() && !ToSimplify->count(I))
121  continue;
122 
123  // Don't bother simplifying unused instructions.
124  if (!I->use_empty()) {
125  Value *V = SimplifyInstruction(I, DL, TLI, DT, &AC);
126  if (V && LI->replacementPreservesLCSSAForm(I, V)) {
127  // Mark all uses for resimplification next time round the loop.
128  for (User *U : I->users())
129  Next->insert(cast<Instruction>(U));
130 
131  I->replaceAllUsesWith(V);
132  LocalChanged = true;
133  ++NumSimplified;
134  }
135  }
137  if (res) {
138  // RecursivelyDeleteTriviallyDeadInstruction can remove
139  // more than one instruction, so simply incrementing the
140  // iterator does not work. When instructions get deleted
141  // re-iterate instead.
142  BI = BB->begin(); BE = BB->end();
143  LocalChanged |= res;
144  }
145 
146  if (IsSubloopHeader && !isa<PHINode>(I))
147  break;
148  }
149 
150  // Add all successors to the worklist, except for loop exit blocks and the
151  // bodies of subloops. We visit the headers of loops so that we can process
152  // their phis, but we contract the rest of the subloop body and only follow
153  // edges leading back to the original loop.
154  for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
155  ++SI) {
156  BasicBlock *SuccBB = *SI;
157  if (!Visited.insert(SuccBB).second)
158  continue;
159 
160  const Loop *SuccLoop = LI->getLoopFor(SuccBB);
161  if (SuccLoop && SuccLoop->getHeader() == SuccBB
162  && L->contains(SuccLoop)) {
163  VisitStack.push_back(WorklistItem(SuccBB, true));
164 
165  SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
166  SuccLoop->getExitBlocks(SubLoopExitBlocks);
167 
168  for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
169  BasicBlock *ExitBB = SubLoopExitBlocks[i];
170  if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB).second)
171  VisitStack.push_back(WorklistItem(ExitBB, false));
172  }
173 
174  continue;
175  }
176 
177  bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
178  ExitBlocks.end(), SuccBB);
179  if (IsExitBlock)
180  continue;
181 
182  VisitStack.push_back(WorklistItem(SuccBB, false));
183  }
184  }
185 
186  // Place the list of instructions to simplify on the next loop iteration
187  // into ToSimplify.
188  std::swap(ToSimplify, Next);
189  Next->clear();
190 
191  Changed |= LocalChanged;
192  } while (LocalChanged);
193 
194  return Changed;
195 }
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:82
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
Hexagon generate extract instructions
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...
STATISTIC(NumFunctions,"Total number of functions")
ScalarEvolution - This class is the main scalar evolution driver.
An immutable pass that tracks lazily created AssumptionCache objects.
LoopT * getLoopFor(const BlockT *BB) const
getLoopFor - Return the inner most loop that BB lives in.
Definition: LoopInfo.h:540
BlockT * getHeader() const
Definition: LoopInfo.h:96
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:70
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:406
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:75
DominatorTree & getDomTree()
Definition: Dominators.h:213
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
getExitBlocks - Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:64
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
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
AnalysisUsage & addPreservedID(const void *ID)
Pass * createLoopInstSimplifyPass()
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:351
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:67
loop instsimplify
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:107
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:287
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
PointerIntPair - This class implements a pair of a pointer and small integer.
char & LCSSAID
Definition: LCSSA.cpp:312
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:264
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
contains - Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:105
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a trivially dead instruction...
Definition: Local.cpp:340
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
getUniqueExitBlocks - Return all unique successor blocks of this loop.
Definition: LoopInfo.cpp:347
char & LoopSimplifyID
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
loop Simplify instructions in loops
iterator end()
Definition: BasicBlock.h:233
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:276
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Provides information about what library functions are available for the current target.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:263
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:576
INITIALIZE_PASS_BEGIN(LoopInstSimplify,"loop-instsimplify","Simplify instructions in loops", false, false) INITIALIZE_PASS_END(LoopInstSimplify
iterator_range< user_iterator > users()
Definition: Value.h:300
loop Simplify instructions in false
#define I(x, y, z)
Definition: MD5.cpp:54
bool use_empty() const
Definition: Value.h:275
LLVM Value Representation.
Definition: Value.h:69
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:737
Value * SimplifyInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
SimplifyInstruction - See if we can compute a simplified version of this instruction.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:203
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
replacementPreservesLCSSAForm - Returns true if replacing From with To everywhere is guaranteed to pr...
Definition: LoopInfo.h:662
void initializeLoopInstSimplifyPass(PassRegistry &)