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