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 
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/Transforms/Utils/LoopUtils.h"
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "loop-delete"
28 
29 STATISTIC(NumDeleted, "Number of loops deleted");
30 
31 namespace {
32   class LoopDeletion : public LoopPass {
33   public:
34     static char ID; // Pass ID, replacement for typeid
35     LoopDeletion() : LoopPass(ID) {
36       initializeLoopDeletionPass(*PassRegistry::getPassRegistry());
37     }
38 
39     // Possibly eliminate loop L if it is dead.
40     bool runOnLoop(Loop *L, LPPassManager &) override;
41 
42     void getAnalysisUsage(AnalysisUsage &AU) const override {
43       getLoopAnalysisUsage(AU);
44     }
45 
46   private:
47     bool isLoopDead(Loop *L, ScalarEvolution &SE,
48                     SmallVectorImpl<BasicBlock *> &exitingBlocks,
49                     SmallVectorImpl<BasicBlock *> &exitBlocks, bool &Changed,
50                     BasicBlock *Preheader);
51   };
52 }
53 
54 char LoopDeletion::ID = 0;
55 INITIALIZE_PASS_BEGIN(LoopDeletion, "loop-deletion",
56                 "Delete dead loops", false, false)
57 INITIALIZE_PASS_DEPENDENCY(LoopPass)
58 INITIALIZE_PASS_END(LoopDeletion, "loop-deletion",
59                 "Delete dead loops", false, false)
60 
61 Pass *llvm::createLoopDeletionPass() {
62   return new LoopDeletion();
63 }
64 
65 /// isLoopDead - Determined if a loop is dead.  This assumes that we've already
66 /// checked for unique exit and exiting blocks, and that the code is in LCSSA
67 /// form.
68 bool LoopDeletion::isLoopDead(Loop *L, ScalarEvolution &SE,
69                               SmallVectorImpl<BasicBlock *> &exitingBlocks,
70                               SmallVectorImpl<BasicBlock *> &exitBlocks,
71                               bool &Changed, BasicBlock *Preheader) {
72   BasicBlock *exitBlock = exitBlocks[0];
73 
74   // Make sure that all PHI entries coming from the loop are loop invariant.
75   // Because the code is in LCSSA form, any values used outside of the loop
76   // must pass through a PHI in the exit block, meaning that this check is
77   // sufficient to guarantee that no loop-variant values are used outside
78   // of the loop.
79   BasicBlock::iterator BI = exitBlock->begin();
80   bool AllEntriesInvariant = true;
81   bool AllOutgoingValuesSame = true;
82   while (PHINode *P = dyn_cast<PHINode>(BI)) {
83     Value *incoming = P->getIncomingValueForBlock(exitingBlocks[0]);
84 
85     // Make sure all exiting blocks produce the same incoming value for the exit
86     // block.  If there are different incoming values for different exiting
87     // blocks, then it is impossible to statically determine which value should
88     // be used.
89     AllOutgoingValuesSame =
90         all_of(makeArrayRef(exitingBlocks).slice(1), [&](BasicBlock *BB) {
91           return incoming == P->getIncomingValueForBlock(BB);
92         });
93 
94     if (!AllOutgoingValuesSame)
95       break;
96 
97     if (Instruction *I = dyn_cast<Instruction>(incoming))
98       if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
99         AllEntriesInvariant = false;
100         break;
101       }
102 
103     ++BI;
104   }
105 
106   if (Changed)
107     SE.forgetLoopDispositions(L);
108 
109   if (!AllEntriesInvariant || !AllOutgoingValuesSame)
110     return false;
111 
112   // Make sure that no instructions in the block have potential side-effects.
113   // This includes instructions that could write to memory, and loads that are
114   // marked volatile.  This could be made more aggressive by using aliasing
115   // information to identify readonly and readnone calls.
116   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
117        LI != LE; ++LI) {
118     for (Instruction &I : **LI) {
119       if (I.mayHaveSideEffects())
120         return false;
121     }
122   }
123 
124   return true;
125 }
126 
127 /// runOnLoop - Remove dead loops, by which we mean loops that do not impact the
128 /// observable behavior of the program other than finite running time.  Note
129 /// we do ensure that this never remove a loop that might be infinite, as doing
130 /// so could change the halting/non-halting nature of a program.
131 /// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA
132 /// in order to make various safety checks work.
133 bool LoopDeletion::runOnLoop(Loop *L, LPPassManager &) {
134   if (skipLoop(L))
135     return false;
136 
137   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
138   assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
139 
140   // We can only remove the loop if there is a preheader that we can
141   // branch from after removing it.
142   BasicBlock *preheader = L->getLoopPreheader();
143   if (!preheader)
144     return false;
145 
146   // If LoopSimplify form is not available, stay out of trouble.
147   if (!L->hasDedicatedExits())
148     return false;
149 
150   // We can't remove loops that contain subloops.  If the subloops were dead,
151   // they would already have been removed in earlier executions of this pass.
152   if (L->begin() != L->end())
153     return false;
154 
155   SmallVector<BasicBlock*, 4> exitingBlocks;
156   L->getExitingBlocks(exitingBlocks);
157 
158   SmallVector<BasicBlock*, 4> exitBlocks;
159   L->getUniqueExitBlocks(exitBlocks);
160 
161   // We require that the loop only have a single exit block.  Otherwise, we'd
162   // be in the situation of needing to be able to solve statically which exit
163   // block will be branched to, or trying to preserve the branching logic in
164   // a loop invariant manner.
165   if (exitBlocks.size() != 1)
166     return false;
167 
168   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
169 
170   // Finally, we have to check that the loop really is dead.
171   bool Changed = false;
172   if (!isLoopDead(L, SE, exitingBlocks, exitBlocks, Changed, preheader))
173     return Changed;
174 
175   // Don't remove loops for which we can't solve the trip count.
176   // They could be infinite, in which case we'd be changing program behavior.
177   const SCEV *S = SE.getMaxBackedgeTakenCount(L);
178   if (isa<SCEVCouldNotCompute>(S))
179     return Changed;
180 
181   // Now that we know the removal is safe, remove the loop by changing the
182   // branch from the preheader to go to the single exit block.
183   BasicBlock *exitBlock = exitBlocks[0];
184 
185   // Because we're deleting a large chunk of code at once, the sequence in which
186   // we remove things is very important to avoid invalidation issues.  Don't
187   // mess with this unless you have good reason and know what you're doing.
188 
189   // Tell ScalarEvolution that the loop is deleted. Do this before
190   // deleting the loop so that ScalarEvolution can look at the loop
191   // to determine what it needs to clean up.
192   SE.forgetLoop(L);
193 
194   // Connect the preheader directly to the exit block.
195   TerminatorInst *TI = preheader->getTerminator();
196   TI->replaceUsesOfWith(L->getHeader(), exitBlock);
197 
198   // Rewrite phis in the exit block to get their inputs from
199   // the preheader instead of the exiting block.
200   BasicBlock *exitingBlock = exitingBlocks[0];
201   BasicBlock::iterator BI = exitBlock->begin();
202   while (PHINode *P = dyn_cast<PHINode>(BI)) {
203     int j = P->getBasicBlockIndex(exitingBlock);
204     assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
205     P->setIncomingBlock(j, preheader);
206     for (unsigned i = 1; i < exitingBlocks.size(); ++i)
207       P->removeIncomingValue(exitingBlocks[i]);
208     ++BI;
209   }
210 
211   // Update the dominator tree and remove the instructions and blocks that will
212   // be deleted from the reference counting scheme.
213   SmallVector<DomTreeNode*, 8> ChildNodes;
214   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
215        LI != LE; ++LI) {
216     // Move all of the block's children to be children of the preheader, which
217     // allows us to remove the domtree entry for the block.
218     ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
219     for (DomTreeNode *ChildNode : ChildNodes) {
220       DT.changeImmediateDominator(ChildNode, DT[preheader]);
221     }
222 
223     ChildNodes.clear();
224     DT.eraseNode(*LI);
225 
226     // Remove the block from the reference counting scheme, so that we can
227     // delete it freely later.
228     (*LI)->dropAllReferences();
229   }
230 
231   // Erase the instructions and the blocks without having to worry
232   // about ordering because we already dropped the references.
233   // NOTE: This iteration is safe because erasing the block does not remove its
234   // entry from the loop's block list.  We do that in the next section.
235   for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
236        LI != LE; ++LI)
237     (*LI)->eraseFromParent();
238 
239   // Finally, the blocks from loopinfo.  This has to happen late because
240   // otherwise our loop iterators won't work.
241   LoopInfo &loopInfo = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
242   SmallPtrSet<BasicBlock*, 8> blocks;
243   blocks.insert(L->block_begin(), L->block_end());
244   for (BasicBlock *BB : blocks)
245     loopInfo.removeBlock(BB);
246 
247   // The last step is to update LoopInfo now that we've eliminated this loop.
248   loopInfo.markAsRemoved(L);
249   Changed = true;
250 
251   ++NumDeleted;
252 
253   return Changed;
254 }
255