LoopDeletion.cpp revision 210299
1193323Sed//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements the Dead Loop Deletion Pass. This pass is responsible
11193323Sed// for eliminating loops with non-infinite computable trip counts that have no
12193323Sed// side effects or volatile instructions, and do not contribute to the
13193323Sed// computation of the function's return value.
14193323Sed//
15193323Sed//===----------------------------------------------------------------------===//
16193323Sed
17193323Sed#define DEBUG_TYPE "loop-delete"
18193323Sed#include "llvm/Transforms/Scalar.h"
19193323Sed#include "llvm/Analysis/LoopPass.h"
20193323Sed#include "llvm/Analysis/ScalarEvolution.h"
21193323Sed#include "llvm/ADT/Statistic.h"
22193323Sed#include "llvm/ADT/SmallVector.h"
23193323Sedusing namespace llvm;
24193323Sed
25193323SedSTATISTIC(NumDeleted, "Number of loops deleted");
26193323Sed
27193323Sednamespace {
28198090Srdivacky  class LoopDeletion : public LoopPass {
29193323Sed  public:
30193323Sed    static char ID; // Pass ID, replacement for typeid
31193323Sed    LoopDeletion() : LoopPass(&ID) {}
32193323Sed
33193323Sed    // Possibly eliminate loop L if it is dead.
34193323Sed    bool runOnLoop(Loop* L, LPPassManager& LPM);
35193323Sed
36193323Sed    bool IsLoopDead(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks,
37198090Srdivacky                    SmallVector<BasicBlock*, 4>& exitBlocks,
38198090Srdivacky                    bool &Changed, BasicBlock *Preheader);
39198090Srdivacky
40193323Sed    virtual void getAnalysisUsage(AnalysisUsage& AU) const {
41193323Sed      AU.addRequired<ScalarEvolution>();
42193323Sed      AU.addRequired<DominatorTree>();
43193323Sed      AU.addRequired<LoopInfo>();
44193323Sed      AU.addRequiredID(LoopSimplifyID);
45193323Sed      AU.addRequiredID(LCSSAID);
46193323Sed
47193323Sed      AU.addPreserved<ScalarEvolution>();
48193323Sed      AU.addPreserved<DominatorTree>();
49193323Sed      AU.addPreserved<LoopInfo>();
50193323Sed      AU.addPreservedID(LoopSimplifyID);
51193323Sed      AU.addPreservedID(LCSSAID);
52193323Sed      AU.addPreserved<DominanceFrontier>();
53193323Sed    }
54193323Sed  };
55193323Sed}
56193323Sed
57193323Sedchar LoopDeletion::ID = 0;
58193323Sedstatic RegisterPass<LoopDeletion> X("loop-deletion", "Delete dead loops");
59193323Sed
60193323SedPass* llvm::createLoopDeletionPass() {
61193323Sed  return new LoopDeletion();
62193323Sed}
63193323Sed
64193323Sed/// IsLoopDead - Determined if a loop is dead.  This assumes that we've already
65193323Sed/// checked for unique exit and exiting blocks, and that the code is in LCSSA
66193323Sed/// form.
67193323Sedbool LoopDeletion::IsLoopDead(Loop* L,
68193323Sed                              SmallVector<BasicBlock*, 4>& exitingBlocks,
69198090Srdivacky                              SmallVector<BasicBlock*, 4>& exitBlocks,
70198090Srdivacky                              bool &Changed, BasicBlock *Preheader) {
71193323Sed  BasicBlock* exitingBlock = exitingBlocks[0];
72193323Sed  BasicBlock* exitBlock = exitBlocks[0];
73193323Sed
74193323Sed  // Make sure that all PHI entries coming from the loop are loop invariant.
75193323Sed  // Because the code is in LCSSA form, any values used outside of the loop
76193323Sed  // must pass through a PHI in the exit block, meaning that this check is
77193323Sed  // sufficient to guarantee that no loop-variant values are used outside
78193323Sed  // of the loop.
79193323Sed  BasicBlock::iterator BI = exitBlock->begin();
80193323Sed  while (PHINode* P = dyn_cast<PHINode>(BI)) {
81193323Sed    Value* incoming = P->getIncomingValueForBlock(exitingBlock);
82193323Sed    if (Instruction* I = dyn_cast<Instruction>(incoming))
83198090Srdivacky      if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator()))
84193323Sed        return false;
85193323Sed
86210299Sed    ++BI;
87193323Sed  }
88193323Sed
89193323Sed  // Make sure that no instructions in the block have potential side-effects.
90193323Sed  // This includes instructions that could write to memory, and loads that are
91193323Sed  // marked volatile.  This could be made more aggressive by using aliasing
92193323Sed  // information to identify readonly and readnone calls.
93193323Sed  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
94193323Sed       LI != LE; ++LI) {
95193323Sed    for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end();
96193323Sed         BI != BE; ++BI) {
97193323Sed      if (BI->mayHaveSideEffects())
98193323Sed        return false;
99193323Sed    }
100193323Sed  }
101193323Sed
102193323Sed  return true;
103193323Sed}
104193323Sed
105193323Sed/// runOnLoop - Remove dead loops, by which we mean loops that do not impact the
106193323Sed/// observable behavior of the program other than finite running time.  Note
107193323Sed/// we do ensure that this never remove a loop that might be infinite, as doing
108193323Sed/// so could change the halting/non-halting nature of a program.
109193323Sed/// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA
110193323Sed/// in order to make various safety checks work.
111193323Sedbool LoopDeletion::runOnLoop(Loop* L, LPPassManager& LPM) {
112193323Sed  // We can only remove the loop if there is a preheader that we can
113193323Sed  // branch from after removing it.
114193323Sed  BasicBlock* preheader = L->getLoopPreheader();
115193323Sed  if (!preheader)
116193323Sed    return false;
117193323Sed
118199481Srdivacky  // If LoopSimplify form is not available, stay out of trouble.
119199481Srdivacky  if (!L->hasDedicatedExits())
120199481Srdivacky    return false;
121199481Srdivacky
122193323Sed  // We can't remove loops that contain subloops.  If the subloops were dead,
123193323Sed  // they would already have been removed in earlier executions of this pass.
124193323Sed  if (L->begin() != L->end())
125193323Sed    return false;
126193323Sed
127193323Sed  SmallVector<BasicBlock*, 4> exitingBlocks;
128193323Sed  L->getExitingBlocks(exitingBlocks);
129193323Sed
130193323Sed  SmallVector<BasicBlock*, 4> exitBlocks;
131193323Sed  L->getUniqueExitBlocks(exitBlocks);
132193323Sed
133193323Sed  // We require that the loop only have a single exit block.  Otherwise, we'd
134193323Sed  // be in the situation of needing to be able to solve statically which exit
135193323Sed  // block will be branched to, or trying to preserve the branching logic in
136193323Sed  // a loop invariant manner.
137193323Sed  if (exitBlocks.size() != 1)
138193323Sed    return false;
139193323Sed
140198892Srdivacky  // Loops with multiple exits are too complicated to handle correctly.
141198892Srdivacky  if (exitingBlocks.size() != 1)
142193323Sed    return false;
143193323Sed
144193323Sed  // Finally, we have to check that the loop really is dead.
145198090Srdivacky  bool Changed = false;
146198090Srdivacky  if (!IsLoopDead(L, exitingBlocks, exitBlocks, Changed, preheader))
147198090Srdivacky    return Changed;
148193323Sed
149193323Sed  // Don't remove loops for which we can't solve the trip count.
150193323Sed  // They could be infinite, in which case we'd be changing program behavior.
151193323Sed  ScalarEvolution& SE = getAnalysis<ScalarEvolution>();
152198892Srdivacky  const SCEV *S = SE.getMaxBackedgeTakenCount(L);
153193323Sed  if (isa<SCEVCouldNotCompute>(S))
154198090Srdivacky    return Changed;
155193323Sed
156193323Sed  // Now that we know the removal is safe, remove the loop by changing the
157193323Sed  // branch from the preheader to go to the single exit block.
158193323Sed  BasicBlock* exitBlock = exitBlocks[0];
159193323Sed  BasicBlock* exitingBlock = exitingBlocks[0];
160193323Sed
161193323Sed  // Because we're deleting a large chunk of code at once, the sequence in which
162193323Sed  // we remove things is very important to avoid invalidation issues.  Don't
163193323Sed  // mess with this unless you have good reason and know what you're doing.
164198090Srdivacky
165198090Srdivacky  // Tell ScalarEvolution that the loop is deleted. Do this before
166198090Srdivacky  // deleting the loop so that ScalarEvolution can look at the loop
167198090Srdivacky  // to determine what it needs to clean up.
168198892Srdivacky  SE.forgetLoop(L);
169198090Srdivacky
170193323Sed  // Connect the preheader directly to the exit block.
171193323Sed  TerminatorInst* TI = preheader->getTerminator();
172193323Sed  TI->replaceUsesOfWith(L->getHeader(), exitBlock);
173193323Sed
174193323Sed  // Rewrite phis in the exit block to get their inputs from
175193323Sed  // the preheader instead of the exiting block.
176193323Sed  BasicBlock::iterator BI = exitBlock->begin();
177193323Sed  while (PHINode* P = dyn_cast<PHINode>(BI)) {
178193323Sed    P->replaceUsesOfWith(exitingBlock, preheader);
179210299Sed    ++BI;
180193323Sed  }
181193323Sed
182193323Sed  // Update the dominator tree and remove the instructions and blocks that will
183193323Sed  // be deleted from the reference counting scheme.
184193323Sed  DominatorTree& DT = getAnalysis<DominatorTree>();
185193323Sed  DominanceFrontier* DF = getAnalysisIfAvailable<DominanceFrontier>();
186193323Sed  SmallPtrSet<DomTreeNode*, 8> ChildNodes;
187193323Sed  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
188193323Sed       LI != LE; ++LI) {
189193323Sed    // Move all of the block's children to be children of the preheader, which
190193323Sed    // allows us to remove the domtree entry for the block.
191193323Sed    ChildNodes.insert(DT[*LI]->begin(), DT[*LI]->end());
192193323Sed    for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = ChildNodes.begin(),
193193323Sed         DE = ChildNodes.end(); DI != DE; ++DI) {
194193323Sed      DT.changeImmediateDominator(*DI, DT[preheader]);
195193323Sed      if (DF) DF->changeImmediateDominator((*DI)->getBlock(), preheader, &DT);
196193323Sed    }
197193323Sed
198193323Sed    ChildNodes.clear();
199193323Sed    DT.eraseNode(*LI);
200193323Sed    if (DF) DF->removeBlock(*LI);
201193323Sed
202193323Sed    // Remove the block from the reference counting scheme, so that we can
203193323Sed    // delete it freely later.
204193323Sed    (*LI)->dropAllReferences();
205193323Sed  }
206193323Sed
207193323Sed  // Erase the instructions and the blocks without having to worry
208193323Sed  // about ordering because we already dropped the references.
209193323Sed  // NOTE: This iteration is safe because erasing the block does not remove its
210193323Sed  // entry from the loop's block list.  We do that in the next section.
211193323Sed  for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
212193323Sed       LI != LE; ++LI)
213193323Sed    (*LI)->eraseFromParent();
214193323Sed
215193323Sed  // Finally, the blocks from loopinfo.  This has to happen late because
216193323Sed  // otherwise our loop iterators won't work.
217193323Sed  LoopInfo& loopInfo = getAnalysis<LoopInfo>();
218193323Sed  SmallPtrSet<BasicBlock*, 8> blocks;
219193323Sed  blocks.insert(L->block_begin(), L->block_end());
220193323Sed  for (SmallPtrSet<BasicBlock*,8>::iterator I = blocks.begin(),
221193323Sed       E = blocks.end(); I != E; ++I)
222193323Sed    loopInfo.removeBlock(*I);
223193323Sed
224193323Sed  // The last step is to inform the loop pass manager that we've
225193323Sed  // eliminated this loop.
226193323Sed  LPM.deleteLoopFromQueue(L);
227198090Srdivacky  Changed = true;
228193323Sed
229210299Sed  ++NumDeleted;
230193323Sed
231198090Srdivacky  return Changed;
232193323Sed}
233