blob: 6a5d885336295da35d744292f58b313ce0445644 [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/IVUsers.h"
21#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000026#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
Andrew Trick0ba77a02013-12-23 23:31:49 +000028#include "llvm/IR/IntrinsicInst.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000032
33using namespace llvm;
34
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "indvars"
36
Andrew Trick3ec331e2011-08-10 03:46:27 +000037STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
38STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
39STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
40STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
41
42namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000043 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000044 /// based on ScalarEvolution. It is the primary instrument of the
45 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
46 /// other loop passes that preserve SCEV.
47 class SimplifyIndvar {
48 Loop *L;
49 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000050 ScalarEvolution *SE;
Andrew Trick3ec331e2011-08-10 03:46:27 +000051
52 SmallVectorImpl<WeakVH> &DeadInsts;
53
54 bool Changed;
55
56 public:
Chandler Carruth4f8f3072015-01-17 14:16:18 +000057 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LoopInfo *LI,
Chandler Carruth24fd0292015-01-17 14:31:35 +000058 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = nullptr)
59 : L(Loop), LI(LI), SE(SE), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000060 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000061 }
62
63 bool hasChanged() const { return Changed; }
64
65 /// Iteratively perform simplification on a worklist of users of the
66 /// specified induction variable. This is the top-level driver that applies
67 /// all simplicitions to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000068 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000069
Andrew Trick74664d52011-08-10 04:01:31 +000070 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000071
72 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
73 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
74 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
75 bool IsSigned);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000076 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
Andrew Trick0ba77a02013-12-23 23:31:49 +000077
78 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
79 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000080 };
81}
82
Sanjay Patel7777b502014-11-12 18:07:42 +000083/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000084/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000085///
Andrew Trick7251e412011-09-19 17:54:39 +000086/// IVOperand is guaranteed SCEVable, but UseInst may not be.
87///
Andrew Trick74664d52011-08-10 04:01:31 +000088/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000089/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000090/// Otherwise return null.
91Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000092 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000093 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000094 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000095 switch (UseInst->getOpcode()) {
96 default:
Craig Topperf40110f2014-04-25 05:29:35 +000097 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000098 case Instruction::UDiv:
99 case Instruction::LShr:
100 // We're only interested in the case where we know something about
101 // the numerator and have a constant denominator.
102 if (IVOperand != UseInst->getOperand(OperIdx) ||
103 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000104 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000105
106 // Attempt to fold a binary operator with constant operand.
107 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000108 if (!isa<BinaryOperator>(IVOperand)
109 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000110 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000111
112 IVSrc = IVOperand->getOperand(0);
113 // IVSrc must be the (SCEVable) IV, since the other operand is const.
114 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
115
116 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
117 if (UseInst->getOpcode() == Instruction::LShr) {
118 // Get a constant for the divisor. See createSCEV.
119 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
120 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000121 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000122
123 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000124 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000125 }
126 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
127 }
128 // We have something that might fold it's operand. Compare SCEVs.
129 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000130 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000131
132 // Bypass the operand if SCEV can prove it has no effect.
133 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000134 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000135
136 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
137 << " -> " << *UseInst << '\n');
138
139 UseInst->setOperand(OperIdx, IVSrc);
140 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
141
142 ++NumElimOperand;
143 Changed = true;
144 if (IVOperand->use_empty())
145 DeadInsts.push_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000146 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000147}
148
Sanjay Patel7777b502014-11-12 18:07:42 +0000149/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000150/// comparisons against an induction variable.
151void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
152 unsigned IVOperIdx = 0;
153 ICmpInst::Predicate Pred = ICmp->getPredicate();
154 if (IVOperand != ICmp->getOperand(0)) {
155 // Swapped
156 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
157 IVOperIdx = 1;
158 Pred = ICmpInst::getSwappedPredicate(Pred);
159 }
160
161 // Get the SCEVs for the ICmp operands.
162 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
163 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
164
165 // Simplify unnecessary loops away.
166 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
167 S = SE->getSCEVAtScope(S, ICmpLoop);
168 X = SE->getSCEVAtScope(X, ICmpLoop);
169
170 // If the condition is always true or always false, replace it with
171 // a constant value.
172 if (SE->isKnownPredicate(Pred, S, X))
173 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
174 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
175 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
176 else
177 return;
178
179 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
180 ++NumElimCmp;
181 Changed = true;
182 DeadInsts.push_back(ICmp);
183}
184
Sanjay Patel7777b502014-11-12 18:07:42 +0000185/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000186/// remainder operations operating on an induction variable.
187void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
188 Value *IVOperand,
189 bool IsSigned) {
190 // We're only interested in the case where we know something about
191 // the numerator.
192 if (IVOperand != Rem->getOperand(0))
193 return;
194
195 // Get the SCEVs for the ICmp operands.
196 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
197 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
198
199 // Simplify unnecessary loops away.
200 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
201 S = SE->getSCEVAtScope(S, ICmpLoop);
202 X = SE->getSCEVAtScope(X, ICmpLoop);
203
204 // i % n --> i if i is in [0,n).
205 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
206 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
207 S, X))
208 Rem->replaceAllUsesWith(Rem->getOperand(0));
209 else {
210 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
211 const SCEV *LessOne =
212 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
213 if (IsSigned && !SE->isKnownNonNegative(LessOne))
214 return;
215
216 if (!SE->isKnownPredicate(IsSigned ?
217 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
218 LessOne, X))
219 return;
220
221 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000222 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000223 SelectInst *Sel =
224 SelectInst::Create(ICmp,
225 ConstantInt::get(Rem->getType(), 0),
226 Rem->getOperand(0), "tmp", Rem);
227 Rem->replaceAllUsesWith(Sel);
228 }
229
Andrew Trick3ec331e2011-08-10 03:46:27 +0000230 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
231 ++NumElimRem;
232 Changed = true;
233 DeadInsts.push_back(Rem);
234}
235
Sanjay Patel7777b502014-11-12 18:07:42 +0000236/// Eliminate an operation that consumes a simple IV and has
Andrew Trick3ec331e2011-08-10 03:46:27 +0000237/// no observable side-effect given the range of IV values.
Andrew Trick7251e412011-09-19 17:54:39 +0000238/// IVOperand is guaranteed SCEVable, but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000239bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
240 Instruction *IVOperand) {
241 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
242 eliminateIVComparison(ICmp, IVOperand);
243 return true;
244 }
245 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
246 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
247 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
248 eliminateIVRemainder(Rem, IVOperand, IsSigned);
249 return true;
250 }
251 }
252
253 // Eliminate any operation that SCEV can prove is an identity function.
254 if (!SE->isSCEVable(UseInst->getType()) ||
255 (UseInst->getType() != IVOperand->getType()) ||
256 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
257 return false;
258
259 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
260
261 UseInst->replaceAllUsesWith(IVOperand);
262 ++NumElimIdentity;
263 Changed = true;
264 DeadInsts.push_back(UseInst);
265 return true;
266}
267
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000268/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
269/// unsigned-overflow. Returns true if anything changed, false otherwise.
270bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
271 Value *IVOperand) {
272
273 // Currently we only handle instructions of the form "add <indvar> <value>"
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000274 unsigned Op = BO->getOpcode();
Sanjoy Das8c252bd2015-01-15 01:46:09 +0000275 if (Op != Instruction::Add)
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000276 return false;
277
278 // If BO is already both nuw and nsw then there is nothing left to do
279 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
280 return false;
281
282 IntegerType *IT = cast<IntegerType>(IVOperand->getType());
283 Value *OtherOperand = nullptr;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000284 if (BO->getOperand(0) == IVOperand) {
285 OtherOperand = BO->getOperand(1);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000286 } else {
287 assert(BO->getOperand(1) == IVOperand && "only other use!");
288 OtherOperand = BO->getOperand(0);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000289 }
290
291 bool Changed = false;
292 const SCEV *OtherOpSCEV = SE->getSCEV(OtherOperand);
293 if (OtherOpSCEV == SE->getCouldNotCompute())
294 return false;
295
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000296 const SCEV *IVOpSCEV = SE->getSCEV(IVOperand);
297 const SCEV *ZeroSCEV = SE->getConstant(IVOpSCEV->getType(), 0);
298
299 if (!BO->hasNoSignedWrap()) {
300 // Upgrade the add to an "add nsw" if we can prove that it will never
301 // sign-overflow or sign-underflow.
302
303 const SCEV *SignedMax =
304 SE->getConstant(APInt::getSignedMaxValue(IT->getBitWidth()));
305 const SCEV *SignedMin =
306 SE->getConstant(APInt::getSignedMinValue(IT->getBitWidth()));
307
308 // The addition "IVOperand + OtherOp" does not sign-overflow if the result
309 // is sign-representable in 2's complement in the given bit-width.
310 //
311 // If OtherOp is SLT 0, then for an IVOperand in [SignedMin - OtherOp,
312 // SignedMax], "IVOperand + OtherOp" is in [SignedMin, SignedMax + OtherOp].
313 // Everything in [SignedMin, SignedMax + OtherOp] is representable since
314 // SignedMax + OtherOp is at least -1.
315 //
316 // If OtherOp is SGE 0, then for an IVOperand in [SignedMin, SignedMax -
317 // OtherOp], "IVOperand + OtherOp" is in [SignedMin + OtherOp, SignedMax].
318 // Everything in [SignedMin + OtherOp, SignedMax] is representable since
319 // SignedMin + OtherOp is at most -1.
320 //
321 // It follows that for all values of IVOperand in [SignedMin - smin(0,
322 // OtherOp), SignedMax - smax(0, OtherOp)] the result of the add is
323 // representable (i.e. there is no sign-overflow).
324
325 const SCEV *UpperDelta = SE->getSMaxExpr(ZeroSCEV, OtherOpSCEV);
326 const SCEV *UpperLimit = SE->getMinusSCEV(SignedMax, UpperDelta);
327
328 bool NeverSignedOverflows =
329 SE->isKnownPredicate(ICmpInst::ICMP_SLE, IVOpSCEV, UpperLimit);
330
331 if (NeverSignedOverflows) {
332 const SCEV *LowerDelta = SE->getSMinExpr(ZeroSCEV, OtherOpSCEV);
333 const SCEV *LowerLimit = SE->getMinusSCEV(SignedMin, LowerDelta);
334
335 bool NeverSignedUnderflows =
336 SE->isKnownPredicate(ICmpInst::ICMP_SGE, IVOpSCEV, LowerLimit);
337 if (NeverSignedUnderflows) {
338 BO->setHasNoSignedWrap(true);
339 Changed = true;
340 }
341 }
342 }
343
344 if (!BO->hasNoUnsignedWrap()) {
345 // Upgrade the add computing "IVOperand + OtherOp" to an "add nuw" if we can
346 // prove that it will never unsigned-overflow (i.e. the result will always
347 // be representable in the given bit-width).
348 //
349 // "IVOperand + OtherOp" is unsigned-representable in 2's complement iff it
350 // does not produce a carry. "IVOperand + OtherOp" produces no carry iff
351 // IVOperand ULE (UnsignedMax - OtherOp).
352
353 const SCEV *UnsignedMax =
354 SE->getConstant(APInt::getMaxValue(IT->getBitWidth()));
355 const SCEV *UpperLimit = SE->getMinusSCEV(UnsignedMax, OtherOpSCEV);
356
357 bool NeverUnsignedOverflows =
358 SE->isKnownPredicate(ICmpInst::ICMP_ULE, IVOpSCEV, UpperLimit);
359
360 if (NeverUnsignedOverflows) {
361 BO->setHasNoUnsignedWrap(true);
362 Changed = true;
363 }
364 }
365
366 return Changed;
367}
368
Andrew Trick0ba77a02013-12-23 23:31:49 +0000369/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
370/// analysis and optimization.
371///
372/// \return A new value representing the non-overflowing add if possible,
373/// otherwise return the original value.
374Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
375 const DominatorTree *DT) {
376 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
377 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
378 return IVUser;
379
380 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000381 BranchInst *Branch = nullptr;
382 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000383 for (User *U : II->users()) {
384 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000385 if (ExtractInst->getNumIndices() != 1)
386 continue;
387 if (ExtractInst->getIndices()[0] == 0)
388 AddVal = ExtractInst;
389 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000390 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000391 }
392 }
393 if (!AddVal || !Branch)
394 return IVUser;
395
396 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000397 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000398 return IVUser;
399
400 // Check if all users of the add are provably NSW.
401 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000402 for (Use &U : AddVal->uses()) {
403 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000404 BasicBlock *UseBB = UseInst->getParent();
405 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000406 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000407 if (!DT->dominates(ContinueBB, UseBB)) {
408 AllNSW = false;
409 break;
410 }
411 }
412 }
413 if (!AllNSW)
414 return IVUser;
415
416 // Go for it...
417 IRBuilder<> Builder(IVUser);
418 Instruction *AddInst = dyn_cast<Instruction>(
419 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
420
421 // The caller expects the new add to have the same form as the intrinsic. The
422 // IV operand position must be the same.
423 assert((AddInst->getOpcode() == Instruction::Add &&
424 AddInst->getOperand(0) == II->getOperand(0)) &&
425 "Bad add instruction created from overflow intrinsic.");
426
427 AddVal->replaceAllUsesWith(AddInst);
428 DeadInsts.push_back(AddVal);
429 return AddInst;
430}
431
Sanjay Patel7777b502014-11-12 18:07:42 +0000432/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000433static void pushIVUsers(
434 Instruction *Def,
435 SmallPtrSet<Instruction*,16> &Simplified,
436 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
437
Chandler Carruthcdf47882014-03-09 03:16:01 +0000438 for (User *U : Def->users()) {
439 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000440
441 // Avoid infinite or exponential worklist processing.
442 // Also ensure unique worklist users.
443 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
444 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000445 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000446 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000447 }
448}
449
Sanjay Patel7777b502014-11-12 18:07:42 +0000450/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000451/// expression in terms of that IV.
452///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000453/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000454/// non-recursively when the operand is already known to be a simpleIVUser.
455///
456static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
457 if (!SE->isSCEVable(I->getType()))
458 return false;
459
460 // Get the symbolic expression for this instruction.
461 const SCEV *S = SE->getSCEV(I);
462
463 // Only consider affine recurrences.
464 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
465 if (AR && AR->getLoop() == L)
466 return true;
467
468 return false;
469}
470
Sanjay Patel7777b502014-11-12 18:07:42 +0000471/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000472/// of the specified induction variable. Each successive simplification may push
473/// more users which may themselves be candidates for simplification.
474///
475/// This algorithm does not require IVUsers analysis. Instead, it simplifies
476/// instructions in-place during analysis. Rather than rewriting induction
477/// variables bottom-up from their users, it transforms a chain of IVUsers
478/// top-down, updating the IR only when it encouters a clear optimization
479/// opportunitiy.
480///
481/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
482///
483void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000484 if (!SE->isSCEVable(CurrIV->getType()))
485 return;
486
Andrew Trick3ec331e2011-08-10 03:46:27 +0000487 // Instructions processed by SimplifyIndvar for CurrIV.
488 SmallPtrSet<Instruction*,16> Simplified;
489
490 // Use-def pairs if IV users waiting to be processed for CurrIV.
491 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
492
493 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
494 // called multiple times for the same LoopPhi. This is the proper thing to
495 // do for loop header phis that use each other.
496 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
497
498 while (!SimpleIVUsers.empty()) {
499 std::pair<Instruction*, Instruction*> UseOper =
500 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000501 Instruction *UseInst = UseOper.first;
502
Andrew Trick3ec331e2011-08-10 03:46:27 +0000503 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000504 if (UseInst == CurrIV) continue;
505
506 if (V && V->shouldSplitOverflowInstrinsics()) {
507 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
508 if (!UseInst)
509 continue;
510 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000511
Andrew Trick74664d52011-08-10 04:01:31 +0000512 Instruction *IVOperand = UseOper.second;
513 for (unsigned N = 0; IVOperand; ++N) {
514 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000515
Andrew Trick74664d52011-08-10 04:01:31 +0000516 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
517 if (!NewOper)
518 break; // done folding
519 IVOperand = dyn_cast<Instruction>(NewOper);
520 }
521 if (!IVOperand)
522 continue;
523
524 if (eliminateIVUser(UseOper.first, IVOperand)) {
525 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000526 continue;
527 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000528
529 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
530 if (isa<OverflowingBinaryOperator>(BO) &&
531 strengthenOverflowingOperation(BO, IVOperand)) {
532 // re-queue uses of the now modified binary operator and fall
533 // through to the checks that remain.
534 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
535 }
536 }
537
Andrew Trick3ec331e2011-08-10 03:46:27 +0000538 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
539 if (V && Cast) {
540 V->visitCast(Cast);
541 continue;
542 }
543 if (isSimpleIVUser(UseOper.first, L, SE)) {
544 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
545 }
546 }
547}
548
549namespace llvm {
550
David Blaikiea379b1812011-12-20 02:50:00 +0000551void IVVisitor::anchor() { }
552
Sanjay Patel7777b502014-11-12 18:07:42 +0000553/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000554/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Tricke629d002011-08-10 04:22:26 +0000555bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000556 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
557{
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000558 LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth24fd0292015-01-17 14:31:35 +0000559 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000560 SIV.simplifyUsers(CurrIV, V);
561 return SIV.hasChanged();
562}
563
Sanjay Patel7777b502014-11-12 18:07:42 +0000564/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000565/// loop. This does not actually change or add IVs.
Andrew Tricke629d002011-08-10 04:22:26 +0000566bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000567 SmallVectorImpl<WeakVH> &Dead) {
568 bool Changed = false;
569 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Tricke629d002011-08-10 04:22:26 +0000570 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000571 }
572 return Changed;
573}
574
Andrew Trick3ec331e2011-08-10 03:46:27 +0000575} // namespace llvm