1 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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/IR/PatternMatch.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Transforms/Scalar/LoopPassManager.h"
26 #include "llvm/Transforms/Utils/LoopUtils.h"
29 #define DEBUG_TYPE "loop-delete"
31 STATISTIC(NumDeleted, "Number of loops deleted");
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
39 /// difference to program behaviour.
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
45 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
46 LoopInfo &LI, bool LoopIsNeverExecuted,
47 LPMUpdater *Updater = nullptr);
48 /// Determines if a loop is dead.
50 /// This assumes that we've already checked for unique exit and exiting blocks,
51 /// and that the code is in LCSSA form.
52 static bool isLoopDead(Loop *L, ScalarEvolution &SE,
53 SmallVectorImpl<BasicBlock *> &ExitingBlocks,
54 BasicBlock *ExitBlock, bool &Changed,
55 BasicBlock *Preheader) {
56 // Make sure that all PHI entries coming from the loop are loop invariant.
57 // Because the code is in LCSSA form, any values used outside of the loop
58 // must pass through a PHI in the exit block, meaning that this check is
59 // sufficient to guarantee that no loop-variant values are used outside
61 BasicBlock::iterator BI = ExitBlock->begin();
62 bool AllEntriesInvariant = true;
63 bool AllOutgoingValuesSame = true;
64 while (PHINode *P = dyn_cast<PHINode>(BI)) {
65 Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
67 // Make sure all exiting blocks produce the same incoming value for the exit
68 // block. If there are different incoming values for different exiting
69 // blocks, then it is impossible to statically determine which value should
71 AllOutgoingValuesSame =
72 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
73 return incoming == P->getIncomingValueForBlock(BB);
76 if (!AllOutgoingValuesSame)
79 if (Instruction *I = dyn_cast<Instruction>(incoming))
80 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
81 AllEntriesInvariant = false;
89 SE.forgetLoopDispositions(L);
91 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
94 // Make sure that no instructions in the block have potential side-effects.
95 // This includes instructions that could write to memory, and loads that are
97 for (auto &I : L->blocks())
98 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
103 /// This function returns true if there is no viable path from the
104 /// entry block to the header of \p L. Right now, it only does
105 /// a local search to save compile time.
106 static bool isLoopNeverExecuted(Loop *L) {
107 using namespace PatternMatch;
109 auto *Preheader = L->getLoopPreheader();
110 // TODO: We can relax this constraint, since we just need a loop
112 assert(Preheader && "Needs preheader!");
114 if (Preheader == &Preheader->getParent()->getEntryBlock())
116 // All predecessors of the preheader should have a constant conditional
117 // branch, with the loop's preheader as not-taken.
118 for (auto *Pred: predecessors(Preheader)) {
119 BasicBlock *Taken, *NotTaken;
121 if (!match(Pred->getTerminator(),
122 m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
124 if (!Cond->getZExtValue())
125 std::swap(Taken, NotTaken);
126 if (Taken == Preheader)
129 assert(!pred_empty(Preheader) &&
130 "Preheader should have predecessors at this point!");
131 // All the predecessors have the loop preheader as not-taken target.
135 /// Remove a loop if it is dead.
137 /// A loop is considered dead if it does not impact the observable behavior of
138 /// the program other than finite running time. This never removes a loop that
139 /// might be infinite (unless it is never executed), as doing so could change
140 /// the halting/non-halting nature of a program.
142 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
143 /// order to make various safety checks work.
145 /// \returns true if any changes were made. This may mutate the loop even if it
146 /// is unable to delete it due to hoisting trivially loop invariant
147 /// instructions out of the loop.
148 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
149 LoopInfo &LI, LPMUpdater *Updater = nullptr) {
150 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
152 // We can only remove the loop if there is a preheader that we can
153 // branch from after removing it.
154 BasicBlock *Preheader = L->getLoopPreheader();
158 // If LoopSimplify form is not available, stay out of trouble.
159 if (!L->hasDedicatedExits())
162 // We can't remove loops that contain subloops. If the subloops were dead,
163 // they would already have been removed in earlier executions of this pass.
164 if (L->begin() != L->end())
168 BasicBlock *ExitBlock = L->getUniqueExitBlock();
170 if (ExitBlock && isLoopNeverExecuted(L)) {
171 deleteDeadLoop(L, DT, SE, LI, true /* LoopIsNeverExecuted */, Updater);
176 // The remaining checks below are for a loop being dead because all statements
177 // in the loop are invariant.
178 SmallVector<BasicBlock *, 4> ExitingBlocks;
179 L->getExitingBlocks(ExitingBlocks);
181 // We require that the loop only have a single exit block. Otherwise, we'd
182 // be in the situation of needing to be able to solve statically which exit
183 // block will be branched to, or trying to preserve the branching logic in
184 // a loop invariant manner.
188 // Finally, we have to check that the loop really is dead.
189 bool Changed = false;
190 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader))
193 // Don't remove loops for which we can't solve the trip count.
194 // They could be infinite, in which case we'd be changing program behavior.
195 const SCEV *S = SE.getMaxBackedgeTakenCount(L);
196 if (isa<SCEVCouldNotCompute>(S))
199 deleteDeadLoop(L, DT, SE, LI, false /* LoopIsNeverExecuted */, Updater);
205 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
206 LoopInfo &LI, bool LoopIsNeverExecuted,
207 LPMUpdater *Updater) {
208 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
209 auto *Preheader = L->getLoopPreheader();
210 assert(Preheader && "Preheader should exist!");
212 // Now that we know the removal is safe, remove the loop by changing the
213 // branch from the preheader to go to the single exit block.
215 // Because we're deleting a large chunk of code at once, the sequence in which
216 // we remove things is very important to avoid invalidation issues.
218 // If we have an LPM updater, tell it about the loop being removed.
220 Updater->markLoopAsDeleted(*L);
222 // Tell ScalarEvolution that the loop is deleted. Do this before
223 // deleting the loop so that ScalarEvolution can look at the loop
224 // to determine what it needs to clean up.
227 auto *ExitBlock = L->getUniqueExitBlock();
228 assert(ExitBlock && "Should have a unique exit block!");
230 // Connect the preheader directly to the exit block.
231 // Even when the loop is never executed, we cannot remove the edge from the
232 // source block to the exit block. Consider the case where the unexecuted loop
233 // branches back to an outer loop. If we deleted the loop and removed the edge
234 // coming to this inner loop, this will break the outer loop structure (by
235 // deleting the backedge of the outer loop). If the outer loop is indeed a
236 // non-loop, it will be deleted in a future iteration of loop deletion pass.
237 Preheader->getTerminator()->replaceUsesOfWith(L->getHeader(), ExitBlock);
239 SmallVector<BasicBlock *, 4> ExitingBlocks;
240 L->getExitingBlocks(ExitingBlocks);
241 // Rewrite phis in the exit block to get their inputs from the Preheader
242 // instead of the exiting block.
243 BasicBlock *ExitingBlock = ExitingBlocks[0];
244 BasicBlock::iterator BI = ExitBlock->begin();
245 while (PHINode *P = dyn_cast<PHINode>(BI)) {
246 int j = P->getBasicBlockIndex(ExitingBlock);
247 assert(j >= 0 && "Can't find exiting block in exit block's phi node!");
248 if (LoopIsNeverExecuted)
249 P->setIncomingValue(j, UndefValue::get(P->getType()));
250 P->setIncomingBlock(j, Preheader);
251 for (unsigned i = 1; i < ExitingBlocks.size(); ++i)
252 P->removeIncomingValue(ExitingBlocks[i]);
256 // Update the dominator tree and remove the instructions and blocks that will
257 // be deleted from the reference counting scheme.
258 SmallVector<DomTreeNode*, 8> ChildNodes;
259 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
261 // Move all of the block's children to be children of the Preheader, which
262 // allows us to remove the domtree entry for the block.
263 ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end());
264 for (DomTreeNode *ChildNode : ChildNodes) {
265 DT.changeImmediateDominator(ChildNode, DT[Preheader]);
271 // Remove the block from the reference counting scheme, so that we can
272 // delete it freely later.
273 (*LI)->dropAllReferences();
276 // Erase the instructions and the blocks without having to worry
277 // about ordering because we already dropped the references.
278 // NOTE: This iteration is safe because erasing the block does not remove its
279 // entry from the loop's block list. We do that in the next section.
280 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
282 (*LI)->eraseFromParent();
284 // Finally, the blocks from loopinfo. This has to happen late because
285 // otherwise our loop iterators won't work.
287 SmallPtrSet<BasicBlock *, 8> blocks;
288 blocks.insert(L->block_begin(), L->block_end());
289 for (BasicBlock *BB : blocks)
292 // The last step is to update LoopInfo now that we've eliminated this loop.
296 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
297 LoopStandardAnalysisResults &AR,
298 LPMUpdater &Updater) {
299 if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater))
300 return PreservedAnalyses::all();
302 return getLoopPassPreservedAnalyses();
306 class LoopDeletionLegacyPass : public LoopPass {
308 static char ID; // Pass ID, replacement for typeid
309 LoopDeletionLegacyPass() : LoopPass(ID) {
310 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
313 // Possibly eliminate loop L if it is dead.
314 bool runOnLoop(Loop *L, LPPassManager &) override;
316 void getAnalysisUsage(AnalysisUsage &AU) const override {
317 getLoopAnalysisUsage(AU);
322 char LoopDeletionLegacyPass::ID = 0;
323 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
324 "Delete dead loops", false, false)
325 INITIALIZE_PASS_DEPENDENCY(LoopPass)
326 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
327 "Delete dead loops", false, false)
329 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
331 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) {
334 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
335 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
336 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
338 return deleteLoopIfDead(L, DT, SE, LI);