blob: 96b51396c9b639a5c27441bee903d686337a572a [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);
Philip Reames7b861f02017-11-01 19:49:20 +000086 bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000087 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000088 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
89 bool IsSigned);
90 void replaceRemWithNumerator(BinaryOperator *Rem);
91 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
92 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000093 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000094 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000095 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000096 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000097}
Andrew Trick3ec331e2011-08-10 03:46:27 +000098
Sanjay Patel7777b502014-11-12 18:07:42 +000099/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +0000100/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +0000101///
Andrew Trick7251e412011-09-19 17:54:39 +0000102/// IVOperand is guaranteed SCEVable, but UseInst may not be.
103///
Andrew Trick74664d52011-08-10 04:01:31 +0000104/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000105/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000106/// Otherwise return null.
107Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000108 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000109 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000110 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000111 switch (UseInst->getOpcode()) {
112 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000113 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000114 case Instruction::UDiv:
115 case Instruction::LShr:
116 // We're only interested in the case where we know something about
117 // the numerator and have a constant denominator.
118 if (IVOperand != UseInst->getOperand(OperIdx) ||
119 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000120 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000121
122 // Attempt to fold a binary operator with constant operand.
123 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000124 if (!isa<BinaryOperator>(IVOperand)
125 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000126 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000127
128 IVSrc = IVOperand->getOperand(0);
129 // IVSrc must be the (SCEVable) IV, since the other operand is const.
130 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
131
132 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
133 if (UseInst->getOpcode() == Instruction::LShr) {
134 // Get a constant for the divisor. See createSCEV.
135 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
136 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000137 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000138
139 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000140 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000141 }
142 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
143 }
144 // We have something that might fold it's operand. Compare SCEVs.
145 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000146 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000147
148 // Bypass the operand if SCEV can prove it has no effect.
149 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000150 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000151
152 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
153 << " -> " << *UseInst << '\n');
154
155 UseInst->setOperand(OperIdx, IVSrc);
156 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
157
158 ++NumElimOperand;
159 Changed = true;
160 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000161 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000162 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000163}
164
Philip Reames7b861f02017-11-01 19:49:20 +0000165bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
166 Value *IVOperand) {
167 unsigned IVOperIdx = 0;
168 ICmpInst::Predicate Pred = ICmp->getPredicate();
169 if (IVOperand != ICmp->getOperand(0)) {
170 // Swapped
171 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
172 IVOperIdx = 1;
173 Pred = ICmpInst::getSwappedPredicate(Pred);
174 }
Philip Reamesdc417a92017-10-31 18:04:57 +0000175
Philip Reames7b861f02017-11-01 19:49:20 +0000176 // Get the SCEVs for the ICmp operands (in the specific context of the
177 // current loop)
178 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
179 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
180 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
181
182 ICmpInst::Predicate InvariantPredicate;
Philip Reamesdc417a92017-10-31 18:04:57 +0000183 const SCEV *InvariantLHS, *InvariantRHS;
Philip Reames7b861f02017-11-01 19:49:20 +0000184
185 auto *PN = dyn_cast<PHINode>(IVOperand);
186 if (!PN)
187 return false;
188 if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
Philip Reamesdc417a92017-10-31 18:04:57 +0000189 InvariantLHS, InvariantRHS))
190 return false;
191
192 // Rewrite the comparison to a loop invariant comparison if it can be done
193 // cheaply, where cheaply means "we don't need to emit any new
194 // instructions".
Philip Reamesdc417a92017-10-31 18:04:57 +0000195
Philip Reames7b861f02017-11-01 19:49:20 +0000196 SmallDenseMap<const SCEV*, Value*> CheapExpansions;
197 CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
198 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
199
200 // TODO: Support multiple entry loops? (We currently bail out of these in
201 // the IndVarSimplify pass)
202 if (auto *BB = L->getLoopPredecessor()) {
Philip Reames6260cf72017-12-01 20:57:19 +0000203 const int Idx = PN->getBasicBlockIndex(BB);
204 if (Idx >= 0) {
205 Value *Incoming = PN->getIncomingValue(Idx);
206 const SCEV *IncomingS = SE->getSCEV(Incoming);
207 CheapExpansions[IncomingS] = Incoming;
208 }
Philip Reames7b861f02017-11-01 19:49:20 +0000209 }
210 Value *NewLHS = CheapExpansions[InvariantLHS];
211 Value *NewRHS = CheapExpansions[InvariantRHS];
212
Philip Reames6260cf72017-12-01 20:57:19 +0000213 if (!NewLHS)
214 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
215 NewLHS = ConstLHS->getValue();
216 if (!NewRHS)
217 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
218 NewRHS = ConstRHS->getValue();
219
Philip Reames7b861f02017-11-01 19:49:20 +0000220 if (!NewLHS || !NewRHS)
221 // We could not find an existing value to replace either LHS or RHS.
222 // Generating new instructions has subtler tradeoffs, so avoid doing that
223 // for now.
224 return false;
225
226 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
227 ICmp->setPredicate(InvariantPredicate);
228 ICmp->setOperand(0, NewLHS);
229 ICmp->setOperand(1, NewRHS);
230 return true;
Philip Reamesdc417a92017-10-31 18:04:57 +0000231}
232
Sanjay Patel7777b502014-11-12 18:07:42 +0000233/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000234/// comparisons against an induction variable.
235void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
236 unsigned IVOperIdx = 0;
237 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000238 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000239 if (IVOperand != ICmp->getOperand(0)) {
240 // Swapped
241 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
242 IVOperIdx = 1;
243 Pred = ICmpInst::getSwappedPredicate(Pred);
244 }
245
Philip Reames29dd40b2017-10-26 22:02:16 +0000246 // Get the SCEVs for the ICmp operands (in the specific context of the
247 // current loop)
Andrew Trick3ec331e2011-08-10 03:46:27 +0000248 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
Philip Reames29dd40b2017-10-26 22:02:16 +0000249 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
250 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000251
252 // If the condition is always true or always false, replace it with
253 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000254 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000255 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000256 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000257 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000258 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000259 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000260 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000261 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000262 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
263 // fallthrough to end of function
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000264 } else if (ICmpInst::isSigned(OriginalPred) &&
265 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
266 // If we were unable to make anything above, all we can is to canonicalize
267 // the comparison hoping that it will open the doors for other
268 // optimizations. If we find out that we compare two non-negative values,
269 // we turn the instruction's predicate to its unsigned version. Note that
270 // we cannot rely on Pred here unless we check if we have swapped it.
271 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
272 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
273 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000274 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000275 return;
276
Andrew Trick3ec331e2011-08-10 03:46:27 +0000277 ++NumElimCmp;
278 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000279}
280
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000281bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
282 // Get the SCEVs for the ICmp operands.
283 auto *N = SE->getSCEV(SDiv->getOperand(0));
284 auto *D = SE->getSCEV(SDiv->getOperand(1));
285
286 // Simplify unnecessary loops away.
287 const Loop *L = LI->getLoopFor(SDiv->getParent());
288 N = SE->getSCEVAtScope(N, L);
289 D = SE->getSCEVAtScope(D, L);
290
291 // Replace sdiv by udiv if both of the operands are non-negative
292 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
293 auto *UDiv = BinaryOperator::Create(
294 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
295 SDiv->getName() + ".udiv", SDiv);
296 UDiv->setIsExact(SDiv->isExact());
297 SDiv->replaceAllUsesWith(UDiv);
298 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
299 ++NumSimplifiedSDiv;
300 Changed = true;
301 DeadInsts.push_back(SDiv);
302 return true;
303 }
304
305 return false;
306}
307
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000308// i %s n -> i %u n if i >= 0 and n >= 0
309void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
310 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
311 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
312 Rem->getName() + ".urem", Rem);
313 Rem->replaceAllUsesWith(URem);
314 DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
315 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000316 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000317 DeadInsts.emplace_back(Rem);
318}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000319
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000320// i % n --> i if i is in [0,n).
321void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
322 Rem->replaceAllUsesWith(Rem->getOperand(0));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000323 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
324 ++NumElimRem;
325 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000326 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000327}
328
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000329// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
330void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
331 auto *T = Rem->getType();
332 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
333 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
334 SelectInst *Sel =
335 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
336 Rem->replaceAllUsesWith(Sel);
337 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
338 ++NumElimRem;
339 Changed = true;
340 DeadInsts.emplace_back(Rem);
341}
342
343/// SimplifyIVUsers helper for eliminating useless remainder operations
344/// operating on an induction variable or replacing srem by urem.
345void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
346 bool IsSigned) {
347 auto *NValue = Rem->getOperand(0);
348 auto *DValue = Rem->getOperand(1);
349 // We're only interested in the case where we know something about
350 // the numerator, unless it is a srem, because we want to replace srem by urem
351 // in general.
352 bool UsedAsNumerator = IVOperand == NValue;
353 if (!UsedAsNumerator && !IsSigned)
354 return;
355
356 const SCEV *N = SE->getSCEV(NValue);
357
358 // Simplify unnecessary loops away.
359 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
360 N = SE->getSCEVAtScope(N, ICmpLoop);
361
362 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
363
364 // Do not proceed if the Numerator may be negative
365 if (!IsNumeratorNonNegative)
366 return;
367
368 const SCEV *D = SE->getSCEV(DValue);
369 D = SE->getSCEVAtScope(D, ICmpLoop);
370
371 if (UsedAsNumerator) {
372 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
373 if (SE->isKnownPredicate(LT, N, D)) {
374 replaceRemWithNumerator(Rem);
375 return;
376 }
377
378 auto *T = Rem->getType();
379 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
380 if (SE->isKnownPredicate(LT, NLessOne, D)) {
381 replaceRemWithNumeratorOrZero(Rem);
382 return;
383 }
384 }
385
386 // Try to replace SRem with URem, if both N and D are known non-negative.
387 // Since we had already check N, we only need to check D now
388 if (!IsSigned || !SE->isKnownNonNegative(D))
389 return;
390
391 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000392}
393
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000394bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
395 auto *F = CI->getCalledFunction();
396 if (!F)
397 return false;
398
399 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000400 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000401 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000402 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000403
404 OperationFunctionTy Operation;
405 ExtensionFunctionTy Extension;
406
407 Instruction::BinaryOps RawOp;
408
409 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
410 // have nuw.
411 bool NoSignedOverflow;
412
413 switch (F->getIntrinsicID()) {
414 default:
415 return false;
416
417 case Intrinsic::sadd_with_overflow:
418 Operation = &ScalarEvolution::getAddExpr;
419 Extension = &ScalarEvolution::getSignExtendExpr;
420 RawOp = Instruction::Add;
421 NoSignedOverflow = true;
422 break;
423
424 case Intrinsic::uadd_with_overflow:
425 Operation = &ScalarEvolution::getAddExpr;
426 Extension = &ScalarEvolution::getZeroExtendExpr;
427 RawOp = Instruction::Add;
428 NoSignedOverflow = false;
429 break;
430
431 case Intrinsic::ssub_with_overflow:
432 Operation = &ScalarEvolution::getMinusSCEV;
433 Extension = &ScalarEvolution::getSignExtendExpr;
434 RawOp = Instruction::Sub;
435 NoSignedOverflow = true;
436 break;
437
438 case Intrinsic::usub_with_overflow:
439 Operation = &ScalarEvolution::getMinusSCEV;
440 Extension = &ScalarEvolution::getZeroExtendExpr;
441 RawOp = Instruction::Sub;
442 NoSignedOverflow = false;
443 break;
444 }
445
446 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
447 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
448
449 auto *NarrowTy = cast<IntegerType>(LHS->getType());
450 auto *WideTy =
451 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
452
453 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000454 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
455 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000456 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000457 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
458 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000459
460 if (A != B)
461 return false;
462
463 // Proved no overflow, nuke the overflow check and, if possible, the overflow
464 // intrinsic as well.
465
466 BinaryOperator *NewResult = BinaryOperator::Create(
467 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
468
469 if (NoSignedOverflow)
470 NewResult->setHasNoSignedWrap(true);
471 else
472 NewResult->setHasNoUnsignedWrap(true);
473
474 SmallVector<ExtractValueInst *, 4> ToDelete;
475
476 for (auto *U : CI->users()) {
477 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
478 if (EVI->getIndices()[0] == 1)
479 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
480 else {
481 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
482 EVI->replaceAllUsesWith(NewResult);
483 }
484 ToDelete.push_back(EVI);
485 }
486 }
487
488 for (auto *EVI : ToDelete)
489 EVI->eraseFromParent();
490
491 if (CI->use_empty())
492 CI->eraseFromParent();
493
494 return true;
495}
496
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000497/// Eliminate an operation that consumes a simple IV and has no observable
498/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
499/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000500bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
501 Instruction *IVOperand) {
502 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
503 eliminateIVComparison(ICmp, IVOperand);
504 return true;
505 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000506 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
507 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
508 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000509 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000510 return true;
511 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000512
513 if (Bin->getOpcode() == Instruction::SDiv)
514 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000515 }
516
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000517 if (auto *CI = dyn_cast<CallInst>(UseInst))
518 if (eliminateOverflowIntrinsic(CI))
519 return true;
520
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000521 if (eliminateIdentitySCEV(UseInst, IVOperand))
522 return true;
523
524 return false;
525}
526
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000527static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
528 if (auto *BB = L->getLoopPreheader())
529 return BB->getTerminator();
530
531 return Hint;
532}
533
534/// Replace the UseInst with a constant if possible.
535bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000536 if (!SE->isSCEVable(I->getType()))
537 return false;
538
539 // Get the symbolic expression for this instruction.
540 const SCEV *S = SE->getSCEV(I);
541
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000542 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000543 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000544
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000545 // Do not generate something ridiculous even if S is loop invariant.
546 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000547 return false;
548
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000549 auto *IP = GetLoopInvariantInsertPosition(L, I);
550 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
551
552 I->replaceAllUsesWith(Invariant);
553 DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
554 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000555 ++NumFoldedUser;
556 Changed = true;
557 DeadInsts.emplace_back(I);
558 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000559}
560
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000561/// Eliminate any operation that SCEV can prove is an identity function.
562bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
563 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000564 if (!SE->isSCEVable(UseInst->getType()) ||
565 (UseInst->getType() != IVOperand->getType()) ||
566 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
567 return false;
568
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000569 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
570 // dominator tree, even if X is an operand to Y. For instance, in
571 //
572 // %iv = phi i32 {0,+,1}
573 // br %cond, label %left, label %merge
574 //
575 // left:
576 // %X = add i32 %iv, 0
577 // br label %merge
578 //
579 // merge:
580 // %M = phi (%X, %iv)
581 //
582 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
583 // %M.replaceAllUsesWith(%X) would be incorrect.
584
585 if (isa<PHINode>(UseInst))
586 // If UseInst is not a PHI node then we know that IVOperand dominates
587 // UseInst directly from the legality of SSA.
588 if (!DT || !DT->dominates(IVOperand, UseInst))
589 return false;
590
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000591 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
592 return false;
593
Andrew Trick3ec331e2011-08-10 03:46:27 +0000594 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
595
596 UseInst->replaceAllUsesWith(IVOperand);
597 ++NumElimIdentity;
598 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000599 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000600 return true;
601}
602
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000603/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
604/// unsigned-overflow. Returns true if anything changed, false otherwise.
605bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
606 Value *IVOperand) {
607
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000608 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000609 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
610 return false;
611
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000612 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000613 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000614 switch (BO->getOpcode()) {
615 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000616 return false;
617
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000618 case Instruction::Add:
619 GetExprForBO = &ScalarEvolution::getAddExpr;
620 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000621
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000622 case Instruction::Sub:
623 GetExprForBO = &ScalarEvolution::getMinusSCEV;
624 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000625
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000626 case Instruction::Mul:
627 GetExprForBO = &ScalarEvolution::getMulExpr;
628 break;
629 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000630
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000631 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
632 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
633 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
634 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000635
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000636 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000637
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000638 if (!BO->hasNoUnsignedWrap()) {
639 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
640 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
641 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000642 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000643 if (ExtendAfterOp == OpAfterExtend) {
644 BO->setHasNoUnsignedWrap();
645 SE->forgetValue(BO);
646 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000647 }
648 }
649
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000650 if (!BO->hasNoSignedWrap()) {
651 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
652 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
653 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000654 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000655 if (ExtendAfterOp == OpAfterExtend) {
656 BO->setHasNoSignedWrap();
657 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000658 Changed = true;
659 }
660 }
661
662 return Changed;
663}
664
David Greenb26a0a42017-07-05 13:25:58 +0000665/// Annotate the Shr in (X << IVOperand) >> C as exact using the
666/// information from the IV's range. Returns true if anything changed, false
667/// otherwise.
668bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
669 Value *IVOperand) {
670 using namespace llvm::PatternMatch;
671
672 if (BO->getOpcode() == Instruction::Shl) {
673 bool Changed = false;
674 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
675 for (auto *U : BO->users()) {
676 const APInt *C;
677 if (match(U,
678 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
679 match(U,
680 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
681 BinaryOperator *Shr = cast<BinaryOperator>(U);
682 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
683 Shr->setIsExact(true);
684 Changed = true;
685 }
686 }
687 }
688 return Changed;
689 }
690
691 return false;
692}
693
Sanjay Patel7777b502014-11-12 18:07:42 +0000694/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000695static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000696 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000697 SmallPtrSet<Instruction*,16> &Simplified,
698 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
699
Chandler Carruthcdf47882014-03-09 03:16:01 +0000700 for (User *U : Def->users()) {
701 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000702
703 // Avoid infinite or exponential worklist processing.
704 // Also ensure unique worklist users.
705 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
706 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000707 if (UI == Def)
708 continue;
709
710 // Only change the current Loop, do not change the other parts (e.g. other
711 // Loops).
712 if (!L->contains(UI))
713 continue;
714
715 // Do not push the same instruction more than once.
716 if (!Simplified.insert(UI).second)
717 continue;
718
719 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000720 }
721}
722
Sanjay Patel7777b502014-11-12 18:07:42 +0000723/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000724/// expression in terms of that IV.
725///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000726/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000727/// non-recursively when the operand is already known to be a simpleIVUser.
728///
729static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
730 if (!SE->isSCEVable(I->getType()))
731 return false;
732
733 // Get the symbolic expression for this instruction.
734 const SCEV *S = SE->getSCEV(I);
735
736 // Only consider affine recurrences.
737 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
738 if (AR && AR->getLoop() == L)
739 return true;
740
741 return false;
742}
743
Sanjay Patel7777b502014-11-12 18:07:42 +0000744/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000745/// of the specified induction variable. Each successive simplification may push
746/// more users which may themselves be candidates for simplification.
747///
748/// This algorithm does not require IVUsers analysis. Instead, it simplifies
749/// instructions in-place during analysis. Rather than rewriting induction
750/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000751/// top-down, updating the IR only when it encounters a clear optimization
752/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000753///
754/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
755///
756void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000757 if (!SE->isSCEVable(CurrIV->getType()))
758 return;
759
Andrew Trick3ec331e2011-08-10 03:46:27 +0000760 // Instructions processed by SimplifyIndvar for CurrIV.
761 SmallPtrSet<Instruction*,16> Simplified;
762
763 // Use-def pairs if IV users waiting to be processed for CurrIV.
764 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
765
766 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
767 // called multiple times for the same LoopPhi. This is the proper thing to
768 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000769 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000770
771 while (!SimpleIVUsers.empty()) {
772 std::pair<Instruction*, Instruction*> UseOper =
773 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000774 Instruction *UseInst = UseOper.first;
775
Andrew Trick3ec331e2011-08-10 03:46:27 +0000776 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000777 if (UseInst == CurrIV) continue;
778
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000779 // Try to replace UseInst with a loop invariant before any other
780 // simplifications.
781 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000782 continue;
783
Andrew Trick74664d52011-08-10 04:01:31 +0000784 Instruction *IVOperand = UseOper.second;
785 for (unsigned N = 0; IVOperand; ++N) {
786 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000787
Andrew Trick74664d52011-08-10 04:01:31 +0000788 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
789 if (!NewOper)
790 break; // done folding
791 IVOperand = dyn_cast<Instruction>(NewOper);
792 }
793 if (!IVOperand)
794 continue;
795
796 if (eliminateIVUser(UseOper.first, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000797 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000798 continue;
799 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000800
801 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000802 if ((isa<OverflowingBinaryOperator>(BO) &&
803 strengthenOverflowingOperation(BO, IVOperand)) ||
804 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000805 // re-queue uses of the now modified binary operator and fall
806 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000807 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000808 }
809 }
810
Andrew Trick3ec331e2011-08-10 03:46:27 +0000811 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
812 if (V && Cast) {
813 V->visitCast(Cast);
814 continue;
815 }
816 if (isSimpleIVUser(UseOper.first, L, SE)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000817 pushIVUsers(UseOper.first, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000818 }
819 }
820}
821
822namespace llvm {
823
David Blaikiea379b1812011-12-20 02:50:00 +0000824void IVVisitor::anchor() { }
825
Sanjay Patel7777b502014-11-12 18:07:42 +0000826/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000827/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000828bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000829 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000830 SCEVExpander &Rewriter, IVVisitor *V) {
831 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
832 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000833 SIV.simplifyUsers(CurrIV, V);
834 return SIV.hasChanged();
835}
836
Sanjay Patel7777b502014-11-12 18:07:42 +0000837/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000838/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000839bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000840 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000841 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
842#ifndef NDEBUG
843 Rewriter.setDebugType(DEBUG_TYPE);
844#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000845 bool Changed = false;
846 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000847 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000848 }
849 return Changed;
850}
851
Andrew Trick3ec331e2011-08-10 03:46:27 +0000852} // namespace llvm