blob: d412025d7e9458dfb0735a9cf28f39c0ca9753b2 [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//
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//
Gordon Henriksen829046b2008-05-08 17:46:35 +000010// 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.
Owen Anderson94ad7022008-04-29 00:38:34 +000014//
15//===----------------------------------------------------------------------===//
16
Jun Bum Limc837af32016-07-14 18:28:29 +000017#include "llvm/Transforms/Scalar/LoopDeletion.h"
Owen Anderson94ad7022008-04-29 00:38:34 +000018#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/Statistic.h"
James Molloyefbba722015-09-10 10:22:12 +000020#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/LoopPass.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Anna Thomas53c8d952017-05-03 11:47:11 +000023#include "llvm/IR/PatternMatch.h"
Jun Bum Limc837af32016-07-14 18:28:29 +000024#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000025#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000026#include "llvm/Transforms/Utils/LoopUtils.h"
Owen Anderson94ad7022008-04-29 00:38:34 +000027using namespace llvm;
28
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "loop-delete"
30
Owen Anderson94ad7022008-04-29 00:38:34 +000031STATISTIC(NumDeleted, "Number of loops deleted");
32
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +000033enum class LoopDeletionResult {
34 Unmodified,
35 Modified,
36 Deleted,
37};
38
Chandler Carruth26169f002017-01-17 22:07:26 +000039/// Determines if a loop is dead.
40///
41/// This assumes that we've already checked for unique exit and exiting blocks,
42/// and that the code is in LCSSA form.
43static bool isLoopDead(Loop *L, ScalarEvolution &SE,
44 SmallVectorImpl<BasicBlock *> &ExitingBlocks,
45 BasicBlock *ExitBlock, bool &Changed,
46 BasicBlock *Preheader) {
Owen Anderson94ad7022008-04-29 00:38:34 +000047 // Make sure that all PHI entries coming from the loop are loop invariant.
Owen Andersone6746002008-04-29 20:59:33 +000048 // Because the code is in LCSSA form, any values used outside of the loop
49 // must pass through a PHI in the exit block, meaning that this check is
50 // sufficient to guarantee that no loop-variant values are used outside
51 // of the loop.
Sanjoy Das905fc272016-05-03 17:50:02 +000052 bool AllEntriesInvariant = true;
53 bool AllOutgoingValuesSame = true;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000054 for (PHINode &P : ExitBlock->phis()) {
55 Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]);
Cameron Zwarich82630852011-02-22 22:25:39 +000056
57 // Make sure all exiting blocks produce the same incoming value for the exit
58 // block. If there are different incoming values for different exiting
59 // blocks, then it is impossible to statically determine which value should
60 // be used.
Sanjoy Das7e7a5a02016-05-03 17:50:06 +000061 AllOutgoingValuesSame =
Chandler Carruth04a73872017-01-17 21:51:39 +000062 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000063 return incoming == P.getIncomingValueForBlock(BB);
Sanjoy Das7e7a5a02016-05-03 17:50:06 +000064 });
Nadav Rotem465834c2012-07-24 10:51:42 +000065
Sanjoy Das905fc272016-05-03 17:50:02 +000066 if (!AllOutgoingValuesSame)
67 break;
68
Jakub Staszakbc421ef2013-03-18 23:31:30 +000069 if (Instruction *I = dyn_cast<Instruction>(incoming))
Sanjoy Das905fc272016-05-03 17:50:02 +000070 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
71 AllEntriesInvariant = false;
72 break;
73 }
Owen Anderson94ad7022008-04-29 00:38:34 +000074 }
Nadav Rotem465834c2012-07-24 10:51:42 +000075
Sanjoy Das905fc272016-05-03 17:50:02 +000076 if (Changed)
77 SE.forgetLoopDispositions(L);
78
79 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
80 return false;
81
Owen Anderson94ad7022008-04-29 00:38:34 +000082 // Make sure that no instructions in the block have potential side-effects.
Owen Andersone6746002008-04-29 20:59:33 +000083 // This includes instructions that could write to memory, and loads that are
Xin Tongdf4dff32017-02-23 23:47:10 +000084 // marked volatile.
Davide Italiano49a0aac2017-02-26 07:08:20 +000085 for (auto &I : L->blocks())
86 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
87 return false;
Owen Anderson94ad7022008-04-29 00:38:34 +000088 return true;
89}
90
Anna Thomas53c8d952017-05-03 11:47:11 +000091/// This function returns true if there is no viable path from the
92/// entry block to the header of \p L. Right now, it only does
93/// a local search to save compile time.
94static bool isLoopNeverExecuted(Loop *L) {
95 using namespace PatternMatch;
96
97 auto *Preheader = L->getLoopPreheader();
98 // TODO: We can relax this constraint, since we just need a loop
99 // predecessor.
100 assert(Preheader && "Needs preheader!");
101
102 if (Preheader == &Preheader->getParent()->getEntryBlock())
103 return false;
104 // All predecessors of the preheader should have a constant conditional
105 // branch, with the loop's preheader as not-taken.
106 for (auto *Pred: predecessors(Preheader)) {
107 BasicBlock *Taken, *NotTaken;
108 ConstantInt *Cond;
109 if (!match(Pred->getTerminator(),
110 m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
111 return false;
112 if (!Cond->getZExtValue())
113 std::swap(Taken, NotTaken);
114 if (Taken == Preheader)
115 return false;
116 }
117 assert(!pred_empty(Preheader) &&
118 "Preheader should have predecessors at this point!");
119 // All the predecessors have the loop preheader as not-taken target.
120 return true;
121}
122
Chandler Carruth26169f002017-01-17 22:07:26 +0000123/// Remove a loop if it is dead.
124///
125/// A loop is considered dead if it does not impact the observable behavior of
126/// the program other than finite running time. This never removes a loop that
Anna Thomas53c8d952017-05-03 11:47:11 +0000127/// might be infinite (unless it is never executed), as doing so could change
128/// the halting/non-halting nature of a program.
Chandler Carruth26169f002017-01-17 22:07:26 +0000129///
130/// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
131/// order to make various safety checks work.
132///
Chandler Carruth027340f2017-02-11 00:09:30 +0000133/// \returns true if any changes were made. This may mutate the loop even if it
134/// is unable to delete it due to hoisting trivially loop invariant
135/// instructions out of the loop.
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000136static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT,
137 ScalarEvolution &SE, LoopInfo &LI) {
Sanjoy Das979a11d2016-02-21 17:11:59 +0000138 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
139
Anna Thomas90f69ab2017-07-04 14:05:19 +0000140 // We can only remove the loop if there is a preheader that we can branch from
141 // after removing it. Also, if LoopSimplify form is not available, stay out
142 // of trouble.
Chandler Carruthaa885c92017-01-17 22:19:56 +0000143 BasicBlock *Preheader = L->getLoopPreheader();
Anna Thomas90f69ab2017-07-04 14:05:19 +0000144 if (!Preheader || !L->hasDedicatedExits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000145 LLVM_DEBUG(
146 dbgs()
147 << "Deletion requires Loop with preheader and dedicated exits.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000148 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000149 }
Owen Anderson94ad7022008-04-29 00:38:34 +0000150 // We can't remove loops that contain subloops. If the subloops were dead,
151 // they would already have been removed in earlier executions of this pass.
Anna Thomas90f69ab2017-07-04 14:05:19 +0000152 if (L->begin() != L->end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000153 LLVM_DEBUG(dbgs() << "Loop contains subloops.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000154 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000155 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000156
Anna Thomas53c8d952017-05-03 11:47:11 +0000157
158 BasicBlock *ExitBlock = L->getUniqueExitBlock();
159
160 if (ExitBlock && isLoopNeverExecuted(L)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000161 LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
Anna Thomase7cb6332017-06-25 21:13:58 +0000162 // Set incoming value to undef for phi nodes in the exit block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000163 for (PHINode &P : ExitBlock->phis()) {
164 std::fill(P.incoming_values().begin(), P.incoming_values().end(),
165 UndefValue::get(P.getType()));
Anna Thomase7cb6332017-06-25 21:13:58 +0000166 }
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000167 deleteDeadLoop(L, &DT, &SE, &LI);
Anna Thomas53c8d952017-05-03 11:47:11 +0000168 ++NumDeleted;
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000169 return LoopDeletionResult::Deleted;
Anna Thomas53c8d952017-05-03 11:47:11 +0000170 }
171
172 // The remaining checks below are for a loop being dead because all statements
173 // in the loop are invariant.
Chandler Carruth04a73872017-01-17 21:51:39 +0000174 SmallVector<BasicBlock *, 4> ExitingBlocks;
175 L->getExitingBlocks(ExitingBlocks);
Nadav Rotem465834c2012-07-24 10:51:42 +0000176
Owen Andersonad5f2112008-05-16 04:32:45 +0000177 // We require that the loop only have a single exit block. Otherwise, we'd
178 // be in the situation of needing to be able to solve statically which exit
179 // block will be branched to, or trying to preserve the branching logic in
180 // a loop invariant manner.
Anna Thomas90f69ab2017-07-04 14:05:19 +0000181 if (!ExitBlock) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000182 LLVM_DEBUG(dbgs() << "Deletion requires single exit block\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000183 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000184 }
Owen Anderson94ad7022008-04-29 00:38:34 +0000185 // Finally, we have to check that the loop really is dead.
Chandler Carruth027340f2017-02-11 00:09:30 +0000186 bool Changed = false;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000187 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000188 LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000189 return Changed ? LoopDeletionResult::Modified
190 : LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000191 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000192
Owen Andersonad5f2112008-05-16 04:32:45 +0000193 // 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.
Dan Gohman41d00ac2009-10-23 17:10:01 +0000195 const SCEV *S = SE.getMaxBackedgeTakenCount(L);
Anna Thomas90f69ab2017-07-04 14:05:19 +0000196 if (isa<SCEVCouldNotCompute>(S)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000197 LLVM_DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000198 return Changed ? LoopDeletionResult::Modified
199 : LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000200 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000201
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000202 LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000203 deleteDeadLoop(L, &DT, &SE, &LI);
Anna Thomas53c8d952017-05-03 11:47:11 +0000204 ++NumDeleted;
205
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000206 return LoopDeletionResult::Deleted;
Anna Thomas53c8d952017-05-03 11:47:11 +0000207}
208
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000209PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
210 LoopStandardAnalysisResults &AR,
Chandler Carruthd50c5fb2017-01-18 02:41:26 +0000211 LPMUpdater &Updater) {
Anna Thomas90f69ab2017-07-04 14:05:19 +0000212
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000213 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
214 LLVM_DEBUG(L.dump());
Sanjoy Dasdef17292017-09-28 02:45:42 +0000215 std::string LoopName = L.getName();
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000216 auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI);
217 if (Result == LoopDeletionResult::Unmodified)
Jun Bum Limc837af32016-07-14 18:28:29 +0000218 return PreservedAnalyses::all();
219
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000220 if (Result == LoopDeletionResult::Deleted)
Sanjoy Dasdef17292017-09-28 02:45:42 +0000221 Updater.markLoopAsDeleted(L, LoopName);
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000222
Jun Bum Limc837af32016-07-14 18:28:29 +0000223 return getLoopPassPreservedAnalyses();
224}
225
226namespace {
227class LoopDeletionLegacyPass : public LoopPass {
228public:
229 static char ID; // Pass ID, replacement for typeid
230 LoopDeletionLegacyPass() : LoopPass(ID) {
231 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
232 }
233
234 // Possibly eliminate loop L if it is dead.
235 bool runOnLoop(Loop *L, LPPassManager &) override;
236
237 void getAnalysisUsage(AnalysisUsage &AU) const override {
238 getLoopAnalysisUsage(AU);
239 }
240};
241}
242
243char LoopDeletionLegacyPass::ID = 0;
244INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
245 "Delete dead loops", false, false)
246INITIALIZE_PASS_DEPENDENCY(LoopPass)
247INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
248 "Delete dead loops", false, false)
249
250Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
251
Sanjoy Dasdef17292017-09-28 02:45:42 +0000252bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
Jun Bum Limc837af32016-07-14 18:28:29 +0000253 if (skipLoop(L))
254 return false;
Jun Bum Limc837af32016-07-14 18:28:29 +0000255 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
256 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruth04a73872017-01-17 21:51:39 +0000257 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Jun Bum Limc837af32016-07-14 18:28:29 +0000258
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000259 LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: ");
260 LLVM_DEBUG(L->dump());
Sanjoy Dasdef17292017-09-28 02:45:42 +0000261
262 LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI);
263
264 if (Result == LoopDeletionResult::Deleted)
265 LPM.markLoopAsDeleted(*L);
266
267 return Result != LoopDeletionResult::Unmodified;
Jun Bum Limc837af32016-07-14 18:28:29 +0000268}