blob: 6a83053bd97f4313b1ee979822c01bc4500acaae [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"
Andrew Trick3ec331e2011-08-10 03:46:27 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000030
31using namespace llvm;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "indvars"
34
Andrew Trick3ec331e2011-08-10 03:46:27 +000035STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
36STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
37STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
38STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
39
40namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000041 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000042 /// based on ScalarEvolution. It is the primary instrument of the
43 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
44 /// other loop passes that preserve SCEV.
45 class SimplifyIndvar {
46 Loop *L;
47 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000048 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000049 DominatorTree *DT;
Andrew Trick3ec331e2011-08-10 03:46:27 +000050
51 SmallVectorImpl<WeakVH> &DeadInsts;
52
53 bool Changed;
54
55 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000056 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
57 LoopInfo *LI,SmallVectorImpl<WeakVH> &Dead)
58 : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000059 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000060 }
61
62 bool hasChanged() const { return Changed; }
63
64 /// Iteratively perform simplification on a worklist of users of the
65 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000066 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000067 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000068
Andrew Trick74664d52011-08-10 04:01:31 +000069 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000070
Sanjoy Das088bb0e2015-10-06 21:44:39 +000071 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
72
Andrew Trick3ec331e2011-08-10 03:46:27 +000073 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
74 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
75 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
76 bool IsSigned);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000077 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
Andrew Trick0ba77a02013-12-23 23:31:49 +000078
79 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
80 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000081 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000082}
Andrew Trick3ec331e2011-08-10 03:46:27 +000083
Sanjay Patel7777b502014-11-12 18:07:42 +000084/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000085/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000086///
Andrew Trick7251e412011-09-19 17:54:39 +000087/// IVOperand is guaranteed SCEVable, but UseInst may not be.
88///
Andrew Trick74664d52011-08-10 04:01:31 +000089/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000090/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000091/// Otherwise return null.
92Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000093 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000094 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000095 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000096 switch (UseInst->getOpcode()) {
97 default:
Craig Topperf40110f2014-04-25 05:29:35 +000098 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000099 case Instruction::UDiv:
100 case Instruction::LShr:
101 // We're only interested in the case where we know something about
102 // the numerator and have a constant denominator.
103 if (IVOperand != UseInst->getOperand(OperIdx) ||
104 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000105 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000106
107 // Attempt to fold a binary operator with constant operand.
108 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000109 if (!isa<BinaryOperator>(IVOperand)
110 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000111 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000112
113 IVSrc = IVOperand->getOperand(0);
114 // IVSrc must be the (SCEVable) IV, since the other operand is const.
115 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
116
117 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
118 if (UseInst->getOpcode() == Instruction::LShr) {
119 // Get a constant for the divisor. See createSCEV.
120 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
121 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000122 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000123
124 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000125 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000126 }
127 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
128 }
129 // We have something that might fold it's operand. Compare SCEVs.
130 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000131 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000132
133 // Bypass the operand if SCEV can prove it has no effect.
134 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136
137 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
138 << " -> " << *UseInst << '\n');
139
140 UseInst->setOperand(OperIdx, IVSrc);
141 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
142
143 ++NumElimOperand;
144 Changed = true;
145 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000146 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000147 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000148}
149
Sanjay Patel7777b502014-11-12 18:07:42 +0000150/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000151/// comparisons against an induction variable.
152void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
153 unsigned IVOperIdx = 0;
154 ICmpInst::Predicate Pred = ICmp->getPredicate();
155 if (IVOperand != ICmp->getOperand(0)) {
156 // Swapped
157 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
158 IVOperIdx = 1;
159 Pred = ICmpInst::getSwappedPredicate(Pred);
160 }
161
162 // Get the SCEVs for the ICmp operands.
163 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
164 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
165
166 // Simplify unnecessary loops away.
167 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
168 S = SE->getSCEVAtScope(S, ICmpLoop);
169 X = SE->getSCEVAtScope(X, ICmpLoop);
170
Sanjoy Das5dab2052015-07-27 21:42:49 +0000171 ICmpInst::Predicate InvariantPredicate;
172 const SCEV *InvariantLHS, *InvariantRHS;
173
Andrew Trick3ec331e2011-08-10 03:46:27 +0000174 // If the condition is always true or always false, replace it with
175 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000176 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000177 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000178 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000179 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000180 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000181 ICmp->replaceAllUsesWith(ConstantInt::getFalse(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 (isa<PHINode>(IVOperand) &&
Sanjoy Das60fb8992016-03-18 20:37:07 +0000185 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
186 InvariantLHS, InvariantRHS)) {
Sanjoy Das5dab2052015-07-27 21:42:49 +0000187
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000188 // Rewrite the comparison to a loop invariant comparison if it can be done
Sanjoy Das5dab2052015-07-27 21:42:49 +0000189 // cheaply, where cheaply means "we don't need to emit any new
190 // instructions".
191
192 Value *NewLHS = nullptr, *NewRHS = nullptr;
193
194 if (S == InvariantLHS || X == InvariantLHS)
195 NewLHS =
196 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
197
198 if (S == InvariantRHS || X == InvariantRHS)
199 NewRHS =
200 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
201
Sanjoy Das74af78e32016-03-18 20:37:11 +0000202 auto *PN = cast<PHINode>(IVOperand);
203 for (unsigned i = 0, e = PN->getNumIncomingValues();
204 i != e && (!NewLHS || !NewRHS);
205 ++i) {
206
207 // If this is a value incoming from the backedge, then it cannot be a loop
208 // invariant value (since we know that IVOperand is an induction variable).
209 if (L->contains(PN->getIncomingBlock(i)))
210 continue;
211
212 // NB! This following assert does not fundamentally have to be true, but
213 // it is true today given how SCEV analyzes induction variables.
214 // Specifically, today SCEV will *not* recognize %iv as an induction
215 // variable in the following case:
216 //
217 // define void @f(i32 %k) {
218 // entry:
219 // br i1 undef, label %r, label %l
220 //
221 // l:
222 // %k.inc.l = add i32 %k, 1
223 // br label %loop
224 //
225 // r:
226 // %k.inc.r = add i32 %k, 1
227 // br label %loop
228 //
229 // loop:
230 // %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
231 // %iv.inc = add i32 %iv, 1
232 // br label %loop
233 // }
234 //
235 // but if it starts to, at some point, then the assertion below will have
236 // to be changed to a runtime check.
237
238 Value *Incoming = PN->getIncomingValue(i);
239
240#ifndef NDEBUG
241 if (auto *I = dyn_cast<Instruction>(Incoming))
242 assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
243#endif
Sanjoy Das5dab2052015-07-27 21:42:49 +0000244
245 const SCEV *IncomingS = SE->getSCEV(Incoming);
246
247 if (!NewLHS && IncomingS == InvariantLHS)
248 NewLHS = Incoming;
249 if (!NewRHS && IncomingS == InvariantRHS)
250 NewRHS = Incoming;
251 }
252
253 if (!NewLHS || !NewRHS)
254 // We could not find an existing value to replace either LHS or RHS.
255 // Generating new instructions has subtler tradeoffs, so avoid doing that
256 // for now.
257 return;
258
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000259 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000260 ICmp->setPredicate(InvariantPredicate);
261 ICmp->setOperand(0, NewLHS);
262 ICmp->setOperand(1, NewRHS);
263 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000264 return;
265
Andrew Trick3ec331e2011-08-10 03:46:27 +0000266 ++NumElimCmp;
267 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000268}
269
Sanjay Patel7777b502014-11-12 18:07:42 +0000270/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000271/// remainder operations operating on an induction variable.
272void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
273 Value *IVOperand,
274 bool IsSigned) {
275 // We're only interested in the case where we know something about
276 // the numerator.
277 if (IVOperand != Rem->getOperand(0))
278 return;
279
280 // Get the SCEVs for the ICmp operands.
281 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
282 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
283
284 // Simplify unnecessary loops away.
285 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
286 S = SE->getSCEVAtScope(S, ICmpLoop);
287 X = SE->getSCEVAtScope(X, ICmpLoop);
288
289 // i % n --> i if i is in [0,n).
290 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
291 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
292 S, X))
293 Rem->replaceAllUsesWith(Rem->getOperand(0));
294 else {
295 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000296 const SCEV *LessOne = SE->getMinusSCEV(S, SE->getOne(S->getType()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000297 if (IsSigned && !SE->isKnownNonNegative(LessOne))
298 return;
299
300 if (!SE->isKnownPredicate(IsSigned ?
301 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
302 LessOne, X))
303 return;
304
305 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000306 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000307 SelectInst *Sel =
308 SelectInst::Create(ICmp,
309 ConstantInt::get(Rem->getType(), 0),
310 Rem->getOperand(0), "tmp", Rem);
311 Rem->replaceAllUsesWith(Sel);
312 }
313
Andrew Trick3ec331e2011-08-10 03:46:27 +0000314 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
315 ++NumElimRem;
316 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000317 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000318}
319
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000320/// Eliminate an operation that consumes a simple IV and has no observable
321/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
322/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000323bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
324 Instruction *IVOperand) {
325 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
326 eliminateIVComparison(ICmp, IVOperand);
327 return true;
328 }
329 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
330 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
331 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
332 eliminateIVRemainder(Rem, IVOperand, IsSigned);
333 return true;
334 }
335 }
336
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000337 if (eliminateIdentitySCEV(UseInst, IVOperand))
338 return true;
339
340 return false;
341}
342
343/// Eliminate any operation that SCEV can prove is an identity function.
344bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
345 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000346 if (!SE->isSCEVable(UseInst->getType()) ||
347 (UseInst->getType() != IVOperand->getType()) ||
348 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
349 return false;
350
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000351 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
352 // dominator tree, even if X is an operand to Y. For instance, in
353 //
354 // %iv = phi i32 {0,+,1}
355 // br %cond, label %left, label %merge
356 //
357 // left:
358 // %X = add i32 %iv, 0
359 // br label %merge
360 //
361 // merge:
362 // %M = phi (%X, %iv)
363 //
364 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
365 // %M.replaceAllUsesWith(%X) would be incorrect.
366
367 if (isa<PHINode>(UseInst))
368 // If UseInst is not a PHI node then we know that IVOperand dominates
369 // UseInst directly from the legality of SSA.
370 if (!DT || !DT->dominates(IVOperand, UseInst))
371 return false;
372
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000373 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
374 return false;
375
Andrew Trick3ec331e2011-08-10 03:46:27 +0000376 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
377
378 UseInst->replaceAllUsesWith(IVOperand);
379 ++NumElimIdentity;
380 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000381 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000382 return true;
383}
384
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000385/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
386/// unsigned-overflow. Returns true if anything changed, false otherwise.
387bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
388 Value *IVOperand) {
389
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000390 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000391 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
392 return false;
393
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000394 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
395 SCEV::NoWrapFlags);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000396
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000397 switch (BO->getOpcode()) {
398 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000399 return false;
400
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000401 case Instruction::Add:
402 GetExprForBO = &ScalarEvolution::getAddExpr;
403 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000404
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000405 case Instruction::Sub:
406 GetExprForBO = &ScalarEvolution::getMinusSCEV;
407 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000408
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000409 case Instruction::Mul:
410 GetExprForBO = &ScalarEvolution::getMulExpr;
411 break;
412 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000413
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000414 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
415 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
416 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
417 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000418
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000419 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000420
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000421 if (!BO->hasNoUnsignedWrap()) {
422 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
423 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
424 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
425 SCEV::FlagAnyWrap);
426 if (ExtendAfterOp == OpAfterExtend) {
427 BO->setHasNoUnsignedWrap();
428 SE->forgetValue(BO);
429 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000430 }
431 }
432
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000433 if (!BO->hasNoSignedWrap()) {
434 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
435 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
436 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
437 SCEV::FlagAnyWrap);
438 if (ExtendAfterOp == OpAfterExtend) {
439 BO->setHasNoSignedWrap();
440 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000441 Changed = true;
442 }
443 }
444
445 return Changed;
446}
447
Andrew Trick0ba77a02013-12-23 23:31:49 +0000448/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
449/// analysis and optimization.
450///
451/// \return A new value representing the non-overflowing add if possible,
452/// otherwise return the original value.
453Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
454 const DominatorTree *DT) {
455 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
456 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
457 return IVUser;
458
459 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000460 BranchInst *Branch = nullptr;
461 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000462 for (User *U : II->users()) {
463 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000464 if (ExtractInst->getNumIndices() != 1)
465 continue;
466 if (ExtractInst->getIndices()[0] == 0)
467 AddVal = ExtractInst;
468 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000469 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000470 }
471 }
472 if (!AddVal || !Branch)
473 return IVUser;
474
475 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000476 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000477 return IVUser;
478
479 // Check if all users of the add are provably NSW.
480 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000481 for (Use &U : AddVal->uses()) {
482 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000483 BasicBlock *UseBB = UseInst->getParent();
484 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000485 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000486 if (!DT->dominates(ContinueBB, UseBB)) {
487 AllNSW = false;
488 break;
489 }
490 }
491 }
492 if (!AllNSW)
493 return IVUser;
494
495 // Go for it...
496 IRBuilder<> Builder(IVUser);
497 Instruction *AddInst = dyn_cast<Instruction>(
498 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
499
500 // The caller expects the new add to have the same form as the intrinsic. The
501 // IV operand position must be the same.
502 assert((AddInst->getOpcode() == Instruction::Add &&
503 AddInst->getOperand(0) == II->getOperand(0)) &&
504 "Bad add instruction created from overflow intrinsic.");
505
506 AddVal->replaceAllUsesWith(AddInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000507 DeadInsts.emplace_back(AddVal);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000508 return AddInst;
509}
510
Sanjay Patel7777b502014-11-12 18:07:42 +0000511/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000512static void pushIVUsers(
513 Instruction *Def,
514 SmallPtrSet<Instruction*,16> &Simplified,
515 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
516
Chandler Carruthcdf47882014-03-09 03:16:01 +0000517 for (User *U : Def->users()) {
518 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000519
520 // Avoid infinite or exponential worklist processing.
521 // Also ensure unique worklist users.
522 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
523 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000524 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000525 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000526 }
527}
528
Sanjay Patel7777b502014-11-12 18:07:42 +0000529/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000530/// expression in terms of that IV.
531///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000532/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000533/// non-recursively when the operand is already known to be a simpleIVUser.
534///
535static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
536 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
542 // Only consider affine recurrences.
543 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
544 if (AR && AR->getLoop() == L)
545 return true;
546
547 return false;
548}
549
Sanjay Patel7777b502014-11-12 18:07:42 +0000550/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000551/// of the specified induction variable. Each successive simplification may push
552/// more users which may themselves be candidates for simplification.
553///
554/// This algorithm does not require IVUsers analysis. Instead, it simplifies
555/// instructions in-place during analysis. Rather than rewriting induction
556/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000557/// top-down, updating the IR only when it encounters a clear optimization
558/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000559///
560/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
561///
562void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000563 if (!SE->isSCEVable(CurrIV->getType()))
564 return;
565
Andrew Trick3ec331e2011-08-10 03:46:27 +0000566 // Instructions processed by SimplifyIndvar for CurrIV.
567 SmallPtrSet<Instruction*,16> Simplified;
568
569 // Use-def pairs if IV users waiting to be processed for CurrIV.
570 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
571
572 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
573 // called multiple times for the same LoopPhi. This is the proper thing to
574 // do for loop header phis that use each other.
575 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
576
577 while (!SimpleIVUsers.empty()) {
578 std::pair<Instruction*, Instruction*> UseOper =
579 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000580 Instruction *UseInst = UseOper.first;
581
Andrew Trick3ec331e2011-08-10 03:46:27 +0000582 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000583 if (UseInst == CurrIV) continue;
584
585 if (V && V->shouldSplitOverflowInstrinsics()) {
586 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
587 if (!UseInst)
588 continue;
589 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000590
Andrew Trick74664d52011-08-10 04:01:31 +0000591 Instruction *IVOperand = UseOper.second;
592 for (unsigned N = 0; IVOperand; ++N) {
593 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000594
Andrew Trick74664d52011-08-10 04:01:31 +0000595 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
596 if (!NewOper)
597 break; // done folding
598 IVOperand = dyn_cast<Instruction>(NewOper);
599 }
600 if (!IVOperand)
601 continue;
602
603 if (eliminateIVUser(UseOper.first, IVOperand)) {
604 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000605 continue;
606 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000607
608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
609 if (isa<OverflowingBinaryOperator>(BO) &&
610 strengthenOverflowingOperation(BO, IVOperand)) {
611 // re-queue uses of the now modified binary operator and fall
612 // through to the checks that remain.
613 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
614 }
615 }
616
Andrew Trick3ec331e2011-08-10 03:46:27 +0000617 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
618 if (V && Cast) {
619 V->visitCast(Cast);
620 continue;
621 }
622 if (isSimpleIVUser(UseOper.first, L, SE)) {
623 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
624 }
625 }
626}
627
628namespace llvm {
629
David Blaikiea379b1812011-12-20 02:50:00 +0000630void IVVisitor::anchor() { }
631
Sanjay Patel7777b502014-11-12 18:07:42 +0000632/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000633/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000634bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000635 LoopInfo *LI, SmallVectorImpl<WeakVH> &Dead,
636 IVVisitor *V) {
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000637 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000638 SIV.simplifyUsers(CurrIV, V);
639 return SIV.hasChanged();
640}
641
Sanjay Patel7777b502014-11-12 18:07:42 +0000642/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000643/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000644bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000645 LoopInfo *LI, SmallVectorImpl<WeakVH> &Dead) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000646 bool Changed = false;
647 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Justin Bogner843fb202015-12-15 19:40:57 +0000648 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000649 }
650 return Changed;
651}
652
Andrew Trick3ec331e2011-08-10 03:46:27 +0000653} // namespace llvm