1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/IVUsers.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
35 #define DEBUG_TYPE "indvars"
37 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
38 STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
39 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
40 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
43 /// This is a utility for simplifying induction variables
44 /// 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 {
51 const DataLayout *DL; // May be NULL
53 SmallVectorImpl<WeakVH> &DeadInsts;
58 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LoopInfo *LI,
59 const DataLayout *DL, SmallVectorImpl<WeakVH> &Dead,
60 IVUsers *IVU = nullptr)
61 : L(Loop), LI(LI), SE(SE), DL(DL), DeadInsts(Dead), Changed(false) {
62 assert(LI && "IV simplification requires LoopInfo");
65 bool hasChanged() const { return Changed; }
67 /// Iteratively perform simplification on a worklist of users of the
68 /// specified induction variable. This is the top-level driver that applies
69 /// all simplicitions to users of an IV.
70 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
72 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
74 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
75 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
76 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
78 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
80 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
81 const DominatorTree *DT);
85 /// Fold an IV operand into its use. This removes increments of an
86 /// aligned IV when used by a instruction that ignores the low bits.
88 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
90 /// Return the operand of IVOperand for this induction variable if IVOperand can
91 /// be folded (in case more folding opportunities have been exposed).
92 /// Otherwise return null.
93 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
94 Value *IVSrc = nullptr;
96 const SCEV *FoldedExpr = nullptr;
97 switch (UseInst->getOpcode()) {
100 case Instruction::UDiv:
101 case Instruction::LShr:
102 // We're only interested in the case where we know something about
103 // the numerator and have a constant denominator.
104 if (IVOperand != UseInst->getOperand(OperIdx) ||
105 !isa<ConstantInt>(UseInst->getOperand(1)))
108 // Attempt to fold a binary operator with constant operand.
109 // e.g. ((I + 1) >> 2) => I >> 2
110 if (!isa<BinaryOperator>(IVOperand)
111 || !isa<ConstantInt>(IVOperand->getOperand(1)))
114 IVSrc = IVOperand->getOperand(0);
115 // IVSrc must be the (SCEVable) IV, since the other operand is const.
116 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
118 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
119 if (UseInst->getOpcode() == Instruction::LShr) {
120 // Get a constant for the divisor. See createSCEV.
121 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
122 if (D->getValue().uge(BitWidth))
125 D = ConstantInt::get(UseInst->getContext(),
126 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
128 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
130 // We have something that might fold it's operand. Compare SCEVs.
131 if (!SE->isSCEVable(UseInst->getType()))
134 // Bypass the operand if SCEV can prove it has no effect.
135 if (SE->getSCEV(UseInst) != FoldedExpr)
138 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
139 << " -> " << *UseInst << '\n');
141 UseInst->setOperand(OperIdx, IVSrc);
142 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
146 if (IVOperand->use_empty())
147 DeadInsts.push_back(IVOperand);
151 /// SimplifyIVUsers helper for eliminating useless
152 /// comparisons against an induction variable.
153 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
154 unsigned IVOperIdx = 0;
155 ICmpInst::Predicate Pred = ICmp->getPredicate();
156 if (IVOperand != ICmp->getOperand(0)) {
158 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
160 Pred = ICmpInst::getSwappedPredicate(Pred);
163 // Get the SCEVs for the ICmp operands.
164 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
165 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
167 // Simplify unnecessary loops away.
168 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
169 S = SE->getSCEVAtScope(S, ICmpLoop);
170 X = SE->getSCEVAtScope(X, ICmpLoop);
172 // If the condition is always true or always false, replace it with
174 if (SE->isKnownPredicate(Pred, S, X))
175 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
176 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
177 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
181 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
184 DeadInsts.push_back(ICmp);
187 /// SimplifyIVUsers helper for eliminating useless
188 /// remainder operations operating on an induction variable.
189 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
192 // We're only interested in the case where we know something about
194 if (IVOperand != Rem->getOperand(0))
197 // Get the SCEVs for the ICmp operands.
198 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
199 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
201 // Simplify unnecessary loops away.
202 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
203 S = SE->getSCEVAtScope(S, ICmpLoop);
204 X = SE->getSCEVAtScope(X, ICmpLoop);
206 // i % n --> i if i is in [0,n).
207 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
208 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
210 Rem->replaceAllUsesWith(Rem->getOperand(0));
212 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
213 const SCEV *LessOne =
214 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
215 if (IsSigned && !SE->isKnownNonNegative(LessOne))
218 if (!SE->isKnownPredicate(IsSigned ?
219 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
223 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
224 Rem->getOperand(0), Rem->getOperand(1));
226 SelectInst::Create(ICmp,
227 ConstantInt::get(Rem->getType(), 0),
228 Rem->getOperand(0), "tmp", Rem);
229 Rem->replaceAllUsesWith(Sel);
232 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
235 DeadInsts.push_back(Rem);
238 /// Eliminate an operation that consumes a simple IV and has
239 /// no observable side-effect given the range of IV values.
240 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
241 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
242 Instruction *IVOperand) {
243 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
244 eliminateIVComparison(ICmp, IVOperand);
247 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
248 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
249 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
250 eliminateIVRemainder(Rem, IVOperand, IsSigned);
255 // Eliminate any operation that SCEV can prove is an identity function.
256 if (!SE->isSCEVable(UseInst->getType()) ||
257 (UseInst->getType() != IVOperand->getType()) ||
258 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
261 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
263 UseInst->replaceAllUsesWith(IVOperand);
266 DeadInsts.push_back(UseInst);
270 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
271 /// unsigned-overflow. Returns true if anything changed, false otherwise.
272 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
275 // Currently we only handle instructions of the form "add <indvar> <value>"
276 unsigned Op = BO->getOpcode();
277 if (Op != Instruction::Add)
280 // If BO is already both nuw and nsw then there is nothing left to do
281 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
284 IntegerType *IT = cast<IntegerType>(IVOperand->getType());
285 Value *OtherOperand = nullptr;
286 if (BO->getOperand(0) == IVOperand) {
287 OtherOperand = BO->getOperand(1);
289 assert(BO->getOperand(1) == IVOperand && "only other use!");
290 OtherOperand = BO->getOperand(0);
293 bool Changed = false;
294 const SCEV *OtherOpSCEV = SE->getSCEV(OtherOperand);
295 if (OtherOpSCEV == SE->getCouldNotCompute())
298 const SCEV *IVOpSCEV = SE->getSCEV(IVOperand);
299 const SCEV *ZeroSCEV = SE->getConstant(IVOpSCEV->getType(), 0);
301 if (!BO->hasNoSignedWrap()) {
302 // Upgrade the add to an "add nsw" if we can prove that it will never
303 // sign-overflow or sign-underflow.
305 const SCEV *SignedMax =
306 SE->getConstant(APInt::getSignedMaxValue(IT->getBitWidth()));
307 const SCEV *SignedMin =
308 SE->getConstant(APInt::getSignedMinValue(IT->getBitWidth()));
310 // The addition "IVOperand + OtherOp" does not sign-overflow if the result
311 // is sign-representable in 2's complement in the given bit-width.
313 // If OtherOp is SLT 0, then for an IVOperand in [SignedMin - OtherOp,
314 // SignedMax], "IVOperand + OtherOp" is in [SignedMin, SignedMax + OtherOp].
315 // Everything in [SignedMin, SignedMax + OtherOp] is representable since
316 // SignedMax + OtherOp is at least -1.
318 // If OtherOp is SGE 0, then for an IVOperand in [SignedMin, SignedMax -
319 // OtherOp], "IVOperand + OtherOp" is in [SignedMin + OtherOp, SignedMax].
320 // Everything in [SignedMin + OtherOp, SignedMax] is representable since
321 // SignedMin + OtherOp is at most -1.
323 // It follows that for all values of IVOperand in [SignedMin - smin(0,
324 // OtherOp), SignedMax - smax(0, OtherOp)] the result of the add is
325 // representable (i.e. there is no sign-overflow).
327 const SCEV *UpperDelta = SE->getSMaxExpr(ZeroSCEV, OtherOpSCEV);
328 const SCEV *UpperLimit = SE->getMinusSCEV(SignedMax, UpperDelta);
330 bool NeverSignedOverflows =
331 SE->isKnownPredicate(ICmpInst::ICMP_SLE, IVOpSCEV, UpperLimit);
333 if (NeverSignedOverflows) {
334 const SCEV *LowerDelta = SE->getSMinExpr(ZeroSCEV, OtherOpSCEV);
335 const SCEV *LowerLimit = SE->getMinusSCEV(SignedMin, LowerDelta);
337 bool NeverSignedUnderflows =
338 SE->isKnownPredicate(ICmpInst::ICMP_SGE, IVOpSCEV, LowerLimit);
339 if (NeverSignedUnderflows) {
340 BO->setHasNoSignedWrap(true);
346 if (!BO->hasNoUnsignedWrap()) {
347 // Upgrade the add computing "IVOperand + OtherOp" to an "add nuw" if we can
348 // prove that it will never unsigned-overflow (i.e. the result will always
349 // be representable in the given bit-width).
351 // "IVOperand + OtherOp" is unsigned-representable in 2's complement iff it
352 // does not produce a carry. "IVOperand + OtherOp" produces no carry iff
353 // IVOperand ULE (UnsignedMax - OtherOp).
355 const SCEV *UnsignedMax =
356 SE->getConstant(APInt::getMaxValue(IT->getBitWidth()));
357 const SCEV *UpperLimit = SE->getMinusSCEV(UnsignedMax, OtherOpSCEV);
359 bool NeverUnsignedOverflows =
360 SE->isKnownPredicate(ICmpInst::ICMP_ULE, IVOpSCEV, UpperLimit);
362 if (NeverUnsignedOverflows) {
363 BO->setHasNoUnsignedWrap(true);
371 /// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
372 /// analysis and optimization.
374 /// \return A new value representing the non-overflowing add if possible,
375 /// otherwise return the original value.
376 Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
377 const DominatorTree *DT) {
378 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
379 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
382 // Find a branch guarded by the overflow check.
383 BranchInst *Branch = nullptr;
384 Instruction *AddVal = nullptr;
385 for (User *U : II->users()) {
386 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
387 if (ExtractInst->getNumIndices() != 1)
389 if (ExtractInst->getIndices()[0] == 0)
390 AddVal = ExtractInst;
391 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
392 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
395 if (!AddVal || !Branch)
398 BasicBlock *ContinueBB = Branch->getSuccessor(1);
399 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
402 // Check if all users of the add are provably NSW.
404 for (Use &U : AddVal->uses()) {
405 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
406 BasicBlock *UseBB = UseInst->getParent();
407 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
408 UseBB = PHI->getIncomingBlock(U);
409 if (!DT->dominates(ContinueBB, UseBB)) {
419 IRBuilder<> Builder(IVUser);
420 Instruction *AddInst = dyn_cast<Instruction>(
421 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
423 // The caller expects the new add to have the same form as the intrinsic. The
424 // IV operand position must be the same.
425 assert((AddInst->getOpcode() == Instruction::Add &&
426 AddInst->getOperand(0) == II->getOperand(0)) &&
427 "Bad add instruction created from overflow intrinsic.");
429 AddVal->replaceAllUsesWith(AddInst);
430 DeadInsts.push_back(AddVal);
434 /// Add all uses of Def to the current IV's worklist.
435 static void pushIVUsers(
437 SmallPtrSet<Instruction*,16> &Simplified,
438 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
440 for (User *U : Def->users()) {
441 Instruction *UI = cast<Instruction>(U);
443 // Avoid infinite or exponential worklist processing.
444 // Also ensure unique worklist users.
445 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
447 if (UI != Def && Simplified.insert(UI).second)
448 SimpleIVUsers.push_back(std::make_pair(UI, Def));
452 /// Return true if this instruction generates a simple SCEV
453 /// expression in terms of that IV.
455 /// This is similar to IVUsers' isInteresting() but processes each instruction
456 /// non-recursively when the operand is already known to be a simpleIVUser.
458 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
459 if (!SE->isSCEVable(I->getType()))
462 // Get the symbolic expression for this instruction.
463 const SCEV *S = SE->getSCEV(I);
465 // Only consider affine recurrences.
466 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
467 if (AR && AR->getLoop() == L)
473 /// Iteratively perform simplification on a worklist of users
474 /// of the specified induction variable. Each successive simplification may push
475 /// more users which may themselves be candidates for simplification.
477 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
478 /// instructions in-place during analysis. Rather than rewriting induction
479 /// variables bottom-up from their users, it transforms a chain of IVUsers
480 /// top-down, updating the IR only when it encouters a clear optimization
483 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
485 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
486 if (!SE->isSCEVable(CurrIV->getType()))
489 // Instructions processed by SimplifyIndvar for CurrIV.
490 SmallPtrSet<Instruction*,16> Simplified;
492 // Use-def pairs if IV users waiting to be processed for CurrIV.
493 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
495 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
496 // called multiple times for the same LoopPhi. This is the proper thing to
497 // do for loop header phis that use each other.
498 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
500 while (!SimpleIVUsers.empty()) {
501 std::pair<Instruction*, Instruction*> UseOper =
502 SimpleIVUsers.pop_back_val();
503 Instruction *UseInst = UseOper.first;
505 // Bypass back edges to avoid extra work.
506 if (UseInst == CurrIV) continue;
508 if (V && V->shouldSplitOverflowInstrinsics()) {
509 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
514 Instruction *IVOperand = UseOper.second;
515 for (unsigned N = 0; IVOperand; ++N) {
516 assert(N <= Simplified.size() && "runaway iteration");
518 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
520 break; // done folding
521 IVOperand = dyn_cast<Instruction>(NewOper);
526 if (eliminateIVUser(UseOper.first, IVOperand)) {
527 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
531 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
532 if (isa<OverflowingBinaryOperator>(BO) &&
533 strengthenOverflowingOperation(BO, IVOperand)) {
534 // re-queue uses of the now modified binary operator and fall
535 // through to the checks that remain.
536 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
540 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
545 if (isSimpleIVUser(UseOper.first, L, SE)) {
546 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
553 void IVVisitor::anchor() { }
555 /// Simplify instructions that use this induction variable
556 /// by using ScalarEvolution to analyze the IV's recurrence.
557 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
558 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
560 DataLayoutPass *DLP = LPM->getAnalysisIfAvailable<DataLayoutPass>();
561 LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
562 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI,
563 DLP ? &DLP->getDataLayout() : nullptr, Dead);
564 SIV.simplifyUsers(CurrIV, V);
565 return SIV.hasChanged();
568 /// Simplify users of induction variables within this
569 /// loop. This does not actually change or add IVs.
570 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
571 SmallVectorImpl<WeakVH> &Dead) {
572 bool Changed = false;
573 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
574 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);