1 //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Dead Loop Deletion Pass. This pass is responsible
10 // for eliminating loops with non-infinite computable trip counts that have no
11 // side effects or volatile instructions, and do not contribute to the
12 // computation of the function's return value.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Scalar/LoopDeletion.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/MemorySSA.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/Scalar/LoopPassManager.h"
28 #include "llvm/Transforms/Utils/LoopUtils.h"
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "loop-delete"
33 
34 STATISTIC(NumDeleted, "Number of loops deleted");
35 
36 enum class LoopDeletionResult {
37   Unmodified,
38   Modified,
39   Deleted,
40 };
41 
42 static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B) {
43   if (A == LoopDeletionResult::Deleted || B == LoopDeletionResult::Deleted)
44     return LoopDeletionResult::Deleted;
45   if (A == LoopDeletionResult::Modified || B == LoopDeletionResult::Modified)
46     return LoopDeletionResult::Modified;
47   return LoopDeletionResult::Unmodified;
48 }
49 
50 /// Determines if a loop is dead.
51 ///
52 /// This assumes that we've already checked for unique exit and exiting blocks,
53 /// and that the code is in LCSSA form.
54 static bool isLoopDead(Loop *L, ScalarEvolution &SE,
55                        SmallVectorImpl<BasicBlock *> &ExitingBlocks,
56                        BasicBlock *ExitBlock, bool &Changed,
57                        BasicBlock *Preheader) {
58   // Make sure that all PHI entries coming from the loop are loop invariant.
59   // Because the code is in LCSSA form, any values used outside of the loop
60   // must pass through a PHI in the exit block, meaning that this check is
61   // sufficient to guarantee that no loop-variant values are used outside
62   // of the loop.
63   bool AllEntriesInvariant = true;
64   bool AllOutgoingValuesSame = true;
65   if (!L->hasNoExitBlocks()) {
66     for (PHINode &P : ExitBlock->phis()) {
67       Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]);
68 
69       // Make sure all exiting blocks produce the same incoming value for the
70       // block. If there are different incoming values for different exiting
71       // blocks, then it is impossible to statically determine which value
72       // should be used.
73       AllOutgoingValuesSame =
74           all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
75             return incoming == P.getIncomingValueForBlock(BB);
76           });
77 
78       if (!AllOutgoingValuesSame)
79         break;
80 
81       if (Instruction *I = dyn_cast<Instruction>(incoming))
82         if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
83           AllEntriesInvariant = false;
84           break;
85         }
86     }
87   }
88 
89   if (Changed)
90     SE.forgetLoopDispositions(L);
91 
92   if (!AllEntriesInvariant || !AllOutgoingValuesSame)
93     return false;
94 
95   // Make sure that no instructions in the block have potential side-effects.
96   // This includes instructions that could write to memory, and loads that are
97   // marked volatile.
98   for (auto &I : L->blocks())
99     if (any_of(*I, [](Instruction &I) {
100           return I.mayHaveSideEffects() && !I.isDroppable();
101         }))
102       return false;
103 
104   // The loop or any of its sub-loops looping infinitely is legal. The loop can
105   // only be considered dead if either
106   // a. the function is mustprogress.
107   // b. all (sub-)loops are mustprogress or have a known trip-count.
108   if (L->getHeader()->getParent()->mustProgress())
109     return true;
110 
111   SmallVector<Loop *, 8> WorkList;
112   WorkList.push_back(L);
113   while (!WorkList.empty()) {
114     Loop *Current = WorkList.pop_back_val();
115     if (hasMustProgress(Current))
116       continue;
117 
118     const SCEV *S = SE.getConstantMaxBackedgeTakenCount(Current);
119     if (isa<SCEVCouldNotCompute>(S)) {
120       LLVM_DEBUG(
121           dbgs() << "Could not compute SCEV MaxBackedgeTakenCount and was "
122                     "not required to make progress.\n");
123       return false;
124     }
125     WorkList.append(Current->begin(), Current->end());
126   }
127   return true;
128 }
129 
130 /// This function returns true if there is no viable path from the
131 /// entry block to the header of \p L. Right now, it only does
132 /// a local search to save compile time.
133 static bool isLoopNeverExecuted(Loop *L) {
134   using namespace PatternMatch;
135 
136   auto *Preheader = L->getLoopPreheader();
137   // TODO: We can relax this constraint, since we just need a loop
138   // predecessor.
139   assert(Preheader && "Needs preheader!");
140 
141   if (Preheader->isEntryBlock())
142     return false;
143   // All predecessors of the preheader should have a constant conditional
144   // branch, with the loop's preheader as not-taken.
145   for (auto *Pred: predecessors(Preheader)) {
146     BasicBlock *Taken, *NotTaken;
147     ConstantInt *Cond;
148     if (!match(Pred->getTerminator(),
149                m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
150       return false;
151     if (!Cond->getZExtValue())
152       std::swap(Taken, NotTaken);
153     if (Taken == Preheader)
154       return false;
155   }
156   assert(!pred_empty(Preheader) &&
157          "Preheader should have predecessors at this point!");
158   // All the predecessors have the loop preheader as not-taken target.
159   return true;
160 }
161 
162 /// If we can prove the backedge is untaken, remove it.  This destroys the
163 /// loop, but leaves the (now trivially loop invariant) control flow and
164 /// side effects (if any) in place.
165 static LoopDeletionResult
166 breakBackedgeIfNotTaken(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
167                         LoopInfo &LI, MemorySSA *MSSA,
168                         OptimizationRemarkEmitter &ORE) {
169   assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
170 
171   if (!L->getLoopLatch())
172     return LoopDeletionResult::Unmodified;
173 
174   auto *BTC = SE.getBackedgeTakenCount(L);
175   if (!BTC->isZero())
176     return LoopDeletionResult::Unmodified;
177 
178   breakLoopBackedge(L, DT, SE, LI, MSSA);
179   return LoopDeletionResult::Deleted;
180 }
181 
182 /// Remove a loop if it is dead.
183 ///
184 /// A loop is considered dead either if it does not impact the observable
185 /// behavior of the program other than finite running time, or if it is
186 /// required to make progress by an attribute such as 'mustprogress' or
187 /// 'llvm.loop.mustprogress' and does not make any. This may remove
188 /// infinite loops that have been required to make progress.
189 ///
190 /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
191 /// order to make various safety checks work.
192 ///
193 /// \returns true if any changes were made. This may mutate the loop even if it
194 /// is unable to delete it due to hoisting trivially loop invariant
195 /// instructions out of the loop.
196 static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT,
197                                            ScalarEvolution &SE, LoopInfo &LI,
198                                            MemorySSA *MSSA,
199                                            OptimizationRemarkEmitter &ORE) {
200   assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
201 
202   // We can only remove the loop if there is a preheader that we can branch from
203   // after removing it. Also, if LoopSimplify form is not available, stay out
204   // of trouble.
205   BasicBlock *Preheader = L->getLoopPreheader();
206   if (!Preheader || !L->hasDedicatedExits()) {
207     LLVM_DEBUG(
208         dbgs()
209         << "Deletion requires Loop with preheader and dedicated exits.\n");
210     return LoopDeletionResult::Unmodified;
211   }
212 
213   BasicBlock *ExitBlock = L->getUniqueExitBlock();
214 
215   if (ExitBlock && isLoopNeverExecuted(L)) {
216     LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
217     // We need to forget the loop before setting the incoming values of the exit
218     // phis to undef, so we properly invalidate the SCEV expressions for those
219     // phis.
220     SE.forgetLoop(L);
221     // Set incoming value to undef for phi nodes in the exit block.
222     for (PHINode &P : ExitBlock->phis()) {
223       std::fill(P.incoming_values().begin(), P.incoming_values().end(),
224                 UndefValue::get(P.getType()));
225     }
226     ORE.emit([&]() {
227       return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(),
228                                 L->getHeader())
229              << "Loop deleted because it never executes";
230     });
231     deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
232     ++NumDeleted;
233     return LoopDeletionResult::Deleted;
234   }
235 
236   // The remaining checks below are for a loop being dead because all statements
237   // in the loop are invariant.
238   SmallVector<BasicBlock *, 4> ExitingBlocks;
239   L->getExitingBlocks(ExitingBlocks);
240 
241   // We require that the loop has at most one exit block. Otherwise, we'd be in
242   // the situation of needing to be able to solve statically which exit block
243   // will be branched to, or trying to preserve the branching logic in a loop
244   // invariant manner.
245   if (!ExitBlock && !L->hasNoExitBlocks()) {
246     LLVM_DEBUG(dbgs() << "Deletion requires at most one exit block.\n");
247     return LoopDeletionResult::Unmodified;
248   }
249   // Finally, we have to check that the loop really is dead.
250   bool Changed = false;
251   if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) {
252     LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
253     return Changed ? LoopDeletionResult::Modified
254                    : LoopDeletionResult::Unmodified;
255   }
256 
257   LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!");
258   ORE.emit([&]() {
259     return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(),
260                               L->getHeader())
261            << "Loop deleted because it is invariant";
262   });
263   deleteDeadLoop(L, &DT, &SE, &LI, MSSA);
264   ++NumDeleted;
265 
266   return LoopDeletionResult::Deleted;
267 }
268 
269 PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
270                                         LoopStandardAnalysisResults &AR,
271                                         LPMUpdater &Updater) {
272 
273   LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
274   LLVM_DEBUG(L.dump());
275   std::string LoopName = std::string(L.getName());
276   // For the new PM, we can't use OptimizationRemarkEmitter as an analysis
277   // pass. Function analyses need to be preserved across loop transformations
278   // but ORE cannot be preserved (see comment before the pass definition).
279   OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
280   auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE);
281 
282   // If we can prove the backedge isn't taken, just break it and be done.  This
283   // leaves the loop structure in place which means it can handle dispatching
284   // to the right exit based on whatever loop invariant structure remains.
285   if (Result != LoopDeletionResult::Deleted)
286     Result = merge(Result, breakBackedgeIfNotTaken(&L, AR.DT, AR.SE, AR.LI,
287                                                    AR.MSSA, ORE));
288 
289   if (Result == LoopDeletionResult::Unmodified)
290     return PreservedAnalyses::all();
291 
292   if (Result == LoopDeletionResult::Deleted)
293     Updater.markLoopAsDeleted(L, LoopName);
294 
295   auto PA = getLoopPassPreservedAnalyses();
296   if (AR.MSSA)
297     PA.preserve<MemorySSAAnalysis>();
298   return PA;
299 }
300 
301 namespace {
302 class LoopDeletionLegacyPass : public LoopPass {
303 public:
304   static char ID; // Pass ID, replacement for typeid
305   LoopDeletionLegacyPass() : LoopPass(ID) {
306     initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
307   }
308 
309   // Possibly eliminate loop L if it is dead.
310   bool runOnLoop(Loop *L, LPPassManager &) override;
311 
312   void getAnalysisUsage(AnalysisUsage &AU) const override {
313     AU.addPreserved<MemorySSAWrapperPass>();
314     getLoopAnalysisUsage(AU);
315   }
316 };
317 }
318 
319 char LoopDeletionLegacyPass::ID = 0;
320 INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
321                       "Delete dead loops", false, false)
322 INITIALIZE_PASS_DEPENDENCY(LoopPass)
323 INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
324                     "Delete dead loops", false, false)
325 
326 Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
327 
328 bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
329   if (skipLoop(L))
330     return false;
331   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
332   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
333   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
334   auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
335   MemorySSA *MSSA = nullptr;
336   if (MSSAAnalysis)
337     MSSA = &MSSAAnalysis->getMSSA();
338   // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
339   // pass.  Function analyses need to be preserved across loop transformations
340   // but ORE cannot be preserved (see comment before the pass definition).
341   OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
342 
343   LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
344   LLVM_DEBUG(L->dump());
345 
346   LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI, MSSA, ORE);
347 
348   // If we can prove the backedge isn't taken, just break it and be done.  This
349   // leaves the loop structure in place which means it can handle dispatching
350   // to the right exit based on whatever loop invariant structure remains.
351   if (Result != LoopDeletionResult::Deleted)
352     Result = merge(Result, breakBackedgeIfNotTaken(L, DT, SE, LI, MSSA, ORE));
353 
354   if (Result == LoopDeletionResult::Deleted)
355     LPM.markLoopAsDeleted(*L);
356 
357   return Result != LoopDeletionResult::Unmodified;
358 }
359