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 difference
39 /// 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, LPMUpdater *Updater = nullptr);
47 /// Determines if a loop is dead.
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
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]);
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
70 AllOutgoingValuesSame =
71 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
72 return incoming == P->getIncomingValueForBlock(BB);
75 if (!AllOutgoingValuesSame)
78 if (Instruction *I = dyn_cast<Instruction>(incoming))
79 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
80 AllEntriesInvariant = false;
88 SE.forgetLoopDispositions(L);
90 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
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
96 for (auto &I : L->blocks())
97 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
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;
108 auto *Preheader = L->getLoopPreheader();
109 // TODO: We can relax this constraint, since we just need a loop
111 assert(Preheader && "Needs preheader!");
113 if (Preheader == &Preheader->getParent()->getEntryBlock())
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;
120 if (!match(Pred->getTerminator(),
121 m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
123 if (!Cond->getZExtValue())
124 std::swap(Taken, NotTaken);
125 if (Taken == Preheader)
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.
134 /// Remove a loop if it is dead.
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.
141 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
142 /// order to make various safety checks work.
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.
147 static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
148 LoopInfo &LI, LPMUpdater *Updater = nullptr) {
149 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
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
154 BasicBlock *Preheader = L->getLoopPreheader();
155 if (!Preheader || !L->hasDedicatedExits()) {
157 << "Deletion requires Loop with preheader and dedicated exits.\n");
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");
168 BasicBlock *ExitBlock = L->getUniqueExitBlock();
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()));
179 deleteDeadLoop(L, DT, SE, LI, Updater);
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);
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.
194 DEBUG(dbgs() << "Deletion requires single exit block\n");
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");
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");
212 DEBUG(dbgs() << "Loop is invariant, delete it!");
213 deleteDeadLoop(L, DT, SE, LI, Updater);
219 static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
220 LoopInfo &LI, LPMUpdater *Updater) {
221 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
222 auto *Preheader = L->getLoopPreheader();
223 assert(Preheader && "Preheader should exist!");
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.
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.
231 // If we have an LPM updater, tell it about the loop being removed.
233 Updater->markLoopAsDeleted(*L);
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.
240 auto *ExitBlock = L->getUniqueExitBlock();
241 assert(ExitBlock && "Should have a unique exit block!");
243 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
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);
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.
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
270 for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i)
271 P->removeIncomingValue(e-i, false);
273 assert((P->getNumIncomingValues() == 1 &&
274 P->getIncomingBlock(PredIndex) == Preheader) &&
275 "Should have exactly one value and that's from the preheader!");
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();
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]);
294 // Remove the block from the reference counting scheme, so that we can
295 // delete it freely later.
296 (*LI)->dropAllReferences();
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();
305 (*LI)->eraseFromParent();
307 // Finally, the blocks from loopinfo. This has to happen late because
308 // otherwise our loop iterators won't work.
310 SmallPtrSet<BasicBlock *, 8> blocks;
311 blocks.insert(L->block_begin(), L->block_end());
312 for (BasicBlock *BB : blocks)
315 // The last step is to update LoopInfo now that we've eliminated this loop.
319 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
320 LoopStandardAnalysisResults &AR,
321 LPMUpdater &Updater) {
323 DEBUG(dbgs() << "Analyzing Loop for deletion: ");
325 if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater))
326 return PreservedAnalyses::all();
328 return getLoopPassPreservedAnalyses();
332 class LoopDeletionLegacyPass : public LoopPass {
334 static char ID; // Pass ID, replacement for typeid
335 LoopDeletionLegacyPass() : LoopPass(ID) {
336 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
339 // Possibly eliminate loop L if it is dead.
340 bool runOnLoop(Loop *L, LPPassManager &) override;
342 void getAnalysisUsage(AnalysisUsage &AU) const override {
343 getLoopAnalysisUsage(AU);
348 char LoopDeletionLegacyPass::ID = 0;
349 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
350 "Delete dead loops", false, false)
351 INITIALIZE_PASS_DEPENDENCY(LoopPass)
352 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
353 "Delete dead loops", false, false)
355 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
357 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) {
360 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
361 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
362 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
364 DEBUG(dbgs() << "Analyzing Loop for deletion: ");
366 return deleteLoopIfDead(L, DT, SE, LI);