blob: a4fdd55adc1533a040421f1d7f2e670288a21931 [file] [log] [blame]
Andrew Trick3ec331e2011-08-10 03:46:27 +00001//===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
2//
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//
10// This file implements induction variable simplification. It does
11// not define any actual pass or policy, but provides a single function to
12// simplify a loop's induction variables based on ScalarEvolution.
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000020#include "llvm/Analysis/IVUsers.h"
21#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000026#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
Andrew Trick0ba77a02013-12-23 23:31:49 +000028#include "llvm/IR/IntrinsicInst.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000032
33using namespace llvm;
34
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "indvars"
36
Andrew Trick3ec331e2011-08-10 03:46:27 +000037STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
38STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
39STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
40STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
41
42namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000043 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000044 /// based on ScalarEvolution. It is the primary instrument of the
45 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
46 /// other loop passes that preserve SCEV.
47 class SimplifyIndvar {
48 Loop *L;
49 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000050 ScalarEvolution *SE;
Rafael Espindola37dc9e12014-02-21 00:06:31 +000051 const DataLayout *DL; // May be NULL
Andrew Trick3ec331e2011-08-10 03:46:27 +000052
53 SmallVectorImpl<WeakVH> &DeadInsts;
54
55 bool Changed;
56
57 public:
Andrew Tricke629d002011-08-10 04:22:26 +000058 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
Craig Topperf40110f2014-04-25 05:29:35 +000059 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = nullptr) :
Andrew Trick3ec331e2011-08-10 03:46:27 +000060 L(Loop),
61 LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
Andrew Tricke629d002011-08-10 04:22:26 +000062 SE(SE),
Andrew Trick3ec331e2011-08-10 03:46:27 +000063 DeadInsts(Dead),
64 Changed(false) {
Rafael Espindola93512512014-02-25 17:30:31 +000065 DataLayoutPass *DLP = LPM->getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +000066 DL = DLP ? &DLP->getDataLayout() : nullptr;
Andrew Tricke629d002011-08-10 04:22:26 +000067 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000068 }
69
70 bool hasChanged() const { return Changed; }
71
72 /// Iteratively perform simplification on a worklist of users of the
73 /// specified induction variable. This is the top-level driver that applies
74 /// all simplicitions to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000075 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000076
Andrew Trick74664d52011-08-10 04:01:31 +000077 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000078
79 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
80 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
81 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
82 bool IsSigned);
Andrew Trick0ba77a02013-12-23 23:31:49 +000083
84 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
85 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000086 };
87}
88
Sanjay Patel7777b502014-11-12 18:07:42 +000089/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000090/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000091///
Andrew Trick7251e412011-09-19 17:54:39 +000092/// IVOperand is guaranteed SCEVable, but UseInst may not be.
93///
Andrew Trick74664d52011-08-10 04:01:31 +000094/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000095/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000096/// Otherwise return null.
97Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000098 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000099 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000100 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000101 switch (UseInst->getOpcode()) {
102 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000103 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000104 case Instruction::UDiv:
105 case Instruction::LShr:
106 // We're only interested in the case where we know something about
107 // the numerator and have a constant denominator.
108 if (IVOperand != UseInst->getOperand(OperIdx) ||
109 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000110 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000111
112 // Attempt to fold a binary operator with constant operand.
113 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000114 if (!isa<BinaryOperator>(IVOperand)
115 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000116 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000117
118 IVSrc = IVOperand->getOperand(0);
119 // IVSrc must be the (SCEVable) IV, since the other operand is const.
120 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
121
122 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
123 if (UseInst->getOpcode() == Instruction::LShr) {
124 // Get a constant for the divisor. See createSCEV.
125 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
126 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000127 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000128
129 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000130 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000131 }
132 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
133 }
134 // We have something that might fold it's operand. Compare SCEVs.
135 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000137
138 // Bypass the operand if SCEV can prove it has no effect.
139 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000140 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000141
142 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
143 << " -> " << *UseInst << '\n');
144
145 UseInst->setOperand(OperIdx, IVSrc);
146 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
147
148 ++NumElimOperand;
149 Changed = true;
150 if (IVOperand->use_empty())
151 DeadInsts.push_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000152 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000153}
154
Sanjay Patel7777b502014-11-12 18:07:42 +0000155/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000156/// comparisons against an induction variable.
157void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
158 unsigned IVOperIdx = 0;
159 ICmpInst::Predicate Pred = ICmp->getPredicate();
160 if (IVOperand != ICmp->getOperand(0)) {
161 // Swapped
162 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
163 IVOperIdx = 1;
164 Pred = ICmpInst::getSwappedPredicate(Pred);
165 }
166
167 // Get the SCEVs for the ICmp operands.
168 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
169 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
170
171 // Simplify unnecessary loops away.
172 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
173 S = SE->getSCEVAtScope(S, ICmpLoop);
174 X = SE->getSCEVAtScope(X, ICmpLoop);
175
176 // If the condition is always true or always false, replace it with
177 // a constant value.
178 if (SE->isKnownPredicate(Pred, S, X))
179 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
180 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
181 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
182 else
183 return;
184
185 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
186 ++NumElimCmp;
187 Changed = true;
188 DeadInsts.push_back(ICmp);
189}
190
Sanjay Patel7777b502014-11-12 18:07:42 +0000191/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000192/// remainder operations operating on an induction variable.
193void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
194 Value *IVOperand,
195 bool IsSigned) {
196 // We're only interested in the case where we know something about
197 // the numerator.
198 if (IVOperand != Rem->getOperand(0))
199 return;
200
201 // Get the SCEVs for the ICmp operands.
202 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
203 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
204
205 // Simplify unnecessary loops away.
206 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
207 S = SE->getSCEVAtScope(S, ICmpLoop);
208 X = SE->getSCEVAtScope(X, ICmpLoop);
209
210 // i % n --> i if i is in [0,n).
211 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
212 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
213 S, X))
214 Rem->replaceAllUsesWith(Rem->getOperand(0));
215 else {
216 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
217 const SCEV *LessOne =
218 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
219 if (IsSigned && !SE->isKnownNonNegative(LessOne))
220 return;
221
222 if (!SE->isKnownPredicate(IsSigned ?
223 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
224 LessOne, X))
225 return;
226
227 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000228 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000229 SelectInst *Sel =
230 SelectInst::Create(ICmp,
231 ConstantInt::get(Rem->getType(), 0),
232 Rem->getOperand(0), "tmp", Rem);
233 Rem->replaceAllUsesWith(Sel);
234 }
235
Andrew Trick3ec331e2011-08-10 03:46:27 +0000236 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
237 ++NumElimRem;
238 Changed = true;
239 DeadInsts.push_back(Rem);
240}
241
Sanjay Patel7777b502014-11-12 18:07:42 +0000242/// Eliminate an operation that consumes a simple IV and has
Andrew Trick3ec331e2011-08-10 03:46:27 +0000243/// no observable side-effect given the range of IV values.
Andrew Trick7251e412011-09-19 17:54:39 +0000244/// IVOperand is guaranteed SCEVable, but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000245bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
246 Instruction *IVOperand) {
247 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
248 eliminateIVComparison(ICmp, IVOperand);
249 return true;
250 }
251 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
252 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
253 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
254 eliminateIVRemainder(Rem, IVOperand, IsSigned);
255 return true;
256 }
257 }
258
259 // Eliminate any operation that SCEV can prove is an identity function.
260 if (!SE->isSCEVable(UseInst->getType()) ||
261 (UseInst->getType() != IVOperand->getType()) ||
262 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
263 return false;
264
265 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
266
267 UseInst->replaceAllUsesWith(IVOperand);
268 ++NumElimIdentity;
269 Changed = true;
270 DeadInsts.push_back(UseInst);
271 return true;
272}
273
Andrew Trick0ba77a02013-12-23 23:31:49 +0000274/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
275/// analysis and optimization.
276///
277/// \return A new value representing the non-overflowing add if possible,
278/// otherwise return the original value.
279Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
280 const DominatorTree *DT) {
281 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
282 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
283 return IVUser;
284
285 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000286 BranchInst *Branch = nullptr;
287 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000288 for (User *U : II->users()) {
289 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000290 if (ExtractInst->getNumIndices() != 1)
291 continue;
292 if (ExtractInst->getIndices()[0] == 0)
293 AddVal = ExtractInst;
294 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000295 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000296 }
297 }
298 if (!AddVal || !Branch)
299 return IVUser;
300
301 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000302 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000303 return IVUser;
304
305 // Check if all users of the add are provably NSW.
306 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000307 for (Use &U : AddVal->uses()) {
308 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000309 BasicBlock *UseBB = UseInst->getParent();
310 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000311 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000312 if (!DT->dominates(ContinueBB, UseBB)) {
313 AllNSW = false;
314 break;
315 }
316 }
317 }
318 if (!AllNSW)
319 return IVUser;
320
321 // Go for it...
322 IRBuilder<> Builder(IVUser);
323 Instruction *AddInst = dyn_cast<Instruction>(
324 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
325
326 // The caller expects the new add to have the same form as the intrinsic. The
327 // IV operand position must be the same.
328 assert((AddInst->getOpcode() == Instruction::Add &&
329 AddInst->getOperand(0) == II->getOperand(0)) &&
330 "Bad add instruction created from overflow intrinsic.");
331
332 AddVal->replaceAllUsesWith(AddInst);
333 DeadInsts.push_back(AddVal);
334 return AddInst;
335}
336
Sanjay Patel7777b502014-11-12 18:07:42 +0000337/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000338static void pushIVUsers(
339 Instruction *Def,
340 SmallPtrSet<Instruction*,16> &Simplified,
341 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
342
Chandler Carruthcdf47882014-03-09 03:16:01 +0000343 for (User *U : Def->users()) {
344 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000345
346 // Avoid infinite or exponential worklist processing.
347 // Also ensure unique worklist users.
348 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
349 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000350 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000351 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000352 }
353}
354
Sanjay Patel7777b502014-11-12 18:07:42 +0000355/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000356/// expression in terms of that IV.
357///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000358/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000359/// non-recursively when the operand is already known to be a simpleIVUser.
360///
361static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
362 if (!SE->isSCEVable(I->getType()))
363 return false;
364
365 // Get the symbolic expression for this instruction.
366 const SCEV *S = SE->getSCEV(I);
367
368 // Only consider affine recurrences.
369 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
370 if (AR && AR->getLoop() == L)
371 return true;
372
373 return false;
374}
375
Sanjay Patel7777b502014-11-12 18:07:42 +0000376/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000377/// of the specified induction variable. Each successive simplification may push
378/// more users which may themselves be candidates for simplification.
379///
380/// This algorithm does not require IVUsers analysis. Instead, it simplifies
381/// instructions in-place during analysis. Rather than rewriting induction
382/// variables bottom-up from their users, it transforms a chain of IVUsers
383/// top-down, updating the IR only when it encouters a clear optimization
384/// opportunitiy.
385///
386/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
387///
388void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000389 if (!SE->isSCEVable(CurrIV->getType()))
390 return;
391
Andrew Trick3ec331e2011-08-10 03:46:27 +0000392 // Instructions processed by SimplifyIndvar for CurrIV.
393 SmallPtrSet<Instruction*,16> Simplified;
394
395 // Use-def pairs if IV users waiting to be processed for CurrIV.
396 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
397
398 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
399 // called multiple times for the same LoopPhi. This is the proper thing to
400 // do for loop header phis that use each other.
401 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
402
403 while (!SimpleIVUsers.empty()) {
404 std::pair<Instruction*, Instruction*> UseOper =
405 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000406 Instruction *UseInst = UseOper.first;
407
Andrew Trick3ec331e2011-08-10 03:46:27 +0000408 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000409 if (UseInst == CurrIV) continue;
410
411 if (V && V->shouldSplitOverflowInstrinsics()) {
412 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
413 if (!UseInst)
414 continue;
415 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000416
Andrew Trick74664d52011-08-10 04:01:31 +0000417 Instruction *IVOperand = UseOper.second;
418 for (unsigned N = 0; IVOperand; ++N) {
419 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000420
Andrew Trick74664d52011-08-10 04:01:31 +0000421 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
422 if (!NewOper)
423 break; // done folding
424 IVOperand = dyn_cast<Instruction>(NewOper);
425 }
426 if (!IVOperand)
427 continue;
428
429 if (eliminateIVUser(UseOper.first, IVOperand)) {
430 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000431 continue;
432 }
433 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
434 if (V && Cast) {
435 V->visitCast(Cast);
436 continue;
437 }
438 if (isSimpleIVUser(UseOper.first, L, SE)) {
439 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
440 }
441 }
442}
443
444namespace llvm {
445
David Blaikiea379b1812011-12-20 02:50:00 +0000446void IVVisitor::anchor() { }
447
Sanjay Patel7777b502014-11-12 18:07:42 +0000448/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000449/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Tricke629d002011-08-10 04:22:26 +0000450bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000451 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
452{
453 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
Andrew Tricke629d002011-08-10 04:22:26 +0000454 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000455 SIV.simplifyUsers(CurrIV, V);
456 return SIV.hasChanged();
457}
458
Sanjay Patel7777b502014-11-12 18:07:42 +0000459/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000460/// loop. This does not actually change or add IVs.
Andrew Tricke629d002011-08-10 04:22:26 +0000461bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000462 SmallVectorImpl<WeakVH> &Dead) {
463 bool Changed = false;
464 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Tricke629d002011-08-10 04:22:26 +0000465 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000466 }
467 return Changed;
468}
469
Andrew Trick3ec331e2011-08-10 03:46:27 +0000470} // namespace llvm