blob: 82604a8842bf7445401379434f4f2d056d798356 [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.
Chandler Carruth04a73872017-01-17 21:51:39 +000052 BasicBlock::iterator BI = ExitBlock->begin();
Sanjoy Das905fc272016-05-03 17:50:02 +000053 bool AllEntriesInvariant = true;
54 bool AllOutgoingValuesSame = true;
Jakub Staszakbc421ef2013-03-18 23:31:30 +000055 while (PHINode *P = dyn_cast<PHINode>(BI)) {
Chandler Carruth04a73872017-01-17 21:51:39 +000056 Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
Cameron Zwarich82630852011-02-22 22:25:39 +000057
58 // Make sure all exiting blocks produce the same incoming value for the exit
59 // block. If there are different incoming values for different exiting
60 // blocks, then it is impossible to statically determine which value should
61 // be used.
Sanjoy Das7e7a5a02016-05-03 17:50:06 +000062 AllOutgoingValuesSame =
Chandler Carruth04a73872017-01-17 21:51:39 +000063 all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) {
Sanjoy Das7e7a5a02016-05-03 17:50:06 +000064 return incoming == P->getIncomingValueForBlock(BB);
65 });
Nadav Rotem465834c2012-07-24 10:51:42 +000066
Sanjoy Das905fc272016-05-03 17:50:02 +000067 if (!AllOutgoingValuesSame)
68 break;
69
Jakub Staszakbc421ef2013-03-18 23:31:30 +000070 if (Instruction *I = dyn_cast<Instruction>(incoming))
Sanjoy Das905fc272016-05-03 17:50:02 +000071 if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) {
72 AllEntriesInvariant = false;
73 break;
74 }
Cameron Zwarich82630852011-02-22 22:25:39 +000075
Dan Gohmand2d1ae12010-06-22 15:08:57 +000076 ++BI;
Owen Anderson94ad7022008-04-29 00:38:34 +000077 }
Nadav Rotem465834c2012-07-24 10:51:42 +000078
Sanjoy Das905fc272016-05-03 17:50:02 +000079 if (Changed)
80 SE.forgetLoopDispositions(L);
81
82 if (!AllEntriesInvariant || !AllOutgoingValuesSame)
83 return false;
84
Owen Anderson94ad7022008-04-29 00:38:34 +000085 // Make sure that no instructions in the block have potential side-effects.
Owen Andersone6746002008-04-29 20:59:33 +000086 // This includes instructions that could write to memory, and loads that are
Xin Tongdf4dff32017-02-23 23:47:10 +000087 // marked volatile.
Davide Italiano49a0aac2017-02-26 07:08:20 +000088 for (auto &I : L->blocks())
89 if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); }))
90 return false;
Owen Anderson94ad7022008-04-29 00:38:34 +000091 return true;
92}
93
Anna Thomas53c8d952017-05-03 11:47:11 +000094/// This function returns true if there is no viable path from the
95/// entry block to the header of \p L. Right now, it only does
96/// a local search to save compile time.
97static bool isLoopNeverExecuted(Loop *L) {
98 using namespace PatternMatch;
99
100 auto *Preheader = L->getLoopPreheader();
101 // TODO: We can relax this constraint, since we just need a loop
102 // predecessor.
103 assert(Preheader && "Needs preheader!");
104
105 if (Preheader == &Preheader->getParent()->getEntryBlock())
106 return false;
107 // All predecessors of the preheader should have a constant conditional
108 // branch, with the loop's preheader as not-taken.
109 for (auto *Pred: predecessors(Preheader)) {
110 BasicBlock *Taken, *NotTaken;
111 ConstantInt *Cond;
112 if (!match(Pred->getTerminator(),
113 m_Br(m_ConstantInt(Cond), Taken, NotTaken)))
114 return false;
115 if (!Cond->getZExtValue())
116 std::swap(Taken, NotTaken);
117 if (Taken == Preheader)
118 return false;
119 }
120 assert(!pred_empty(Preheader) &&
121 "Preheader should have predecessors at this point!");
122 // All the predecessors have the loop preheader as not-taken target.
123 return true;
124}
125
Chandler Carruth26169f002017-01-17 22:07:26 +0000126/// Remove a loop if it is dead.
127///
128/// A loop is considered dead if it does not impact the observable behavior of
129/// the program other than finite running time. This never removes a loop that
Anna Thomas53c8d952017-05-03 11:47:11 +0000130/// might be infinite (unless it is never executed), as doing so could change
131/// the halting/non-halting nature of a program.
Chandler Carruth26169f002017-01-17 22:07:26 +0000132///
133/// This entire process relies pretty heavily on LoopSimplify form and LCSSA in
134/// order to make various safety checks work.
135///
Chandler Carruth027340f2017-02-11 00:09:30 +0000136/// \returns true if any changes were made. This may mutate the loop even if it
137/// is unable to delete it due to hoisting trivially loop invariant
138/// instructions out of the loop.
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000139static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT,
140 ScalarEvolution &SE, LoopInfo &LI) {
Sanjoy Das979a11d2016-02-21 17:11:59 +0000141 assert(L->isLCSSAForm(DT) && "Expected LCSSA!");
142
Anna Thomas90f69ab2017-07-04 14:05:19 +0000143 // We can only remove the loop if there is a preheader that we can branch from
144 // after removing it. Also, if LoopSimplify form is not available, stay out
145 // of trouble.
Chandler Carruthaa885c92017-01-17 22:19:56 +0000146 BasicBlock *Preheader = L->getLoopPreheader();
Anna Thomas90f69ab2017-07-04 14:05:19 +0000147 if (!Preheader || !L->hasDedicatedExits()) {
148 DEBUG(dbgs()
149 << "Deletion requires Loop with preheader and dedicated exits.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000150 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000151 }
Owen Anderson94ad7022008-04-29 00:38:34 +0000152 // We can't remove loops that contain subloops. If the subloops were dead,
153 // they would already have been removed in earlier executions of this pass.
Anna Thomas90f69ab2017-07-04 14:05:19 +0000154 if (L->begin() != L->end()) {
155 DEBUG(dbgs() << "Loop contains subloops.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000156 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000157 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000158
Anna Thomas53c8d952017-05-03 11:47:11 +0000159
160 BasicBlock *ExitBlock = L->getUniqueExitBlock();
161
162 if (ExitBlock && isLoopNeverExecuted(L)) {
Anna Thomas90f69ab2017-07-04 14:05:19 +0000163 DEBUG(dbgs() << "Loop is proven to never execute, delete it!");
Anna Thomase7cb6332017-06-25 21:13:58 +0000164 // Set incoming value to undef for phi nodes in the exit block.
165 BasicBlock::iterator BI = ExitBlock->begin();
166 while (PHINode *P = dyn_cast<PHINode>(BI)) {
167 for (unsigned i = 0; i < P->getNumIncomingValues(); i++)
168 P->setIncomingValue(i, UndefValue::get(P->getType()));
169 BI++;
170 }
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000171 deleteDeadLoop(L, &DT, &SE, &LI);
Anna Thomas53c8d952017-05-03 11:47:11 +0000172 ++NumDeleted;
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000173 return LoopDeletionResult::Deleted;
Anna Thomas53c8d952017-05-03 11:47:11 +0000174 }
175
176 // The remaining checks below are for a loop being dead because all statements
177 // in the loop are invariant.
Chandler Carruth04a73872017-01-17 21:51:39 +0000178 SmallVector<BasicBlock *, 4> ExitingBlocks;
179 L->getExitingBlocks(ExitingBlocks);
Nadav Rotem465834c2012-07-24 10:51:42 +0000180
Owen Andersonad5f2112008-05-16 04:32:45 +0000181 // 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.
Anna Thomas90f69ab2017-07-04 14:05:19 +0000185 if (!ExitBlock) {
186 DEBUG(dbgs() << "Deletion requires single exit block\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000187 return LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000188 }
Owen Anderson94ad7022008-04-29 00:38:34 +0000189 // Finally, we have to check that the loop really is dead.
Chandler Carruth027340f2017-02-11 00:09:30 +0000190 bool Changed = false;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000191 if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) {
192 DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000193 return Changed ? LoopDeletionResult::Modified
194 : LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000195 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000196
Owen Andersonad5f2112008-05-16 04:32:45 +0000197 // Don't remove loops for which we can't solve the trip count.
198 // They could be infinite, in which case we'd be changing program behavior.
Dan Gohman41d00ac2009-10-23 17:10:01 +0000199 const SCEV *S = SE.getMaxBackedgeTakenCount(L);
Anna Thomas90f69ab2017-07-04 14:05:19 +0000200 if (isa<SCEVCouldNotCompute>(S)) {
201 DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n");
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000202 return Changed ? LoopDeletionResult::Modified
203 : LoopDeletionResult::Unmodified;
Anna Thomas90f69ab2017-07-04 14:05:19 +0000204 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000205
Anna Thomas90f69ab2017-07-04 14:05:19 +0000206 DEBUG(dbgs() << "Loop is invariant, delete it!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000207 deleteDeadLoop(L, &DT, &SE, &LI);
Anna Thomas53c8d952017-05-03 11:47:11 +0000208 ++NumDeleted;
209
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000210 return LoopDeletionResult::Deleted;
Anna Thomas53c8d952017-05-03 11:47:11 +0000211}
212
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000213PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM,
214 LoopStandardAnalysisResults &AR,
Chandler Carruthd50c5fb2017-01-18 02:41:26 +0000215 LPMUpdater &Updater) {
Anna Thomas90f69ab2017-07-04 14:05:19 +0000216
217 DEBUG(dbgs() << "Analyzing Loop for deletion: ");
218 DEBUG(L.dump());
Sanjoy Dasdef17292017-09-28 02:45:42 +0000219 std::string LoopName = L.getName();
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000220 auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI);
221 if (Result == LoopDeletionResult::Unmodified)
Jun Bum Limc837af32016-07-14 18:28:29 +0000222 return PreservedAnalyses::all();
223
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000224 if (Result == LoopDeletionResult::Deleted)
Sanjoy Dasdef17292017-09-28 02:45:42 +0000225 Updater.markLoopAsDeleted(L, LoopName);
Sanjoy Das8e8c1bc2017-09-27 21:45:21 +0000226
Jun Bum Limc837af32016-07-14 18:28:29 +0000227 return getLoopPassPreservedAnalyses();
228}
229
230namespace {
231class LoopDeletionLegacyPass : public LoopPass {
232public:
233 static char ID; // Pass ID, replacement for typeid
234 LoopDeletionLegacyPass() : LoopPass(ID) {
235 initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry());
236 }
237
238 // Possibly eliminate loop L if it is dead.
239 bool runOnLoop(Loop *L, LPPassManager &) override;
240
241 void getAnalysisUsage(AnalysisUsage &AU) const override {
242 getLoopAnalysisUsage(AU);
243 }
244};
245}
246
247char LoopDeletionLegacyPass::ID = 0;
248INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion",
249 "Delete dead loops", false, false)
250INITIALIZE_PASS_DEPENDENCY(LoopPass)
251INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion",
252 "Delete dead loops", false, false)
253
254Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); }
255
Sanjoy Dasdef17292017-09-28 02:45:42 +0000256bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
Jun Bum Limc837af32016-07-14 18:28:29 +0000257 if (skipLoop(L))
258 return false;
Jun Bum Limc837af32016-07-14 18:28:29 +0000259 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
260 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruth04a73872017-01-17 21:51:39 +0000261 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Jun Bum Limc837af32016-07-14 18:28:29 +0000262
Anna Thomasada4ddc2017-07-04 17:00:03 +0000263 DEBUG(dbgs() << "Analyzing Loop for deletion: ");
264 DEBUG(L->dump());
Sanjoy Dasdef17292017-09-28 02:45:42 +0000265
266 LoopDeletionResult Result = deleteLoopIfDead(L, DT, SE, LI);
267
268 if (Result == LoopDeletionResult::Deleted)
269 LPM.markLoopAsDeleted(*L);
270
271 return Result != LoopDeletionResult::Unmodified;
Jun Bum Limc837af32016-07-14 18:28:29 +0000272}