blob: cee197cf8354023814b360c42f6412222e75dd5e [file] [log] [blame]
Owen Anderson2306a1e2008-04-29 20:06:54 +00001//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===//
Owen Anderson94ad7022008-04-29 00:38:34 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Owen Anderson94ad7022008-04-29 00:38:34 +00006//
7//===----------------------------------------------------------------------===//
8//
Gordon Henriksen829046b2008-05-08 17:46:35 +00009// 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.
Owen Anderson94ad7022008-04-29 00:38:34 +000013//
14//===----------------------------------------------------------------------===//
15
Jun Bum Limc837af32016-07-14 18:28:29 +000016#include "llvm/Transforms/Scalar/LoopDeletion.h"
Owen Anderson94ad7022008-04-29 00:38:34 +000017#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/Statistic.h"
James Molloyefbba722015-09-10 10:22:12 +000019#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/LoopPass.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000021#include "llvm/IR/Dominators.h"
Anna Thomas53c8d952017-05-03 11:47:11 +000022#include "llvm/IR/PatternMatch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +000023#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000024#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000025#include "llvm/Transforms/Utils/LoopUtils.h"
Owen Anderson94ad7022008-04-29 00:38:34 +000026using namespace llvm;
27
Chandler Carruth964daaa2014-04-22 02:55:47 +000028#define DEBUG_TYPE "loop-delete"
29
Owen Anderson94ad7022008-04-29 00:38:34 +000030STATISTIC(NumDeleted, "Number of loops deleted");
31
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +000032enum class LoopDeletionResult {
33 Unmodified,
34 Modified,
35 Deleted,
36};
37
Chandler Carruth26169f002017-01-17 22:07:26 +000038/// Determines if a loop is dead.
39///
40/// This assumes that we've already checked for unique exit and exiting blocks,
41/// and that the code is in LCSSA form.
42static bool isLoopDead(Loop *L, ScalarEvolution &SE,
43 SmallVectorImpl<BasicBlock *> &ExitingBlocks,
44 BasicBlock *ExitBlock, bool &Changed,
45 BasicBlock *Preheader) {
Owen Anderson94ad7022008-04-29 00:38:34 +000046 // Make sure that all PHI entries coming from the loop are loop invariant.
Owen Andersone6746002008-04-29 20:59:33 +000047 // Because the code is in LCSSA form, any values used outside of the loop
48 // must pass through a PHI in the exit block, meaning that this check is
49 // sufficient to guarantee that no loop-variant values are used outside
50 // of the loop.
Sanjoy Das905fc272016-05-03 17:50:02 +000051 bool AllEntriesInvariant = true;
52 bool AllOutgoingValuesSame = true;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000053 for (PHINode &P : ExitBlock->phis()) {
54 Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]);
Cameron Zwarich82630852011-02-22 22:25:39 +000055
56 // Make sure all exiting blocks produce the same incoming value for the exit
57 // block. If there are different incoming values for different exiting
58 // blocks, then it is impossible to statically determine which value should
59 // be used.
Sanjoy Das7e7a5a02016-05-03 17:50:06 +000060 AllOutgoingValuesSame =
Chandler Carruth04a73872017-01-17 21:51:39 +000061 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000062 return incoming == P.getIncomingValueForBlock(BB);
Sanjoy Das7e7a5a02016-05-03 17:50:06 +000063 });
Nadav Rotem465834c2012-07-24 10:51:42 +000064
Sanjoy Das905fc272016-05-03 17:50:02 +000065 if (!AllOutgoingValuesSame)
66 break;
67
Jakub Staszakbc421ef2013-03-18 23:31:30 +000068 if (Instruction *I = dyn_cast<Instruction>(incoming))
Sanjoy Das905fc272016-05-03 17:50:02 +000069 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
70 AllEntriesInvariant = false;
71 break;
72 }
Owen Anderson94ad7022008-04-29 00:38:34 +000073 }
Nadav Rotem465834c2012-07-24 10:51:42 +000074
Sanjoy Das905fc272016-05-03 17:50:02 +000075 if (Changed)
76 SE.forgetLoopDispositions(L);
77
78 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
79 return false;
80
Owen Anderson94ad7022008-04-29 00:38:34 +000081 // Make sure that no instructions in the block have potential side-effects.
Owen Andersone6746002008-04-29 20:59:33 +000082 // This includes instructions that could write to memory, and loads that are
Xin Tongdf4dff32017-02-23 23:47:10 +000083 // marked volatile.
Davide Italiano49a0aac2017-02-26 07:08:20 +000084 for (auto &I : L->blocks())
85 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
86 return false;
Owen Anderson94ad7022008-04-29 00:38:34 +000087 return true;
88}
89
Anna Thomas53c8d952017-05-03 11:47:11 +000090/// This function returns true if there is no viable path from the
91/// entry block to the header of \p L. Right now, it only does
92/// a local search to save compile time.
93static bool isLoopNeverExecuted(Loop *L) {
94 using namespace PatternMatch;
95
96 auto *Preheader = L->getLoopPreheader();
97 // TODO: We can relax this constraint, since we just need a loop
98 // predecessor.
99 assert(Preheader && "Needs preheader!");
100
101 if (Preheader == &Preheader->getParent()->getEntryBlock())
102 return false;
103 // All predecessors of the preheader should have a constant conditional
104 // branch, with the loop's preheader as not-taken.
105 for (auto *Pred: predecessors(Preheader)) {
106 BasicBlock *Taken, *NotTaken;
107 ConstantInt *Cond;
108 if (!match(Pred->getTerminator(),
109 m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
110 return false;
111 if (!Cond->getZExtValue())
112 std::swap(Taken, NotTaken);
113 if (Taken == Preheader)
114 return false;
115 }
116 assert(!pred_empty(Preheader) &&
117 "Preheader should have predecessors at this point!");
118 // All the predecessors have the loop preheader as not-taken target.
119 return true;
120}
121
Chandler Carruth26169f002017-01-17 22:07:26 +0000122/// Remove a loop if it is dead.
123///
124/// A loop is considered dead if it does not impact the observable behavior of
125/// the program other than finite running time. This never removes a loop that
Anna Thomas53c8d952017-05-03 11:47:11 +0000126/// might be infinite (unless it is never executed), as doing so could change
127/// the halting/non-halting nature of a program.
Chandler Carruth26169f002017-01-17 22:07:26 +0000128///
129/// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
130/// order to make various safety checks work.
131///
Chandler Carruth027340f2017-02-11 00:09:30 +0000132/// \returns true if any changes were made. This may mutate the loop even if it
133/// is unable to delete it due to hoisting trivially loop invariant
134/// instructions out of the loop.
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000135static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT,
136 ScalarEvolution &SE, LoopInfo &LI) {
Sanjoy Das979a11d2016-02-21 17:11:59 +0000137 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
138
Anna Thomas90f69ab2017-07-04 14:05:19 +0000139 // We can only remove the loop if there is a preheader that we can branch from
140 // after removing it. Also, if LoopSimplify form is not available, stay out
141 // of trouble.
Chandler Carruthaa885c92017-01-17 22:19:56 +0000142 BasicBlock *Preheader = L->getLoopPreheader();
Anna Thomas90f69ab2017-07-04 14:05:19 +0000143 if (!Preheader || !L->hasDedicatedExits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000144 LLVM_DEBUG(
145 dbgs()
146 << "Deletion requires Loop with preheader and dedicated exits.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000147 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000148 }
Owen Anderson94ad7022008-04-29 00:38:34 +0000149 // We can't remove loops that contain subloops. If the subloops were dead,
150 // they would already have been removed in earlier executions of this pass.
Anna Thomas90f69ab2017-07-04 14:05:19 +0000151 if (L->begin() != L->end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000152 LLVM_DEBUG(dbgs() << "Loop contains subloops.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000153 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000154 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000155
Anna Thomas53c8d952017-05-03 11:47:11 +0000156
157 BasicBlock *ExitBlock = L->getUniqueExitBlock();
158
159 if (ExitBlock && isLoopNeverExecuted(L)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000160 LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
Anna Thomase7cb6332017-06-25 21:13:58 +0000161 // Set incoming value to undef for phi nodes in the exit block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000162 for (PHINode &P : ExitBlock->phis()) {
163 std::fill(P.incoming_values().begin(), P.incoming_values().end(),
164 UndefValue::get(P.getType()));
Anna Thomase7cb6332017-06-25 21:13:58 +0000165 }
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000166 deleteDeadLoop(L, &DT, &SE, &LI);
Anna Thomas53c8d952017-05-03 11:47:11 +0000167 ++NumDeleted;
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000168 return LoopDeletionResult::Deleted;
Anna Thomas53c8d952017-05-03 11:47:11 +0000169 }
170
171 // The remaining checks below are for a loop being dead because all statements
172 // in the loop are invariant.
Chandler Carruth04a73872017-01-17 21:51:39 +0000173 SmallVector<BasicBlock *, 4> ExitingBlocks;
174 L->getExitingBlocks(ExitingBlocks);
Nadav Rotem465834c2012-07-24 10:51:42 +0000175
Owen Andersonad5f2112008-05-16 04:32:45 +0000176 // We require that the loop only have a single exit block. Otherwise, we'd
177 // be in the situation of needing to be able to solve statically which exit
178 // block will be branched to, or trying to preserve the branching logic in
179 // a loop invariant manner.
Anna Thomas90f69ab2017-07-04 14:05:19 +0000180 if (!ExitBlock) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000181 LLVM_DEBUG(dbgs() << "Deletion requires single exit block\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000182 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000183 }
Owen Anderson94ad7022008-04-29 00:38:34 +0000184 // Finally, we have to check that the loop really is dead.
Chandler Carruth027340f2017-02-11 00:09:30 +0000185 bool Changed = false;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000186 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000187 LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000188 return Changed ? LoopDeletionResult::Modified
189 : LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000190 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000191
Owen Andersonad5f2112008-05-16 04:32:45 +0000192 // Don't remove loops for which we can't solve the trip count.
193 // They could be infinite, in which case we'd be changing program behavior.
Philip Reames7b051512019-08-14 21:58:13 +0000194 const SCEV *S = SE.getConstantMaxBackedgeTakenCount(L);
Anna Thomas90f69ab2017-07-04 14:05:19 +0000195 if (isa<SCEVCouldNotCompute>(S)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000196 LLVM_DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000197 return Changed ? LoopDeletionResult::Modified
198 : LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000199 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000200
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000201 LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000202 deleteDeadLoop(L, &DT, &SE, &LI);
Anna Thomas53c8d952017-05-03 11:47:11 +0000203 ++NumDeleted;
204
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000205 return LoopDeletionResult::Deleted;
Anna Thomas53c8d952017-05-03 11:47:11 +0000206}
207
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000208PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
209 LoopStandardAnalysisResults &AR,
Chandler Carruthd50c5fb2017-01-18 02:41:26 +0000210 LPMUpdater &Updater) {
Anna Thomas90f69ab2017-07-04 14:05:19 +0000211
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000212 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
213 LLVM_DEBUG(L.dump());
Sanjoy Dasdef17292017-09-28 02:45:42 +0000214 std::string LoopName = L.getName();
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000215 auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI);
216 if (Result == LoopDeletionResult::Unmodified)
Jun Bum Limc837af32016-07-14 18:28:29 +0000217 return PreservedAnalyses::all();
218
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000219 if (Result == LoopDeletionResult::Deleted)
Sanjoy Dasdef17292017-09-28 02:45:42 +0000220 Updater.markLoopAsDeleted(L, LoopName);
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000221
Jun Bum Limc837af32016-07-14 18:28:29 +0000222 return getLoopPassPreservedAnalyses();
223}
224
225namespace {
226class LoopDeletionLegacyPass : public LoopPass {
227public:
228 static char ID; // Pass ID, replacement for typeid
229 LoopDeletionLegacyPass() : LoopPass(ID) {
230 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
231 }
232
233 // Possibly eliminate loop L if it is dead.
234 bool runOnLoop(Loop *L, LPPassManager &) override;
235
236 void getAnalysisUsage(AnalysisUsage &AU) const override {
237 getLoopAnalysisUsage(AU);
238 }
239};
240}
241
242char LoopDeletionLegacyPass::ID = 0;
243INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
244 "Delete dead loops", false, false)
245INITIALIZE_PASS_DEPENDENCY(LoopPass)
246INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
247 "Delete dead loops", false, false)
248
249Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
250
Sanjoy Dasdef17292017-09-28 02:45:42 +0000251bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
Jun Bum Limc837af32016-07-14 18:28:29 +0000252 if (skipLoop(L))
253 return false;
Jun Bum Limc837af32016-07-14 18:28:29 +0000254 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
255 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruth04a73872017-01-17 21:51:39 +0000256 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Jun Bum Limc837af32016-07-14 18:28:29 +0000257
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000258 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
259 LLVM_DEBUG(L->dump());
Sanjoy Dasdef17292017-09-28 02:45:42 +0000260
261 LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI);
262
263 if (Result == LoopDeletionResult::Deleted)
264 LPM.markLoopAsDeleted(*L);
265
266 return Result != LoopDeletionResult::Unmodified;
Jun Bum Limc837af32016-07-14 18:28:29 +0000267}