blob: 4ebafd8ea78b0d0904e9f8fa8af44fe0ded17b77 [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"
22#include "llvm/Analysis/ScalarEvolutionExpressions.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");
38STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000039STATISTIC(
40 NumSimplifiedSDiv,
41 "Number of IV signed division operations converted to unsigned division");
Andrew Trick3ec331e2011-08-10 03:46:27 +000042STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
43
44namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000045 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000046 /// based on ScalarEvolution. It is the primary instrument of the
47 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
48 /// other loop passes that preserve SCEV.
49 class SimplifyIndvar {
50 Loop *L;
51 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000052 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000053 DominatorTree *DT;
Andrew Trick3ec331e2011-08-10 03:46:27 +000054
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000055 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000056
57 bool Changed;
58
59 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000060 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000061 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead)
Sanjoy Das5c8bead2015-10-06 21:44:49 +000062 : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000063 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000064 }
65
66 bool hasChanged() const { return Changed; }
67
68 /// Iteratively perform simplification on a worklist of users of the
69 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000070 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000071 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000072
Andrew Trick74664d52011-08-10 04:01:31 +000073 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000074
Sanjoy Das088bb0e2015-10-06 21:44:39 +000075 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
76
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000077 bool eliminateOverflowIntrinsic(CallInst *CI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000078 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
79 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
80 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
81 bool IsSigned);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000082 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000083 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000084 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000085 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000086}
Andrew Trick3ec331e2011-08-10 03:46:27 +000087
Sanjay Patel7777b502014-11-12 18:07:42 +000088/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000089/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000090///
Andrew Trick7251e412011-09-19 17:54:39 +000091/// IVOperand is guaranteed SCEVable, but UseInst may not be.
92///
Andrew Trick74664d52011-08-10 04:01:31 +000093/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000094/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000095/// Otherwise return null.
96Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000097 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000098 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000099 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000100 switch (UseInst->getOpcode()) {
101 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000102 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000103 case Instruction::UDiv:
104 case Instruction::LShr:
105 // We're only interested in the case where we know something about
106 // the numerator and have a constant denominator.
107 if (IVOperand != UseInst->getOperand(OperIdx) ||
108 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000109 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000110
111 // Attempt to fold a binary operator with constant operand.
112 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000113 if (!isa<BinaryOperator>(IVOperand)
114 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000115 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000116
117 IVSrc = IVOperand->getOperand(0);
118 // IVSrc must be the (SCEVable) IV, since the other operand is const.
119 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
120
121 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
122 if (UseInst->getOpcode() == Instruction::LShr) {
123 // Get a constant for the divisor. See createSCEV.
124 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
125 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000126 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000127
128 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000129 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000130 }
131 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
132 }
133 // We have something that might fold it's operand. Compare SCEVs.
134 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136
137 // Bypass the operand if SCEV can prove it has no effect.
138 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000139 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000140
141 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
142 << " -> " << *UseInst << '\n');
143
144 UseInst->setOperand(OperIdx, IVSrc);
145 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
146
147 ++NumElimOperand;
148 Changed = true;
149 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000150 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000151 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000152}
153
Sanjay Patel7777b502014-11-12 18:07:42 +0000154/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000155/// comparisons against an induction variable.
156void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
157 unsigned IVOperIdx = 0;
158 ICmpInst::Predicate Pred = ICmp->getPredicate();
159 if (IVOperand != ICmp->getOperand(0)) {
160 // Swapped
161 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
162 IVOperIdx = 1;
163 Pred = ICmpInst::getSwappedPredicate(Pred);
164 }
165
166 // Get the SCEVs for the ICmp operands.
167 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
168 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
169
170 // Simplify unnecessary loops away.
171 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
172 S = SE->getSCEVAtScope(S, ICmpLoop);
173 X = SE->getSCEVAtScope(X, ICmpLoop);
174
Sanjoy Das5dab2052015-07-27 21:42:49 +0000175 ICmpInst::Predicate InvariantPredicate;
176 const SCEV *InvariantLHS, *InvariantRHS;
177
Andrew Trick3ec331e2011-08-10 03:46:27 +0000178 // If the condition is always true or always false, replace it with
179 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000180 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000181 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000182 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000183 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000184 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000185 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000186 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000187 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000188 } else if (isa<PHINode>(IVOperand) &&
Sanjoy Das60fb8992016-03-18 20:37:07 +0000189 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
190 InvariantLHS, InvariantRHS)) {
Sanjoy Das5dab2052015-07-27 21:42:49 +0000191
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000192 // Rewrite the comparison to a loop invariant comparison if it can be done
Sanjoy Das5dab2052015-07-27 21:42:49 +0000193 // cheaply, where cheaply means "we don't need to emit any new
194 // instructions".
195
196 Value *NewLHS = nullptr, *NewRHS = nullptr;
197
198 if (S == InvariantLHS || X == InvariantLHS)
199 NewLHS =
200 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
201
202 if (S == InvariantRHS || X == InvariantRHS)
203 NewRHS =
204 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
205
Sanjoy Das74af78e32016-03-18 20:37:11 +0000206 auto *PN = cast<PHINode>(IVOperand);
207 for (unsigned i = 0, e = PN->getNumIncomingValues();
208 i != e && (!NewLHS || !NewRHS);
209 ++i) {
210
211 // If this is a value incoming from the backedge, then it cannot be a loop
212 // invariant value (since we know that IVOperand is an induction variable).
213 if (L->contains(PN->getIncomingBlock(i)))
214 continue;
215
216 // NB! This following assert does not fundamentally have to be true, but
217 // it is true today given how SCEV analyzes induction variables.
218 // Specifically, today SCEV will *not* recognize %iv as an induction
219 // variable in the following case:
220 //
221 // define void @f(i32 %k) {
222 // entry:
223 // br i1 undef, label %r, label %l
224 //
225 // l:
226 // %k.inc.l = add i32 %k, 1
227 // br label %loop
228 //
229 // r:
230 // %k.inc.r = add i32 %k, 1
231 // br label %loop
232 //
233 // loop:
234 // %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
235 // %iv.inc = add i32 %iv, 1
236 // br label %loop
237 // }
238 //
239 // but if it starts to, at some point, then the assertion below will have
240 // to be changed to a runtime check.
241
242 Value *Incoming = PN->getIncomingValue(i);
243
244#ifndef NDEBUG
245 if (auto *I = dyn_cast<Instruction>(Incoming))
246 assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
247#endif
Sanjoy Das5dab2052015-07-27 21:42:49 +0000248
249 const SCEV *IncomingS = SE->getSCEV(Incoming);
250
251 if (!NewLHS && IncomingS == InvariantLHS)
252 NewLHS = Incoming;
253 if (!NewRHS && IncomingS == InvariantRHS)
254 NewRHS = Incoming;
255 }
256
257 if (!NewLHS || !NewRHS)
258 // We could not find an existing value to replace either LHS or RHS.
259 // Generating new instructions has subtler tradeoffs, so avoid doing that
260 // for now.
261 return;
262
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000263 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000264 ICmp->setPredicate(InvariantPredicate);
265 ICmp->setOperand(0, NewLHS);
266 ICmp->setOperand(1, NewRHS);
267 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000268 return;
269
Andrew Trick3ec331e2011-08-10 03:46:27 +0000270 ++NumElimCmp;
271 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000272}
273
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000274bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
275 // Get the SCEVs for the ICmp operands.
276 auto *N = SE->getSCEV(SDiv->getOperand(0));
277 auto *D = SE->getSCEV(SDiv->getOperand(1));
278
279 // Simplify unnecessary loops away.
280 const Loop *L = LI->getLoopFor(SDiv->getParent());
281 N = SE->getSCEVAtScope(N, L);
282 D = SE->getSCEVAtScope(D, L);
283
284 // Replace sdiv by udiv if both of the operands are non-negative
285 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
286 auto *UDiv = BinaryOperator::Create(
287 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
288 SDiv->getName() + ".udiv", SDiv);
289 UDiv->setIsExact(SDiv->isExact());
290 SDiv->replaceAllUsesWith(UDiv);
291 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
292 ++NumSimplifiedSDiv;
293 Changed = true;
294 DeadInsts.push_back(SDiv);
295 return true;
296 }
297
298 return false;
299}
300
Sanjay Patel7777b502014-11-12 18:07:42 +0000301/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000302/// remainder operations operating on an induction variable.
303void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
304 Value *IVOperand,
305 bool IsSigned) {
306 // We're only interested in the case where we know something about
307 // the numerator.
308 if (IVOperand != Rem->getOperand(0))
309 return;
310
311 // Get the SCEVs for the ICmp operands.
312 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
313 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
314
315 // Simplify unnecessary loops away.
316 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
317 S = SE->getSCEVAtScope(S, ICmpLoop);
318 X = SE->getSCEVAtScope(X, ICmpLoop);
319
320 // i % n --> i if i is in [0,n).
321 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
322 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
323 S, X))
324 Rem->replaceAllUsesWith(Rem->getOperand(0));
325 else {
326 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000327 const SCEV *LessOne = SE->getMinusSCEV(S, SE->getOne(S->getType()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000328 if (IsSigned && !SE->isKnownNonNegative(LessOne))
329 return;
330
331 if (!SE->isKnownPredicate(IsSigned ?
332 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
333 LessOne, X))
334 return;
335
336 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000337 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000338 SelectInst *Sel =
339 SelectInst::Create(ICmp,
340 ConstantInt::get(Rem->getType(), 0),
341 Rem->getOperand(0), "tmp", Rem);
342 Rem->replaceAllUsesWith(Sel);
343 }
344
Andrew Trick3ec331e2011-08-10 03:46:27 +0000345 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
346 ++NumElimRem;
347 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000348 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000349}
350
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000351bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
352 auto *F = CI->getCalledFunction();
353 if (!F)
354 return false;
355
356 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000357 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000358 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000359 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000360
361 OperationFunctionTy Operation;
362 ExtensionFunctionTy Extension;
363
364 Instruction::BinaryOps RawOp;
365
366 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
367 // have nuw.
368 bool NoSignedOverflow;
369
370 switch (F->getIntrinsicID()) {
371 default:
372 return false;
373
374 case Intrinsic::sadd_with_overflow:
375 Operation = &ScalarEvolution::getAddExpr;
376 Extension = &ScalarEvolution::getSignExtendExpr;
377 RawOp = Instruction::Add;
378 NoSignedOverflow = true;
379 break;
380
381 case Intrinsic::uadd_with_overflow:
382 Operation = &ScalarEvolution::getAddExpr;
383 Extension = &ScalarEvolution::getZeroExtendExpr;
384 RawOp = Instruction::Add;
385 NoSignedOverflow = false;
386 break;
387
388 case Intrinsic::ssub_with_overflow:
389 Operation = &ScalarEvolution::getMinusSCEV;
390 Extension = &ScalarEvolution::getSignExtendExpr;
391 RawOp = Instruction::Sub;
392 NoSignedOverflow = true;
393 break;
394
395 case Intrinsic::usub_with_overflow:
396 Operation = &ScalarEvolution::getMinusSCEV;
397 Extension = &ScalarEvolution::getZeroExtendExpr;
398 RawOp = Instruction::Sub;
399 NoSignedOverflow = false;
400 break;
401 }
402
403 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
404 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
405
406 auto *NarrowTy = cast<IntegerType>(LHS->getType());
407 auto *WideTy =
408 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
409
410 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000411 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
412 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000413 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000414 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
415 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000416
417 if (A != B)
418 return false;
419
420 // Proved no overflow, nuke the overflow check and, if possible, the overflow
421 // intrinsic as well.
422
423 BinaryOperator *NewResult = BinaryOperator::Create(
424 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
425
426 if (NoSignedOverflow)
427 NewResult->setHasNoSignedWrap(true);
428 else
429 NewResult->setHasNoUnsignedWrap(true);
430
431 SmallVector<ExtractValueInst *, 4> ToDelete;
432
433 for (auto *U : CI->users()) {
434 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
435 if (EVI->getIndices()[0] == 1)
436 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
437 else {
438 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
439 EVI->replaceAllUsesWith(NewResult);
440 }
441 ToDelete.push_back(EVI);
442 }
443 }
444
445 for (auto *EVI : ToDelete)
446 EVI->eraseFromParent();
447
448 if (CI->use_empty())
449 CI->eraseFromParent();
450
451 return true;
452}
453
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000454/// Eliminate an operation that consumes a simple IV and has no observable
455/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
456/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000457bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
458 Instruction *IVOperand) {
459 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
460 eliminateIVComparison(ICmp, IVOperand);
461 return true;
462 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000463 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
464 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
465 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
466 eliminateIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000467 return true;
468 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000469
470 if (Bin->getOpcode() == Instruction::SDiv)
471 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000472 }
473
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000474 if (auto *CI = dyn_cast<CallInst>(UseInst))
475 if (eliminateOverflowIntrinsic(CI))
476 return true;
477
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000478 if (eliminateIdentitySCEV(UseInst, IVOperand))
479 return true;
480
481 return false;
482}
483
484/// Eliminate any operation that SCEV can prove is an identity function.
485bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
486 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000487 if (!SE->isSCEVable(UseInst->getType()) ||
488 (UseInst->getType() != IVOperand->getType()) ||
489 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
490 return false;
491
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000492 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
493 // dominator tree, even if X is an operand to Y. For instance, in
494 //
495 // %iv = phi i32 {0,+,1}
496 // br %cond, label %left, label %merge
497 //
498 // left:
499 // %X = add i32 %iv, 0
500 // br label %merge
501 //
502 // merge:
503 // %M = phi (%X, %iv)
504 //
505 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
506 // %M.replaceAllUsesWith(%X) would be incorrect.
507
508 if (isa<PHINode>(UseInst))
509 // If UseInst is not a PHI node then we know that IVOperand dominates
510 // UseInst directly from the legality of SSA.
511 if (!DT || !DT->dominates(IVOperand, UseInst))
512 return false;
513
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000514 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
515 return false;
516
Andrew Trick3ec331e2011-08-10 03:46:27 +0000517 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
518
519 UseInst->replaceAllUsesWith(IVOperand);
520 ++NumElimIdentity;
521 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000522 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000523 return true;
524}
525
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000526/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
527/// unsigned-overflow. Returns true if anything changed, false otherwise.
528bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
529 Value *IVOperand) {
530
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000531 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000532 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
533 return false;
534
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000535 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000536 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000537 switch (BO->getOpcode()) {
538 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000539 return false;
540
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000541 case Instruction::Add:
542 GetExprForBO = &ScalarEvolution::getAddExpr;
543 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000544
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000545 case Instruction::Sub:
546 GetExprForBO = &ScalarEvolution::getMinusSCEV;
547 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000548
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000549 case Instruction::Mul:
550 GetExprForBO = &ScalarEvolution::getMulExpr;
551 break;
552 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000553
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000554 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
555 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
556 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
557 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000558
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000559 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000560
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000561 if (!BO->hasNoUnsignedWrap()) {
562 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
563 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
564 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000565 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000566 if (ExtendAfterOp == OpAfterExtend) {
567 BO->setHasNoUnsignedWrap();
568 SE->forgetValue(BO);
569 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000570 }
571 }
572
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000573 if (!BO->hasNoSignedWrap()) {
574 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
575 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
576 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000577 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000578 if (ExtendAfterOp == OpAfterExtend) {
579 BO->setHasNoSignedWrap();
580 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000581 Changed = true;
582 }
583 }
584
585 return Changed;
586}
587
David Greenb26a0a42017-07-05 13:25:58 +0000588/// Annotate the Shr in (X << IVOperand) >> C as exact using the
589/// information from the IV's range. Returns true if anything changed, false
590/// otherwise.
591bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
592 Value *IVOperand) {
593 using namespace llvm::PatternMatch;
594
595 if (BO->getOpcode() == Instruction::Shl) {
596 bool Changed = false;
597 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
598 for (auto *U : BO->users()) {
599 const APInt *C;
600 if (match(U,
601 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
602 match(U,
603 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
604 BinaryOperator *Shr = cast<BinaryOperator>(U);
605 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
606 Shr->setIsExact(true);
607 Changed = true;
608 }
609 }
610 }
611 return Changed;
612 }
613
614 return false;
615}
616
Sanjay Patel7777b502014-11-12 18:07:42 +0000617/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000618static void pushIVUsers(
619 Instruction *Def,
620 SmallPtrSet<Instruction*,16> &Simplified,
621 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
622
Chandler Carruthcdf47882014-03-09 03:16:01 +0000623 for (User *U : Def->users()) {
624 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000625
626 // Avoid infinite or exponential worklist processing.
627 // Also ensure unique worklist users.
628 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
629 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000630 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000631 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000632 }
633}
634
Sanjay Patel7777b502014-11-12 18:07:42 +0000635/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000636/// expression in terms of that IV.
637///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000638/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000639/// non-recursively when the operand is already known to be a simpleIVUser.
640///
641static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
642 if (!SE->isSCEVable(I->getType()))
643 return false;
644
645 // Get the symbolic expression for this instruction.
646 const SCEV *S = SE->getSCEV(I);
647
648 // Only consider affine recurrences.
649 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
650 if (AR && AR->getLoop() == L)
651 return true;
652
653 return false;
654}
655
Sanjay Patel7777b502014-11-12 18:07:42 +0000656/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000657/// of the specified induction variable. Each successive simplification may push
658/// more users which may themselves be candidates for simplification.
659///
660/// This algorithm does not require IVUsers analysis. Instead, it simplifies
661/// instructions in-place during analysis. Rather than rewriting induction
662/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000663/// top-down, updating the IR only when it encounters a clear optimization
664/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000665///
666/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
667///
668void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000669 if (!SE->isSCEVable(CurrIV->getType()))
670 return;
671
Andrew Trick3ec331e2011-08-10 03:46:27 +0000672 // Instructions processed by SimplifyIndvar for CurrIV.
673 SmallPtrSet<Instruction*,16> Simplified;
674
675 // Use-def pairs if IV users waiting to be processed for CurrIV.
676 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
677
678 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
679 // called multiple times for the same LoopPhi. This is the proper thing to
680 // do for loop header phis that use each other.
681 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
682
683 while (!SimpleIVUsers.empty()) {
684 std::pair<Instruction*, Instruction*> UseOper =
685 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000686 Instruction *UseInst = UseOper.first;
687
Andrew Trick3ec331e2011-08-10 03:46:27 +0000688 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000689 if (UseInst == CurrIV) continue;
690
Andrew Trick74664d52011-08-10 04:01:31 +0000691 Instruction *IVOperand = UseOper.second;
692 for (unsigned N = 0; IVOperand; ++N) {
693 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000694
Andrew Trick74664d52011-08-10 04:01:31 +0000695 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
696 if (!NewOper)
697 break; // done folding
698 IVOperand = dyn_cast<Instruction>(NewOper);
699 }
700 if (!IVOperand)
701 continue;
702
703 if (eliminateIVUser(UseOper.first, IVOperand)) {
704 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000705 continue;
706 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000707
708 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000709 if ((isa<OverflowingBinaryOperator>(BO) &&
710 strengthenOverflowingOperation(BO, IVOperand)) ||
711 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000712 // re-queue uses of the now modified binary operator and fall
713 // through to the checks that remain.
714 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
715 }
716 }
717
Andrew Trick3ec331e2011-08-10 03:46:27 +0000718 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
719 if (V && Cast) {
720 V->visitCast(Cast);
721 continue;
722 }
723 if (isSimpleIVUser(UseOper.first, L, SE)) {
724 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
725 }
726 }
727}
728
729namespace llvm {
730
David Blaikiea379b1812011-12-20 02:50:00 +0000731void IVVisitor::anchor() { }
732
Sanjay Patel7777b502014-11-12 18:07:42 +0000733/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000734/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000735bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000736 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Justin Bogner843fb202015-12-15 19:40:57 +0000737 IVVisitor *V) {
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000738 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000739 SIV.simplifyUsers(CurrIV, V);
740 return SIV.hasChanged();
741}
742
Sanjay Patel7777b502014-11-12 18:07:42 +0000743/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000744/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000745bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000746 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000747 bool Changed = false;
748 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Justin Bogner843fb202015-12-15 19:40:57 +0000749 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000750 }
751 return Changed;
752}
753
Andrew Trick3ec331e2011-08-10 03:46:27 +0000754} // namespace llvm