LLVM  5.0.0
LoopDeletion.cpp
Go to the documentation of this file.
1 //===- LoopDeletion.cpp - Dead Loop Deletion 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 the Dead Loop Deletion Pass. This pass is responsible
11 // for eliminating loops with non-infinite computable trip counts that have no
12 // side effects or volatile instructions, and do not contribute to the
13 // computation of the function's return value.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/PatternMatch.h"
24 #include "llvm/Transforms/Scalar.h"
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "loop-delete"
30 
31 STATISTIC(NumDeleted, "Number of loops deleted");
32 
33 /// This function deletes dead loops. The caller of this function needs to
34 /// guarantee that the loop is infact dead. Here we handle two kinds of dead
35 /// loop. The first kind (\p isLoopDead) is where only invariant values from
36 /// within the loop are used outside of it. The second kind (\p
37 /// isLoopNeverExecuted) is where the loop is provably never executed. We can
38 /// always remove never executed loops since they will not cause any difference
39 /// to program behaviour.
40 ///
41 /// This also updates the relevant analysis information in \p DT, \p SE, and \p
42 /// LI. It also updates the loop PM if an updater struct is provided.
43 // TODO: This function will be used by loop-simplifyCFG as well. So, move this
44 // to LoopUtils.cpp
45 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
46  LoopInfo &LI, LPMUpdater *Updater = nullptr);
47 /// Determines if a loop is dead.
48 ///
49 /// This assumes that we've already checked for unique exit and exiting blocks,
50 /// and that the code is in LCSSA form.
51 static bool isLoopDead(Loop *L, ScalarEvolution &SE,
52  SmallVectorImpl<BasicBlock *> &ExitingBlocks,
53  BasicBlock *ExitBlock, bool &Changed,
54  BasicBlock *Preheader) {
55  // Make sure that all PHI entries coming from the loop are loop invariant.
56  // Because the code is in LCSSA form, any values used outside of the loop
57  // must pass through a PHI in the exit block, meaning that this check is
58  // sufficient to guarantee that no loop-variant values are used outside
59  // of the loop.
60  BasicBlock::iterator BI = ExitBlock->begin();
61  bool AllEntriesInvariant = true;
62  bool AllOutgoingValuesSame = true;
63  while (PHINode *P = dyn_cast<PHINode>(BI)) {
64  Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
65 
66  // Make sure all exiting blocks produce the same incoming value for the exit
67  // block. If there are different incoming values for different exiting
68  // blocks, then it is impossible to statically determine which value should
69  // be used.
70  AllOutgoingValuesSame =
71  all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
72  return incoming == P->getIncomingValueForBlock(BB);
73  });
74 
75  if (!AllOutgoingValuesSame)
76  break;
77 
78  if (Instruction *I = dyn_cast<Instruction>(incoming))
79  if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
80  AllEntriesInvariant = false;
81  break;
82  }
83 
84  ++BI;
85  }
86 
87  if (Changed)
89 
90  if (!AllEntriesInvariant || !AllOutgoingValuesSame)
91  return false;
92 
93  // Make sure that no instructions in the block have potential side-effects.
94  // This includes instructions that could write to memory, and loads that are
95  // marked volatile.
96  for (auto &I : L->blocks())
97  if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
98  return false;
99  return true;
100 }
101 
102 /// This function returns true if there is no viable path from the
103 /// entry block to the header of \p L. Right now, it only does
104 /// a local search to save compile time.
105 static bool isLoopNeverExecuted(Loop *L) {
106  using namespace PatternMatch;
107 
108  auto *Preheader = L->getLoopPreheader();
109  // TODO: We can relax this constraint, since we just need a loop
110  // predecessor.
111  assert(Preheader && "Needs preheader!");
112 
113  if (Preheader == &Preheader->getParent()->getEntryBlock())
114  return false;
115  // All predecessors of the preheader should have a constant conditional
116  // branch, with the loop's preheader as not-taken.
117  for (auto *Pred: predecessors(Preheader)) {
118  BasicBlock *Taken, *NotTaken;
119  ConstantInt *Cond;
120  if (!match(Pred->getTerminator(),
121  m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
122  return false;
123  if (!Cond->getZExtValue())
124  std::swap(Taken, NotTaken);
125  if (Taken == Preheader)
126  return false;
127  }
128  assert(!pred_empty(Preheader) &&
129  "Preheader should have predecessors at this point!");
130  // All the predecessors have the loop preheader as not-taken target.
131  return true;
132 }
133 
134 /// Remove a loop if it is dead.
135 ///
136 /// A loop is considered dead if it does not impact the observable behavior of
137 /// the program other than finite running time. This never removes a loop that
138 /// might be infinite (unless it is never executed), as doing so could change
139 /// the halting/non-halting nature of a program.
140 ///
141 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
142 /// order to make various safety checks work.
143 ///
144 /// \returns true if any changes were made. This may mutate the loop even if it
145 /// is unable to delete it due to hoisting trivially loop invariant
146 /// instructions out of the loop.
148  LoopInfo &LI, LPMUpdater *Updater = nullptr) {
149  assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
150 
151  // We can only remove the loop if there is a preheader that we can branch from
152  // after removing it. Also, if LoopSimplify form is not available, stay out
153  // of trouble.
154  BasicBlock *Preheader = L->getLoopPreheader();
155  if (!Preheader || !L->hasDedicatedExits()) {
156  DEBUG(dbgs()
157  << "Deletion requires Loop with preheader and dedicated exits.\n");
158  return false;
159  }
160  // We can't remove loops that contain subloops. If the subloops were dead,
161  // they would already have been removed in earlier executions of this pass.
162  if (L->begin() != L->end()) {
163  DEBUG(dbgs() << "Loop contains subloops.\n");
164  return false;
165  }
166 
167 
168  BasicBlock *ExitBlock = L->getUniqueExitBlock();
169 
170  if (ExitBlock && isLoopNeverExecuted(L)) {
171  DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
172  // Set incoming value to undef for phi nodes in the exit block.
173  BasicBlock::iterator BI = ExitBlock->begin();
174  while (PHINode *P = dyn_cast<PHINode>(BI)) {
175  for (unsigned i = 0; i < P->getNumIncomingValues(); i++)
176  P->setIncomingValue(i, UndefValue::get(P->getType()));
177  BI++;
178  }
179  deleteDeadLoop(L, DT, SE, LI, Updater);
180  ++NumDeleted;
181  return true;
182  }
183 
184  // The remaining checks below are for a loop being dead because all statements
185  // in the loop are invariant.
186  SmallVector<BasicBlock *, 4> ExitingBlocks;
187  L->getExitingBlocks(ExitingBlocks);
188 
189  // We require that the loop only have a single exit block. Otherwise, we'd
190  // be in the situation of needing to be able to solve statically which exit
191  // block will be branched to, or trying to preserve the branching logic in
192  // a loop invariant manner.
193  if (!ExitBlock) {
194  DEBUG(dbgs() << "Deletion requires single exit block\n");
195  return false;
196  }
197  // Finally, we have to check that the loop really is dead.
198  bool Changed = false;
199  if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) {
200  DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
201  return Changed;
202  }
203 
204  // Don't remove loops for which we can't solve the trip count.
205  // They could be infinite, in which case we'd be changing program behavior.
206  const SCEV *S = SE.getMaxBackedgeTakenCount(L);
207  if (isa<SCEVCouldNotCompute>(S)) {
208  DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n");
209  return Changed;
210  }
211 
212  DEBUG(dbgs() << "Loop is invariant, delete it!");
213  deleteDeadLoop(L, DT, SE, LI, Updater);
214  ++NumDeleted;
215 
216  return true;
217 }
218 
220  LoopInfo &LI, LPMUpdater *Updater) {
221  assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
222  auto *Preheader = L->getLoopPreheader();
223  assert(Preheader && "Preheader should exist!");
224 
225  // Now that we know the removal is safe, remove the loop by changing the
226  // branch from the preheader to go to the single exit block.
227  //
228  // Because we're deleting a large chunk of code at once, the sequence in which
229  // we remove things is very important to avoid invalidation issues.
230 
231  // If we have an LPM updater, tell it about the loop being removed.
232  if (Updater)
233  Updater->markLoopAsDeleted(*L);
234 
235  // Tell ScalarEvolution that the loop is deleted. Do this before
236  // deleting the loop so that ScalarEvolution can look at the loop
237  // to determine what it needs to clean up.
238  SE.forgetLoop(L);
239 
240  auto *ExitBlock = L->getUniqueExitBlock();
241  assert(ExitBlock && "Should have a unique exit block!");
242 
243  assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
244 
245  // Connect the preheader directly to the exit block.
246  // Even when the loop is never executed, we cannot remove the edge from the
247  // source block to the exit block. Consider the case where the unexecuted loop
248  // branches back to an outer loop. If we deleted the loop and removed the edge
249  // coming to this inner loop, this will break the outer loop structure (by
250  // deleting the backedge of the outer loop). If the outer loop is indeed a
251  // non-loop, it will be deleted in a future iteration of loop deletion pass.
252  Preheader->getTerminator()->replaceUsesOfWith(L->getHeader(), ExitBlock);
253 
254  // Rewrite phis in the exit block to get their inputs from the Preheader
255  // instead of the exiting block.
256  BasicBlock::iterator BI = ExitBlock->begin();
257  while (PHINode *P = dyn_cast<PHINode>(BI)) {
258  // Set the zero'th element of Phi to be from the preheader and remove all
259  // other incoming values. Given the loop has dedicated exits, all other
260  // incoming values must be from the exiting blocks.
261  int PredIndex = 0;
262  P->setIncomingBlock(PredIndex, Preheader);
263  // Removes all incoming values from all other exiting blocks (including
264  // duplicate values from an exiting block).
265  // Nuke all entries except the zero'th entry which is the preheader entry.
266  // NOTE! We need to remove Incoming Values in the reverse order as done
267  // below, to keep the indices valid for deletion (removeIncomingValues
268  // updates getNumIncomingValues and shifts all values down into the operand
269  // being deleted).
270  for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i)
271  P->removeIncomingValue(e-i, false);
272 
273  assert((P->getNumIncomingValues() == 1 &&
274  P->getIncomingBlock(PredIndex) == Preheader) &&
275  "Should have exactly one value and that's from the preheader!");
276  ++BI;
277  }
278 
279  // Update the dominator tree and remove the instructions and blocks that will
280  // be deleted from the reference counting scheme.
281  SmallVector<DomTreeNode*, 8> ChildNodes;
282  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
283  LI != LE; ++LI) {
284  // Move all of the block's children to be children of the Preheader, which
285  // allows us to remove the domtree entry for the block.
286  ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
287  for (DomTreeNode *ChildNode : ChildNodes) {
288  DT.changeImmediateDominator(ChildNode, DT[Preheader]);
289  }
290 
291  ChildNodes.clear();
292  DT.eraseNode(*LI);
293 
294  // Remove the block from the reference counting scheme, so that we can
295  // delete it freely later.
296  (*LI)->dropAllReferences();
297  }
298 
299  // Erase the instructions and the blocks without having to worry
300  // about ordering because we already dropped the references.
301  // NOTE: This iteration is safe because erasing the block does not remove its
302  // entry from the loop's block list. We do that in the next section.
303  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
304  LI != LE; ++LI)
305  (*LI)->eraseFromParent();
306 
307  // Finally, the blocks from loopinfo. This has to happen late because
308  // otherwise our loop iterators won't work.
309 
311  blocks.insert(L->block_begin(), L->block_end());
312  for (BasicBlock *BB : blocks)
313  LI.removeBlock(BB);
314 
315  // The last step is to update LoopInfo now that we've eliminated this loop.
316  LI.markAsRemoved(L);
317 }
318 
321  LPMUpdater &Updater) {
322 
323  DEBUG(dbgs() << "Analyzing Loop for deletion: ");
324  DEBUG(L.dump());
325  if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater))
326  return PreservedAnalyses::all();
327 
329 }
330 
331 namespace {
332 class LoopDeletionLegacyPass : public LoopPass {
333 public:
334  static char ID; // Pass ID, replacement for typeid
335  LoopDeletionLegacyPass() : LoopPass(ID) {
337  }
338 
339  // Possibly eliminate loop L if it is dead.
340  bool runOnLoop(Loop *L, LPPassManager &) override;
341 
342  void getAnalysisUsage(AnalysisUsage &AU) const override {
344  }
345 };
346 }
347 
349 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
350  "Delete dead loops", false, false)
352 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
353  "Delete dead loops", false, false)
354 
355 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
356 
357 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) {
358  if (skipLoop(L))
359  return false;
360  DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
361  ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
362  LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
363 
364  DEBUG(dbgs() << "Analyzing Loop for deletion: ");
365  DEBUG(L->dump());
366  return deleteLoopIfDead(L, DT, SE, LI);
367 }
MachineLoop * L
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:81
BasicBlock * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
Definition: LoopInfo.cpp:402
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.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Definition: LoopInfo.h:647
STATISTIC(NumFunctions,"Total number of functions")
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass,"loop-deletion","Delete dead loops", false, false) INITIALIZE_PASS_END(LoopDeletionLegacyPass
This is the interface for a simple mod/ref and alias analysis over globals.
void initializeLoopDeletionLegacyPassPass(PassRegistry &)
The main scalar evolution driver.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:500
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:818
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
BlockT * getHeader() const
Definition: LoopInfo.h:103
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:36
loop Delete dead loops
static bool isLoopDead(Loop *L, ScalarEvolution &SE, SmallVectorImpl< BasicBlock * > &ExitingBlocks, BasicBlock *ExitBlock, bool &Changed, BasicBlock *Preheader)
Determines if a loop is dead.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater=nullptr)
Remove a loop if it is dead.
Base class for the actual dominator tree node.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:83
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:144
#define P(N)
static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater=nullptr)
This function deletes dead loops.
iterator begin() const
Definition: LoopInfo.h:133
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
void dump() const
Definition: LoopInfo.cpp:411
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:101
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
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
iterator end() const
Definition: LoopInfo.h:134
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
Represent the analysis usage information of a pass.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:825
const SCEV * getMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void markAsRemoved(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:625
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:107
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfo.cpp:347
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1320
loop deletion
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static bool isLoopNeverExecuted(Loop *L)
This function returns true if there is no viable path from the entry block to the header of L...
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
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
Definition: LoopInfo.cpp:65
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
Definition: LoopInfo.cpp:174
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:110
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
Pass * createLoopDeletionPass()
std::vector< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:141
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:479
block_iterator block_end() const
Definition: LoopInfo.h:143
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
#define I(x, y, z)
Definition: MD5.cpp:58
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:1022
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
#define DEBUG(X)
Definition: Debug.h:118
block_iterator block_begin() const
Definition: LoopInfo.h:142
A container for analyses that lazily runs them and caches their results.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void markLoopAsDeleted(Loop &L)
Loop passes should use this method to indicate they have deleted a loop from the nest.
loop Delete dead false