blob: 66e63351822157eaa886271650407b3cd2c66ecf [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/LoopInfo.h"
21#include "llvm/Analysis/LoopPass.h"
Hongbin Zhengd36f20302017-10-12 02:54:11 +000022#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000025#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
Andrew Trick0ba77a02013-12-23 23:31:49 +000027#include "llvm/IR/IntrinsicInst.h"
David Greenb26a0a42017-07-05 13:25:58 +000028#include "llvm/IR/PatternMatch.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000031
32using namespace llvm;
33
Chandler Carruth964daaa2014-04-22 02:55:47 +000034#define DEBUG_TYPE "indvars"
35
Andrew Trick3ec331e2011-08-10 03:46:27 +000036STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
37STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +000038STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
Andrew Trick3ec331e2011-08-10 03:46:27 +000039STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000040STATISTIC(
41 NumSimplifiedSDiv,
42 "Number of IV signed division operations converted to unsigned division");
Hongbin Zhengf0093e42017-09-25 17:39:40 +000043STATISTIC(
44 NumSimplifiedSRem,
45 "Number of IV signed remainder operations converted to unsigned remainder");
Andrew Trick3ec331e2011-08-10 03:46:27 +000046STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
47
48namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000049 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000050 /// based on ScalarEvolution. It is the primary instrument of the
51 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
52 /// other loop passes that preserve SCEV.
53 class SimplifyIndvar {
54 Loop *L;
55 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000056 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000057 DominatorTree *DT;
Hongbin Zhengd36f20302017-10-12 02:54:11 +000058 SCEVExpander &Rewriter;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000059 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000060
61 bool Changed;
62
63 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000064 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Hongbin Zhengd36f20302017-10-12 02:54:11 +000065 LoopInfo *LI, SCEVExpander &Rewriter,
66 SmallVectorImpl<WeakTrackingVH> &Dead)
67 : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
68 Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000069 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000070 }
71
72 bool hasChanged() const { return Changed; }
73
74 /// Iteratively perform simplification on a worklist of users of the
75 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000076 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000077 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000078
Andrew Trick74664d52011-08-10 04:01:31 +000079 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000080
Sanjoy Das088bb0e2015-10-06 21:44:39 +000081 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
Hongbin Zhengd36f20302017-10-12 02:54:11 +000082 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
Sanjoy Das088bb0e2015-10-06 21:44:39 +000083
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000084 bool eliminateOverflowIntrinsic(CallInst *CI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000085 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
86 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000087 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
88 bool IsSigned);
89 void replaceRemWithNumerator(BinaryOperator *Rem);
90 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
91 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000092 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000093 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000094 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Philip Reames357cd322017-10-31 22:56:16 +000095
96
97 private:
98 // Wrapped around ScalarEvolution::isLoopInvariantPredicate which returns
99 // true only when a free expansion is available.
100 bool isCheapLoopInvariantPredicate(ICmpInst::Predicate Pred,
101 const SCEV *LHS, const SCEV *RHS, const Loop *L,
102 const SmallDenseMap<const SCEV*, Value*> &FreeExpansions,
103 ICmpInst::Predicate &InvariantPred,
104 Value *&LHSV, Value *& RHSV);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000105 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000106}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000107
Sanjay Patel7777b502014-11-12 18:07:42 +0000108/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +0000109/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +0000110///
Andrew Trick7251e412011-09-19 17:54:39 +0000111/// IVOperand is guaranteed SCEVable, but UseInst may not be.
112///
Andrew Trick74664d52011-08-10 04:01:31 +0000113/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000114/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000115/// Otherwise return null.
116Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000117 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000118 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000119 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000120 switch (UseInst->getOpcode()) {
121 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000122 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000123 case Instruction::UDiv:
124 case Instruction::LShr:
125 // We're only interested in the case where we know something about
126 // the numerator and have a constant denominator.
127 if (IVOperand != UseInst->getOperand(OperIdx) ||
128 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000129 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000130
131 // Attempt to fold a binary operator with constant operand.
132 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000133 if (!isa<BinaryOperator>(IVOperand)
134 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136
137 IVSrc = IVOperand->getOperand(0);
138 // IVSrc must be the (SCEVable) IV, since the other operand is const.
139 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
140
141 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
142 if (UseInst->getOpcode() == Instruction::LShr) {
143 // Get a constant for the divisor. See createSCEV.
144 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
145 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000146 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000147
148 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000149 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000150 }
151 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
152 }
153 // We have something that might fold it's operand. Compare SCEVs.
154 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000155 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000156
157 // Bypass the operand if SCEV can prove it has no effect.
158 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000159 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000160
161 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
162 << " -> " << *UseInst << '\n');
163
164 UseInst->setOperand(OperIdx, IVSrc);
165 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
166
167 ++NumElimOperand;
168 Changed = true;
169 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000170 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000171 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000172}
173
Philip Reamesdc417a92017-10-31 18:04:57 +0000174bool SimplifyIndvar::isCheapLoopInvariantPredicate(ICmpInst::Predicate Pred,
175 const SCEV *LHS, const SCEV *RHS, const Loop *L,
176 const SmallDenseMap<const SCEV*, Value*> &FreeExpansions,
177 ICmpInst::Predicate &InvariantPred,
178 Value *&LHSV, Value *& RHSV) {
179
180 const SCEV *InvariantLHS, *InvariantRHS;
181 if (!SE->isLoopInvariantPredicate(Pred, LHS, RHS, L, InvariantPred,
182 InvariantLHS, InvariantRHS))
183 return false;
184
185 // Rewrite the comparison to a loop invariant comparison if it can be done
186 // cheaply, where cheaply means "we don't need to emit any new
187 // instructions".
188 LHSV = FreeExpansions.lookup(InvariantLHS);
189 RHSV = FreeExpansions.lookup(InvariantRHS);
190
191 return (LHSV && RHSV);
192}
193
Sanjay Patel7777b502014-11-12 18:07:42 +0000194/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000195/// comparisons against an induction variable.
196void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
197 unsigned IVOperIdx = 0;
198 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000199 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000200 if (IVOperand != ICmp->getOperand(0)) {
201 // Swapped
202 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
203 IVOperIdx = 1;
204 Pred = ICmpInst::getSwappedPredicate(Pred);
205 }
206
Philip Reames29dd40b2017-10-26 22:02:16 +0000207 // Get the SCEVs for the ICmp operands (in the specific context of the
208 // current loop)
Andrew Trick3ec331e2011-08-10 03:46:27 +0000209 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
Philip Reames29dd40b2017-10-26 22:02:16 +0000210 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
211 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000212
Philip Reames357cd322017-10-31 22:56:16 +0000213 SmallDenseMap<const SCEV*, Value*> CheapExpansions;
214 CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
215 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
216
217 // TODO: Support multiple entry loops? (We currently bail out of these in
218 // the IndVarSimplify pass)
219 auto *PN = dyn_cast<PHINode>(IVOperand);
220 if (PN)
221 if (auto *BB = L->getLoopPredecessor()) {
222 Value *Incoming = PN->getIncomingValueForBlock(BB);
223 const SCEV *IncomingS = SE->getSCEV(Incoming);
224 CheapExpansions[IncomingS] = Incoming;
225 }
226
227 ICmpInst::Predicate NewPred;
228 Value *NewLHS = nullptr, *NewRHS = nullptr;
229
Andrew Trick3ec331e2011-08-10 03:46:27 +0000230 // If the condition is always true or always false, replace it with
231 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000232 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000233 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000234 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000235 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000236 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000237 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000238 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000239 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Philip Reames357cd322017-10-31 22:56:16 +0000240 } else if (PN &&
241 isCheapLoopInvariantPredicate(Pred, S, X, L, CheapExpansions,
242 NewPred, NewLHS, NewRHS)) {
243 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
244 ICmp->setPredicate(NewPred);
245 assert(NewLHS && NewRHS);
246 ICmp->setOperand(0, NewLHS);
247 ICmp->setOperand(1, NewRHS);
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000248 } else if (ICmpInst::isSigned(OriginalPred) &&
249 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
250 // If we were unable to make anything above, all we can is to canonicalize
251 // the comparison hoping that it will open the doors for other
252 // optimizations. If we find out that we compare two non-negative values,
253 // we turn the instruction's predicate to its unsigned version. Note that
254 // we cannot rely on Pred here unless we check if we have swapped it.
255 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
256 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
257 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000258 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000259 return;
260
Andrew Trick3ec331e2011-08-10 03:46:27 +0000261 ++NumElimCmp;
262 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000263}
264
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000265bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
266 // Get the SCEVs for the ICmp operands.
267 auto *N = SE->getSCEV(SDiv->getOperand(0));
268 auto *D = SE->getSCEV(SDiv->getOperand(1));
269
270 // Simplify unnecessary loops away.
271 const Loop *L = LI->getLoopFor(SDiv->getParent());
272 N = SE->getSCEVAtScope(N, L);
273 D = SE->getSCEVAtScope(D, L);
274
275 // Replace sdiv by udiv if both of the operands are non-negative
276 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
277 auto *UDiv = BinaryOperator::Create(
278 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
279 SDiv->getName() + ".udiv", SDiv);
280 UDiv->setIsExact(SDiv->isExact());
281 SDiv->replaceAllUsesWith(UDiv);
282 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
283 ++NumSimplifiedSDiv;
284 Changed = true;
285 DeadInsts.push_back(SDiv);
286 return true;
287 }
288
289 return false;
290}
291
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000292// i %s n -> i %u n if i >= 0 and n >= 0
293void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
294 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
295 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
296 Rem->getName() + ".urem", Rem);
297 Rem->replaceAllUsesWith(URem);
298 DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
299 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000300 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000301 DeadInsts.emplace_back(Rem);
302}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000303
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000304// i % n --> i if i is in [0,n).
305void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
306 Rem->replaceAllUsesWith(Rem->getOperand(0));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000307 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
308 ++NumElimRem;
309 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000310 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000311}
312
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000313// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
314void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
315 auto *T = Rem->getType();
316 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
317 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
318 SelectInst *Sel =
319 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
320 Rem->replaceAllUsesWith(Sel);
321 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
322 ++NumElimRem;
323 Changed = true;
324 DeadInsts.emplace_back(Rem);
325}
326
327/// SimplifyIVUsers helper for eliminating useless remainder operations
328/// operating on an induction variable or replacing srem by urem.
329void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
330 bool IsSigned) {
331 auto *NValue = Rem->getOperand(0);
332 auto *DValue = Rem->getOperand(1);
333 // We're only interested in the case where we know something about
334 // the numerator, unless it is a srem, because we want to replace srem by urem
335 // in general.
336 bool UsedAsNumerator = IVOperand == NValue;
337 if (!UsedAsNumerator && !IsSigned)
338 return;
339
340 const SCEV *N = SE->getSCEV(NValue);
341
342 // Simplify unnecessary loops away.
343 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
344 N = SE->getSCEVAtScope(N, ICmpLoop);
345
346 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
347
348 // Do not proceed if the Numerator may be negative
349 if (!IsNumeratorNonNegative)
350 return;
351
352 const SCEV *D = SE->getSCEV(DValue);
353 D = SE->getSCEVAtScope(D, ICmpLoop);
354
355 if (UsedAsNumerator) {
356 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
357 if (SE->isKnownPredicate(LT, N, D)) {
358 replaceRemWithNumerator(Rem);
359 return;
360 }
361
362 auto *T = Rem->getType();
363 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
364 if (SE->isKnownPredicate(LT, NLessOne, D)) {
365 replaceRemWithNumeratorOrZero(Rem);
366 return;
367 }
368 }
369
370 // Try to replace SRem with URem, if both N and D are known non-negative.
371 // Since we had already check N, we only need to check D now
372 if (!IsSigned || !SE->isKnownNonNegative(D))
373 return;
374
375 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000376}
377
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000378bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
379 auto *F = CI->getCalledFunction();
380 if (!F)
381 return false;
382
383 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000384 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000385 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000386 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000387
388 OperationFunctionTy Operation;
389 ExtensionFunctionTy Extension;
390
391 Instruction::BinaryOps RawOp;
392
393 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
394 // have nuw.
395 bool NoSignedOverflow;
396
397 switch (F->getIntrinsicID()) {
398 default:
399 return false;
400
401 case Intrinsic::sadd_with_overflow:
402 Operation = &ScalarEvolution::getAddExpr;
403 Extension = &ScalarEvolution::getSignExtendExpr;
404 RawOp = Instruction::Add;
405 NoSignedOverflow = true;
406 break;
407
408 case Intrinsic::uadd_with_overflow:
409 Operation = &ScalarEvolution::getAddExpr;
410 Extension = &ScalarEvolution::getZeroExtendExpr;
411 RawOp = Instruction::Add;
412 NoSignedOverflow = false;
413 break;
414
415 case Intrinsic::ssub_with_overflow:
416 Operation = &ScalarEvolution::getMinusSCEV;
417 Extension = &ScalarEvolution::getSignExtendExpr;
418 RawOp = Instruction::Sub;
419 NoSignedOverflow = true;
420 break;
421
422 case Intrinsic::usub_with_overflow:
423 Operation = &ScalarEvolution::getMinusSCEV;
424 Extension = &ScalarEvolution::getZeroExtendExpr;
425 RawOp = Instruction::Sub;
426 NoSignedOverflow = false;
427 break;
428 }
429
430 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
431 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
432
433 auto *NarrowTy = cast<IntegerType>(LHS->getType());
434 auto *WideTy =
435 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
436
437 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000438 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
439 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000440 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000441 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
442 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000443
444 if (A != B)
445 return false;
446
447 // Proved no overflow, nuke the overflow check and, if possible, the overflow
448 // intrinsic as well.
449
450 BinaryOperator *NewResult = BinaryOperator::Create(
451 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
452
453 if (NoSignedOverflow)
454 NewResult->setHasNoSignedWrap(true);
455 else
456 NewResult->setHasNoUnsignedWrap(true);
457
458 SmallVector<ExtractValueInst *, 4> ToDelete;
459
460 for (auto *U : CI->users()) {
461 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
462 if (EVI->getIndices()[0] == 1)
463 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
464 else {
465 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
466 EVI->replaceAllUsesWith(NewResult);
467 }
468 ToDelete.push_back(EVI);
469 }
470 }
471
472 for (auto *EVI : ToDelete)
473 EVI->eraseFromParent();
474
475 if (CI->use_empty())
476 CI->eraseFromParent();
477
478 return true;
479}
480
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000481/// Eliminate an operation that consumes a simple IV and has no observable
482/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
483/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000484bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
485 Instruction *IVOperand) {
486 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
487 eliminateIVComparison(ICmp, IVOperand);
488 return true;
489 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000490 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
491 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
492 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000493 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000494 return true;
495 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000496
497 if (Bin->getOpcode() == Instruction::SDiv)
498 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000499 }
500
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000501 if (auto *CI = dyn_cast<CallInst>(UseInst))
502 if (eliminateOverflowIntrinsic(CI))
503 return true;
504
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000505 if (eliminateIdentitySCEV(UseInst, IVOperand))
506 return true;
507
508 return false;
509}
510
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000511static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
512 if (auto *BB = L->getLoopPreheader())
513 return BB->getTerminator();
514
515 return Hint;
516}
517
518/// Replace the UseInst with a constant if possible.
519bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000520 if (!SE->isSCEVable(I->getType()))
521 return false;
522
523 // Get the symbolic expression for this instruction.
524 const SCEV *S = SE->getSCEV(I);
525
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000526 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000527 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000528
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000529 // Do not generate something ridiculous even if S is loop invariant.
530 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000531 return false;
532
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000533 auto *IP = GetLoopInvariantInsertPosition(L, I);
534 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
535
536 I->replaceAllUsesWith(Invariant);
537 DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
538 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000539 ++NumFoldedUser;
540 Changed = true;
541 DeadInsts.emplace_back(I);
542 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000543}
544
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000545/// Eliminate any operation that SCEV can prove is an identity function.
546bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
547 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000548 if (!SE->isSCEVable(UseInst->getType()) ||
549 (UseInst->getType() != IVOperand->getType()) ||
550 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
551 return false;
552
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000553 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
554 // dominator tree, even if X is an operand to Y. For instance, in
555 //
556 // %iv = phi i32 {0,+,1}
557 // br %cond, label %left, label %merge
558 //
559 // left:
560 // %X = add i32 %iv, 0
561 // br label %merge
562 //
563 // merge:
564 // %M = phi (%X, %iv)
565 //
566 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
567 // %M.replaceAllUsesWith(%X) would be incorrect.
568
569 if (isa<PHINode>(UseInst))
570 // If UseInst is not a PHI node then we know that IVOperand dominates
571 // UseInst directly from the legality of SSA.
572 if (!DT || !DT->dominates(IVOperand, UseInst))
573 return false;
574
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000575 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
576 return false;
577
Andrew Trick3ec331e2011-08-10 03:46:27 +0000578 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
579
580 UseInst->replaceAllUsesWith(IVOperand);
581 ++NumElimIdentity;
582 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000583 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000584 return true;
585}
586
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000587/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
588/// unsigned-overflow. Returns true if anything changed, false otherwise.
589bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
590 Value *IVOperand) {
591
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000592 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000593 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
594 return false;
595
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000596 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000597 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000598 switch (BO->getOpcode()) {
599 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000600 return false;
601
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000602 case Instruction::Add:
603 GetExprForBO = &ScalarEvolution::getAddExpr;
604 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000605
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000606 case Instruction::Sub:
607 GetExprForBO = &ScalarEvolution::getMinusSCEV;
608 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000609
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000610 case Instruction::Mul:
611 GetExprForBO = &ScalarEvolution::getMulExpr;
612 break;
613 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000614
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000615 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
616 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
617 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
618 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000619
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000620 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000621
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000622 if (!BO->hasNoUnsignedWrap()) {
623 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
624 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
625 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000626 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000627 if (ExtendAfterOp == OpAfterExtend) {
628 BO->setHasNoUnsignedWrap();
629 SE->forgetValue(BO);
630 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000631 }
632 }
633
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000634 if (!BO->hasNoSignedWrap()) {
635 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
636 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
637 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000638 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000639 if (ExtendAfterOp == OpAfterExtend) {
640 BO->setHasNoSignedWrap();
641 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000642 Changed = true;
643 }
644 }
645
646 return Changed;
647}
648
David Greenb26a0a42017-07-05 13:25:58 +0000649/// Annotate the Shr in (X << IVOperand) >> C as exact using the
650/// information from the IV's range. Returns true if anything changed, false
651/// otherwise.
652bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
653 Value *IVOperand) {
654 using namespace llvm::PatternMatch;
655
656 if (BO->getOpcode() == Instruction::Shl) {
657 bool Changed = false;
658 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
659 for (auto *U : BO->users()) {
660 const APInt *C;
661 if (match(U,
662 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
663 match(U,
664 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
665 BinaryOperator *Shr = cast<BinaryOperator>(U);
666 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
667 Shr->setIsExact(true);
668 Changed = true;
669 }
670 }
671 }
672 return Changed;
673 }
674
675 return false;
676}
677
Sanjay Patel7777b502014-11-12 18:07:42 +0000678/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000679static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000680 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000681 SmallPtrSet<Instruction*,16> &Simplified,
682 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
683
Chandler Carruthcdf47882014-03-09 03:16:01 +0000684 for (User *U : Def->users()) {
685 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000686
687 // Avoid infinite or exponential worklist processing.
688 // Also ensure unique worklist users.
689 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
690 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000691 if (UI == Def)
692 continue;
693
694 // Only change the current Loop, do not change the other parts (e.g. other
695 // Loops).
696 if (!L->contains(UI))
697 continue;
698
699 // Do not push the same instruction more than once.
700 if (!Simplified.insert(UI).second)
701 continue;
702
703 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000704 }
705}
706
Sanjay Patel7777b502014-11-12 18:07:42 +0000707/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000708/// expression in terms of that IV.
709///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000710/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000711/// non-recursively when the operand is already known to be a simpleIVUser.
712///
713static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
714 if (!SE->isSCEVable(I->getType()))
715 return false;
716
717 // Get the symbolic expression for this instruction.
718 const SCEV *S = SE->getSCEV(I);
719
720 // Only consider affine recurrences.
721 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
722 if (AR && AR->getLoop() == L)
723 return true;
724
725 return false;
726}
727
Sanjay Patel7777b502014-11-12 18:07:42 +0000728/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000729/// of the specified induction variable. Each successive simplification may push
730/// more users which may themselves be candidates for simplification.
731///
732/// This algorithm does not require IVUsers analysis. Instead, it simplifies
733/// instructions in-place during analysis. Rather than rewriting induction
734/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000735/// top-down, updating the IR only when it encounters a clear optimization
736/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000737///
738/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
739///
740void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000741 if (!SE->isSCEVable(CurrIV->getType()))
742 return;
743
Andrew Trick3ec331e2011-08-10 03:46:27 +0000744 // Instructions processed by SimplifyIndvar for CurrIV.
745 SmallPtrSet<Instruction*,16> Simplified;
746
747 // Use-def pairs if IV users waiting to be processed for CurrIV.
748 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
749
750 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
751 // called multiple times for the same LoopPhi. This is the proper thing to
752 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000753 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000754
755 while (!SimpleIVUsers.empty()) {
756 std::pair<Instruction*, Instruction*> UseOper =
757 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000758 Instruction *UseInst = UseOper.first;
759
Andrew Trick3ec331e2011-08-10 03:46:27 +0000760 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000761 if (UseInst == CurrIV) continue;
762
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000763 // Try to replace UseInst with a loop invariant before any other
764 // simplifications.
765 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000766 continue;
767
Andrew Trick74664d52011-08-10 04:01:31 +0000768 Instruction *IVOperand = UseOper.second;
769 for (unsigned N = 0; IVOperand; ++N) {
770 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000771
Andrew Trick74664d52011-08-10 04:01:31 +0000772 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
773 if (!NewOper)
774 break; // done folding
775 IVOperand = dyn_cast<Instruction>(NewOper);
776 }
777 if (!IVOperand)
778 continue;
779
780 if (eliminateIVUser(UseOper.first, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000781 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000782 continue;
783 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000784
785 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000786 if ((isa<OverflowingBinaryOperator>(BO) &&
787 strengthenOverflowingOperation(BO, IVOperand)) ||
788 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000789 // re-queue uses of the now modified binary operator and fall
790 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000791 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000792 }
793 }
794
Andrew Trick3ec331e2011-08-10 03:46:27 +0000795 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
796 if (V && Cast) {
797 V->visitCast(Cast);
798 continue;
799 }
800 if (isSimpleIVUser(UseOper.first, L, SE)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000801 pushIVUsers(UseOper.first, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000802 }
803 }
804}
805
806namespace llvm {
807
David Blaikiea379b1812011-12-20 02:50:00 +0000808void IVVisitor::anchor() { }
809
Sanjay Patel7777b502014-11-12 18:07:42 +0000810/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000811/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000812bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000813 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000814 SCEVExpander &Rewriter, IVVisitor *V) {
815 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
816 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000817 SIV.simplifyUsers(CurrIV, V);
818 return SIV.hasChanged();
819}
820
Sanjay Patel7777b502014-11-12 18:07:42 +0000821/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000822/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000823bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000824 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000825 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
826#ifndef NDEBUG
827 Rewriter.setDebugType(DEBUG_TYPE);
828#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000829 bool Changed = false;
830 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000831 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000832 }
833 return Changed;
834}
835
Andrew Trick3ec331e2011-08-10 03:46:27 +0000836} // namespace llvm