blob: 08b84927c674d509ec81c2fa027b484294e9e0ab [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);
Andrew Trick3ec331e2011-08-10 03:46:27 +000095 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000096}
Andrew Trick3ec331e2011-08-10 03:46:27 +000097
Sanjay Patel7777b502014-11-12 18:07:42 +000098/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000099/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +0000100///
Andrew Trick7251e412011-09-19 17:54:39 +0000101/// IVOperand is guaranteed SCEVable, but UseInst may not be.
102///
Andrew Trick74664d52011-08-10 04:01:31 +0000103/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000104/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000105/// Otherwise return null.
106Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000107 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000108 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000109 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000110 switch (UseInst->getOpcode()) {
111 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000113 case Instruction::UDiv:
114 case Instruction::LShr:
115 // We're only interested in the case where we know something about
116 // the numerator and have a constant denominator.
117 if (IVOperand != UseInst->getOperand(OperIdx) ||
118 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000120
121 // Attempt to fold a binary operator with constant operand.
122 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000123 if (!isa<BinaryOperator>(IVOperand)
124 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000125 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000126
127 IVSrc = IVOperand->getOperand(0);
128 // IVSrc must be the (SCEVable) IV, since the other operand is const.
129 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
130
131 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
132 if (UseInst->getOpcode() == Instruction::LShr) {
133 // Get a constant for the divisor. See createSCEV.
134 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
135 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000137
138 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000139 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000140 }
141 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
142 }
143 // We have something that might fold it's operand. Compare SCEVs.
144 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000145 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000146
147 // Bypass the operand if SCEV can prove it has no effect.
148 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000149 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000150
151 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
152 << " -> " << *UseInst << '\n');
153
154 UseInst->setOperand(OperIdx, IVSrc);
155 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
156
157 ++NumElimOperand;
158 Changed = true;
159 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000160 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000161 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000162}
163
Sanjay Patel7777b502014-11-12 18:07:42 +0000164/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000165/// comparisons against an induction variable.
166void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
167 unsigned IVOperIdx = 0;
168 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000169 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000170 if (IVOperand != ICmp->getOperand(0)) {
171 // Swapped
172 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
173 IVOperIdx = 1;
174 Pred = ICmpInst::getSwappedPredicate(Pred);
175 }
176
177 // Get the SCEVs for the ICmp operands.
178 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
179 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
180
181 // Simplify unnecessary loops away.
182 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
183 S = SE->getSCEVAtScope(S, ICmpLoop);
184 X = SE->getSCEVAtScope(X, ICmpLoop);
185
Sanjoy Das5dab2052015-07-27 21:42:49 +0000186 ICmpInst::Predicate InvariantPredicate;
187 const SCEV *InvariantLHS, *InvariantRHS;
188
Andrew Trick3ec331e2011-08-10 03:46:27 +0000189 // If the condition is always true or always false, replace it with
190 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000191 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000192 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000193 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000194 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000195 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000196 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000197 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000198 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000199 } else if (isa<PHINode>(IVOperand) &&
Sanjoy Das60fb8992016-03-18 20:37:07 +0000200 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
201 InvariantLHS, InvariantRHS)) {
Sanjoy Das5dab2052015-07-27 21:42:49 +0000202
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000203 // Rewrite the comparison to a loop invariant comparison if it can be done
Sanjoy Das5dab2052015-07-27 21:42:49 +0000204 // cheaply, where cheaply means "we don't need to emit any new
205 // instructions".
206
207 Value *NewLHS = nullptr, *NewRHS = nullptr;
208
209 if (S == InvariantLHS || X == InvariantLHS)
210 NewLHS =
211 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
212
213 if (S == InvariantRHS || X == InvariantRHS)
214 NewRHS =
215 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
216
Sanjoy Das74af78e32016-03-18 20:37:11 +0000217 auto *PN = cast<PHINode>(IVOperand);
218 for (unsigned i = 0, e = PN->getNumIncomingValues();
219 i != e && (!NewLHS || !NewRHS);
220 ++i) {
221
222 // If this is a value incoming from the backedge, then it cannot be a loop
223 // invariant value (since we know that IVOperand is an induction variable).
224 if (L->contains(PN->getIncomingBlock(i)))
225 continue;
226
227 // NB! This following assert does not fundamentally have to be true, but
228 // it is true today given how SCEV analyzes induction variables.
229 // Specifically, today SCEV will *not* recognize %iv as an induction
230 // variable in the following case:
231 //
232 // define void @f(i32 %k) {
233 // entry:
234 // br i1 undef, label %r, label %l
235 //
236 // l:
237 // %k.inc.l = add i32 %k, 1
238 // br label %loop
239 //
240 // r:
241 // %k.inc.r = add i32 %k, 1
242 // br label %loop
243 //
244 // loop:
245 // %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
246 // %iv.inc = add i32 %iv, 1
247 // br label %loop
248 // }
249 //
250 // but if it starts to, at some point, then the assertion below will have
251 // to be changed to a runtime check.
252
253 Value *Incoming = PN->getIncomingValue(i);
254
255#ifndef NDEBUG
256 if (auto *I = dyn_cast<Instruction>(Incoming))
257 assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
258#endif
Sanjoy Das5dab2052015-07-27 21:42:49 +0000259
260 const SCEV *IncomingS = SE->getSCEV(Incoming);
261
262 if (!NewLHS && IncomingS == InvariantLHS)
263 NewLHS = Incoming;
264 if (!NewRHS && IncomingS == InvariantRHS)
265 NewRHS = Incoming;
266 }
267
268 if (!NewLHS || !NewRHS)
269 // We could not find an existing value to replace either LHS or RHS.
270 // Generating new instructions has subtler tradeoffs, so avoid doing that
271 // for now.
272 return;
273
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000274 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000275 ICmp->setPredicate(InvariantPredicate);
276 ICmp->setOperand(0, NewLHS);
277 ICmp->setOperand(1, NewRHS);
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000278 } else if (ICmpInst::isSigned(OriginalPred) &&
279 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
280 // If we were unable to make anything above, all we can is to canonicalize
281 // the comparison hoping that it will open the doors for other
282 // optimizations. If we find out that we compare two non-negative values,
283 // we turn the instruction's predicate to its unsigned version. Note that
284 // we cannot rely on Pred here unless we check if we have swapped it.
285 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
286 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
287 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000288 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000289 return;
290
Andrew Trick3ec331e2011-08-10 03:46:27 +0000291 ++NumElimCmp;
292 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000293}
294
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000295bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
296 // Get the SCEVs for the ICmp operands.
297 auto *N = SE->getSCEV(SDiv->getOperand(0));
298 auto *D = SE->getSCEV(SDiv->getOperand(1));
299
300 // Simplify unnecessary loops away.
301 const Loop *L = LI->getLoopFor(SDiv->getParent());
302 N = SE->getSCEVAtScope(N, L);
303 D = SE->getSCEVAtScope(D, L);
304
305 // Replace sdiv by udiv if both of the operands are non-negative
306 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
307 auto *UDiv = BinaryOperator::Create(
308 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
309 SDiv->getName() + ".udiv", SDiv);
310 UDiv->setIsExact(SDiv->isExact());
311 SDiv->replaceAllUsesWith(UDiv);
312 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
313 ++NumSimplifiedSDiv;
314 Changed = true;
315 DeadInsts.push_back(SDiv);
316 return true;
317 }
318
319 return false;
320}
321
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000322// i %s n -> i %u n if i >= 0 and n >= 0
323void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
324 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
325 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
326 Rem->getName() + ".urem", Rem);
327 Rem->replaceAllUsesWith(URem);
328 DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
329 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000330 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000331 DeadInsts.emplace_back(Rem);
332}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000333
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000334// i % n --> i if i is in [0,n).
335void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
336 Rem->replaceAllUsesWith(Rem->getOperand(0));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000337 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
338 ++NumElimRem;
339 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000340 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000341}
342
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000343// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
344void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
345 auto *T = Rem->getType();
346 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
347 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
348 SelectInst *Sel =
349 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
350 Rem->replaceAllUsesWith(Sel);
351 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
352 ++NumElimRem;
353 Changed = true;
354 DeadInsts.emplace_back(Rem);
355}
356
357/// SimplifyIVUsers helper for eliminating useless remainder operations
358/// operating on an induction variable or replacing srem by urem.
359void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
360 bool IsSigned) {
361 auto *NValue = Rem->getOperand(0);
362 auto *DValue = Rem->getOperand(1);
363 // We're only interested in the case where we know something about
364 // the numerator, unless it is a srem, because we want to replace srem by urem
365 // in general.
366 bool UsedAsNumerator = IVOperand == NValue;
367 if (!UsedAsNumerator && !IsSigned)
368 return;
369
370 const SCEV *N = SE->getSCEV(NValue);
371
372 // Simplify unnecessary loops away.
373 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
374 N = SE->getSCEVAtScope(N, ICmpLoop);
375
376 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
377
378 // Do not proceed if the Numerator may be negative
379 if (!IsNumeratorNonNegative)
380 return;
381
382 const SCEV *D = SE->getSCEV(DValue);
383 D = SE->getSCEVAtScope(D, ICmpLoop);
384
385 if (UsedAsNumerator) {
386 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
387 if (SE->isKnownPredicate(LT, N, D)) {
388 replaceRemWithNumerator(Rem);
389 return;
390 }
391
392 auto *T = Rem->getType();
393 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
394 if (SE->isKnownPredicate(LT, NLessOne, D)) {
395 replaceRemWithNumeratorOrZero(Rem);
396 return;
397 }
398 }
399
400 // Try to replace SRem with URem, if both N and D are known non-negative.
401 // Since we had already check N, we only need to check D now
402 if (!IsSigned || !SE->isKnownNonNegative(D))
403 return;
404
405 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000406}
407
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000408bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
409 auto *F = CI->getCalledFunction();
410 if (!F)
411 return false;
412
413 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000414 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000415 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000416 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000417
418 OperationFunctionTy Operation;
419 ExtensionFunctionTy Extension;
420
421 Instruction::BinaryOps RawOp;
422
423 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
424 // have nuw.
425 bool NoSignedOverflow;
426
427 switch (F->getIntrinsicID()) {
428 default:
429 return false;
430
431 case Intrinsic::sadd_with_overflow:
432 Operation = &ScalarEvolution::getAddExpr;
433 Extension = &ScalarEvolution::getSignExtendExpr;
434 RawOp = Instruction::Add;
435 NoSignedOverflow = true;
436 break;
437
438 case Intrinsic::uadd_with_overflow:
439 Operation = &ScalarEvolution::getAddExpr;
440 Extension = &ScalarEvolution::getZeroExtendExpr;
441 RawOp = Instruction::Add;
442 NoSignedOverflow = false;
443 break;
444
445 case Intrinsic::ssub_with_overflow:
446 Operation = &ScalarEvolution::getMinusSCEV;
447 Extension = &ScalarEvolution::getSignExtendExpr;
448 RawOp = Instruction::Sub;
449 NoSignedOverflow = true;
450 break;
451
452 case Intrinsic::usub_with_overflow:
453 Operation = &ScalarEvolution::getMinusSCEV;
454 Extension = &ScalarEvolution::getZeroExtendExpr;
455 RawOp = Instruction::Sub;
456 NoSignedOverflow = false;
457 break;
458 }
459
460 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
461 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
462
463 auto *NarrowTy = cast<IntegerType>(LHS->getType());
464 auto *WideTy =
465 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
466
467 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000468 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
469 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000470 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000471 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
472 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000473
474 if (A != B)
475 return false;
476
477 // Proved no overflow, nuke the overflow check and, if possible, the overflow
478 // intrinsic as well.
479
480 BinaryOperator *NewResult = BinaryOperator::Create(
481 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
482
483 if (NoSignedOverflow)
484 NewResult->setHasNoSignedWrap(true);
485 else
486 NewResult->setHasNoUnsignedWrap(true);
487
488 SmallVector<ExtractValueInst *, 4> ToDelete;
489
490 for (auto *U : CI->users()) {
491 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
492 if (EVI->getIndices()[0] == 1)
493 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
494 else {
495 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
496 EVI->replaceAllUsesWith(NewResult);
497 }
498 ToDelete.push_back(EVI);
499 }
500 }
501
502 for (auto *EVI : ToDelete)
503 EVI->eraseFromParent();
504
505 if (CI->use_empty())
506 CI->eraseFromParent();
507
508 return true;
509}
510
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000511/// Eliminate an operation that consumes a simple IV and has no observable
512/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
513/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000514bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
515 Instruction *IVOperand) {
516 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
517 eliminateIVComparison(ICmp, IVOperand);
518 return true;
519 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000520 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
521 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
522 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000523 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000524 return true;
525 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000526
527 if (Bin->getOpcode() == Instruction::SDiv)
528 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000529 }
530
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000531 if (auto *CI = dyn_cast<CallInst>(UseInst))
532 if (eliminateOverflowIntrinsic(CI))
533 return true;
534
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000535 if (eliminateIdentitySCEV(UseInst, IVOperand))
536 return true;
537
538 return false;
539}
540
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000541static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
542 if (auto *BB = L->getLoopPreheader())
543 return BB->getTerminator();
544
545 return Hint;
546}
547
548/// Replace the UseInst with a constant if possible.
549bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000550 if (!SE->isSCEVable(I->getType()))
551 return false;
552
553 // Get the symbolic expression for this instruction.
554 const SCEV *S = SE->getSCEV(I);
555
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000556 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000557 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000558
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000559 // Do not generate something ridiculous even if S is loop invariant.
560 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000561 return false;
562
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000563 auto *IP = GetLoopInvariantInsertPosition(L, I);
564 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
565
566 I->replaceAllUsesWith(Invariant);
567 DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
568 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000569 ++NumFoldedUser;
570 Changed = true;
571 DeadInsts.emplace_back(I);
572 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000573}
574
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000575/// Eliminate any operation that SCEV can prove is an identity function.
576bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
577 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000578 if (!SE->isSCEVable(UseInst->getType()) ||
579 (UseInst->getType() != IVOperand->getType()) ||
580 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
581 return false;
582
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000583 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
584 // dominator tree, even if X is an operand to Y. For instance, in
585 //
586 // %iv = phi i32 {0,+,1}
587 // br %cond, label %left, label %merge
588 //
589 // left:
590 // %X = add i32 %iv, 0
591 // br label %merge
592 //
593 // merge:
594 // %M = phi (%X, %iv)
595 //
596 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
597 // %M.replaceAllUsesWith(%X) would be incorrect.
598
599 if (isa<PHINode>(UseInst))
600 // If UseInst is not a PHI node then we know that IVOperand dominates
601 // UseInst directly from the legality of SSA.
602 if (!DT || !DT->dominates(IVOperand, UseInst))
603 return false;
604
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000605 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
606 return false;
607
Andrew Trick3ec331e2011-08-10 03:46:27 +0000608 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
609
610 UseInst->replaceAllUsesWith(IVOperand);
611 ++NumElimIdentity;
612 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000613 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000614 return true;
615}
616
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000617/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
618/// unsigned-overflow. Returns true if anything changed, false otherwise.
619bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
620 Value *IVOperand) {
621
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000622 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000623 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
624 return false;
625
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000626 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000627 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000628 switch (BO->getOpcode()) {
629 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000630 return false;
631
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000632 case Instruction::Add:
633 GetExprForBO = &ScalarEvolution::getAddExpr;
634 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000635
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000636 case Instruction::Sub:
637 GetExprForBO = &ScalarEvolution::getMinusSCEV;
638 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000639
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000640 case Instruction::Mul:
641 GetExprForBO = &ScalarEvolution::getMulExpr;
642 break;
643 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000644
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000645 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
646 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
647 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
648 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000649
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000650 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000651
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000652 if (!BO->hasNoUnsignedWrap()) {
653 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
654 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
655 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000656 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000657 if (ExtendAfterOp == OpAfterExtend) {
658 BO->setHasNoUnsignedWrap();
659 SE->forgetValue(BO);
660 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000661 }
662 }
663
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000664 if (!BO->hasNoSignedWrap()) {
665 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
666 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
667 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000668 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000669 if (ExtendAfterOp == OpAfterExtend) {
670 BO->setHasNoSignedWrap();
671 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000672 Changed = true;
673 }
674 }
675
676 return Changed;
677}
678
David Greenb26a0a42017-07-05 13:25:58 +0000679/// Annotate the Shr in (X << IVOperand) >> C as exact using the
680/// information from the IV's range. Returns true if anything changed, false
681/// otherwise.
682bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
683 Value *IVOperand) {
684 using namespace llvm::PatternMatch;
685
686 if (BO->getOpcode() == Instruction::Shl) {
687 bool Changed = false;
688 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
689 for (auto *U : BO->users()) {
690 const APInt *C;
691 if (match(U,
692 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
693 match(U,
694 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
695 BinaryOperator *Shr = cast<BinaryOperator>(U);
696 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
697 Shr->setIsExact(true);
698 Changed = true;
699 }
700 }
701 }
702 return Changed;
703 }
704
705 return false;
706}
707
Sanjay Patel7777b502014-11-12 18:07:42 +0000708/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000709static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000710 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000711 SmallPtrSet<Instruction*,16> &Simplified,
712 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
713
Chandler Carruthcdf47882014-03-09 03:16:01 +0000714 for (User *U : Def->users()) {
715 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000716
717 // Avoid infinite or exponential worklist processing.
718 // Also ensure unique worklist users.
719 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
720 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000721 if (UI == Def)
722 continue;
723
724 // Only change the current Loop, do not change the other parts (e.g. other
725 // Loops).
726 if (!L->contains(UI))
727 continue;
728
729 // Do not push the same instruction more than once.
730 if (!Simplified.insert(UI).second)
731 continue;
732
733 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000734 }
735}
736
Sanjay Patel7777b502014-11-12 18:07:42 +0000737/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000738/// expression in terms of that IV.
739///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000740/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000741/// non-recursively when the operand is already known to be a simpleIVUser.
742///
743static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
744 if (!SE->isSCEVable(I->getType()))
745 return false;
746
747 // Get the symbolic expression for this instruction.
748 const SCEV *S = SE->getSCEV(I);
749
750 // Only consider affine recurrences.
751 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
752 if (AR && AR->getLoop() == L)
753 return true;
754
755 return false;
756}
757
Sanjay Patel7777b502014-11-12 18:07:42 +0000758/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000759/// of the specified induction variable. Each successive simplification may push
760/// more users which may themselves be candidates for simplification.
761///
762/// This algorithm does not require IVUsers analysis. Instead, it simplifies
763/// instructions in-place during analysis. Rather than rewriting induction
764/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000765/// top-down, updating the IR only when it encounters a clear optimization
766/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000767///
768/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
769///
770void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000771 if (!SE->isSCEVable(CurrIV->getType()))
772 return;
773
Andrew Trick3ec331e2011-08-10 03:46:27 +0000774 // Instructions processed by SimplifyIndvar for CurrIV.
775 SmallPtrSet<Instruction*,16> Simplified;
776
777 // Use-def pairs if IV users waiting to be processed for CurrIV.
778 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
779
780 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
781 // called multiple times for the same LoopPhi. This is the proper thing to
782 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000783 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000784
785 while (!SimpleIVUsers.empty()) {
786 std::pair<Instruction*, Instruction*> UseOper =
787 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000788 Instruction *UseInst = UseOper.first;
789
Andrew Trick3ec331e2011-08-10 03:46:27 +0000790 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000791 if (UseInst == CurrIV) continue;
792
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000793 // Try to replace UseInst with a loop invariant before any other
794 // simplifications.
795 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000796 continue;
797
Andrew Trick74664d52011-08-10 04:01:31 +0000798 Instruction *IVOperand = UseOper.second;
799 for (unsigned N = 0; IVOperand; ++N) {
800 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000801
Andrew Trick74664d52011-08-10 04:01:31 +0000802 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
803 if (!NewOper)
804 break; // done folding
805 IVOperand = dyn_cast<Instruction>(NewOper);
806 }
807 if (!IVOperand)
808 continue;
809
810 if (eliminateIVUser(UseOper.first, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000811 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000812 continue;
813 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000814
815 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000816 if ((isa<OverflowingBinaryOperator>(BO) &&
817 strengthenOverflowingOperation(BO, IVOperand)) ||
818 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000819 // re-queue uses of the now modified binary operator and fall
820 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000821 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000822 }
823 }
824
Andrew Trick3ec331e2011-08-10 03:46:27 +0000825 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
826 if (V && Cast) {
827 V->visitCast(Cast);
828 continue;
829 }
830 if (isSimpleIVUser(UseOper.first, L, SE)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000831 pushIVUsers(UseOper.first, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000832 }
833 }
834}
835
836namespace llvm {
837
David Blaikiea379b1812011-12-20 02:50:00 +0000838void IVVisitor::anchor() { }
839
Sanjay Patel7777b502014-11-12 18:07:42 +0000840/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000841/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000842bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000843 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000844 SCEVExpander &Rewriter, IVVisitor *V) {
845 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
846 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000847 SIV.simplifyUsers(CurrIV, V);
848 return SIV.hasChanged();
849}
850
Sanjay Patel7777b502014-11-12 18:07:42 +0000851/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000852/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000853bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000854 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000855 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
856#ifndef NDEBUG
857 Rewriter.setDebugType(DEBUG_TYPE);
858#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000859 bool Changed = false;
860 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000861 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000862 }
863 return Changed;
864}
865
Andrew Trick3ec331e2011-08-10 03:46:27 +0000866} // namespace llvm