LLVM  5.0.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 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Transforms/Scalar.h"
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "loop-instsimplify"
34 
35 STATISTIC(NumSimplified, "Number of redundant instructions simplified");
36 
37 static bool SimplifyLoopInst(Loop *L, DominatorTree *DT, LoopInfo *LI,
38  AssumptionCache *AC,
39  const TargetLibraryInfo *TLI) {
41  L->getUniqueExitBlocks(ExitBlocks);
42  array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
43 
44  SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
45 
46  // The bit we are stealing from the pointer represents whether this basic
47  // block is the header of a subloop, in which case we only process its phis.
48  typedef PointerIntPair<BasicBlock *, 1> WorklistItem;
51 
52  bool Changed = false;
53  bool LocalChanged;
54  do {
55  LocalChanged = false;
56 
57  VisitStack.clear();
58  Visited.clear();
59 
60  VisitStack.push_back(WorklistItem(L->getHeader(), false));
61 
62  while (!VisitStack.empty()) {
63  WorklistItem Item = VisitStack.pop_back_val();
64  BasicBlock *BB = Item.getPointer();
65  bool IsSubloopHeader = Item.getInt();
66  const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
67 
68  // Simplify instructions in the current basic block.
69  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
70  Instruction *I = &*BI++;
71 
72  // The first time through the loop ToSimplify is empty and we try to
73  // simplify all instructions. On later iterations ToSimplify is not
74  // empty and we only bother simplifying instructions that are in it.
75  if (!ToSimplify->empty() && !ToSimplify->count(I))
76  continue;
77 
78  // Don't bother simplifying unused instructions.
79  if (!I->use_empty()) {
80  Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC});
81  if (V && LI->replacementPreservesLCSSAForm(I, V)) {
82  // Mark all uses for resimplification next time round the loop.
83  for (User *U : I->users())
84  Next->insert(cast<Instruction>(U));
85 
86  I->replaceAllUsesWith(V);
87  LocalChanged = true;
88  ++NumSimplified;
89  }
90  }
92  // RecursivelyDeleteTriviallyDeadInstruction can remove more than one
93  // instruction, so simply incrementing the iterator does not work.
94  // When instructions get deleted re-iterate instead.
95  BI = BB->begin();
96  BE = BB->end();
97  LocalChanged = true;
98  }
99 
100  if (IsSubloopHeader && !isa<PHINode>(I))
101  break;
102  }
103 
104  // Add all successors to the worklist, except for loop exit blocks and the
105  // bodies of subloops. We visit the headers of loops so that we can
106  // process
107  // their phis, but we contract the rest of the subloop body and only
108  // follow
109  // edges leading back to the original loop.
110  for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
111  ++SI) {
112  BasicBlock *SuccBB = *SI;
113  if (!Visited.insert(SuccBB).second)
114  continue;
115 
116  const Loop *SuccLoop = LI->getLoopFor(SuccBB);
117  if (SuccLoop && SuccLoop->getHeader() == SuccBB &&
118  L->contains(SuccLoop)) {
119  VisitStack.push_back(WorklistItem(SuccBB, true));
120 
121  SmallVector<BasicBlock *, 8> SubLoopExitBlocks;
122  SuccLoop->getExitBlocks(SubLoopExitBlocks);
123 
124  for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
125  BasicBlock *ExitBB = SubLoopExitBlocks[i];
126  if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB).second)
127  VisitStack.push_back(WorklistItem(ExitBB, false));
128  }
129 
130  continue;
131  }
132 
133  bool IsExitBlock =
134  std::binary_search(ExitBlocks.begin(), ExitBlocks.end(), SuccBB);
135  if (IsExitBlock)
136  continue;
137 
138  VisitStack.push_back(WorklistItem(SuccBB, false));
139  }
140  }
141 
142  // Place the list of instructions to simplify on the next loop iteration
143  // into ToSimplify.
144  std::swap(ToSimplify, Next);
145  Next->clear();
146 
147  Changed |= LocalChanged;
148  } while (LocalChanged);
149 
150  return Changed;
151 }
152 
153 namespace {
154 class LoopInstSimplifyLegacyPass : public LoopPass {
155 public:
156  static char ID; // Pass ID, replacement for typeid
157  LoopInstSimplifyLegacyPass() : LoopPass(ID) {
159  }
160 
161  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
162  if (skipLoop(L))
163  return false;
165  getAnalysisIfAvailable<DominatorTreeWrapperPass>();
166  DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
167  LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
168  AssumptionCache *AC =
169  &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
170  *L->getHeader()->getParent());
171  const TargetLibraryInfo *TLI =
172  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
173 
174  return SimplifyLoopInst(L, DT, LI, AC, TLI);
175  }
176 
177  void getAnalysisUsage(AnalysisUsage &AU) const override {
180  AU.setPreservesCFG();
182  }
183 };
184 }
185 
188  LPMUpdater &) {
189  if (!SimplifyLoopInst(&L, &AR.DT, &AR.LI, &AR.AC, &AR.TLI))
190  return PreservedAnalyses::all();
191 
192  auto PA = getLoopPassPreservedAnalyses();
193  PA.preserveSet<CFGAnalyses>();
194  return PA;
195 }
196 
198 INITIALIZE_PASS_BEGIN(LoopInstSimplifyLegacyPass, "loop-instsimplify",
199  "Simplify instructions in loops", false, false)
203 INITIALIZE_PASS_END(LoopInstSimplifyLegacyPass, "loop-instsimplify",
204  "Simplify instructions in loops", false, false)
205 
207  return new LoopInstSimplifyLegacyPass();
208 }
MachineLoop * L
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
INITIALIZE_PASS_BEGIN(LoopInstSimplifyLegacyPass,"loop-instsimplify","Simplify instructions in loops", false, false) INITIALIZE_PASS_END(LoopInstSimplifyLegacyPass
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
STATISTIC(NumFunctions,"Total number of functions")
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
static bool SimplifyLoopInst(Loop *L, DominatorTree *DT, LoopInfo *LI, AssumptionCache *AC, const TargetLibraryInfo *TLI)
DataLayout DL
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:585
BlockT * getHeader() const
Definition: LoopInfo.h:103
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
DominatorTree & getDomTree()
Definition: Dominators.h:271
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:62
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:106
Pass * createLoopInstSimplifyPass()
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
loop instsimplify
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:109
void initializeLoopInstSimplifyLegacyPassPass(PassRegistry &)
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:771
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
PointerIntPair - This class implements a pair of a pointer and small integer.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
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:372
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:370
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfo.cpp:361
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
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:423
loop Simplify instructions in loops
iterator end()
Definition: BasicBlock.h:254
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.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:382
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
iterator_range< user_iterator > users()
Definition: Value.h:395
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:114
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
loop Simplify instructions in false
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:1022
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
bool use_empty() const
Definition: Value.h:322
LLVM Value Representation.
Definition: Value.h:73
inst_range instructions(Function *F)
Definition: InstIterator.h:134
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:261
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
Definition: LoopInfo.h:709
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.