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 #define DEBUG_TYPE "indvars"
18 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/IVUsers.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
33 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
34 STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
35 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
36 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
39 /// SimplifyIndvar - This is a utility for simplifying induction variables
40 /// based on ScalarEvolution. It is the primary instrument of the
41 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
42 /// other loop passes that preserve SCEV.
43 class SimplifyIndvar {
47 const DataLayout *TD; // May be NULL
49 SmallVectorImpl<WeakVH> &DeadInsts;
54 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
55 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
57 LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
59 TD(LPM->getAnalysisIfAvailable<DataLayout>()),
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 = NULL);
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,
81 /// foldIVUser - Fold an IV operand into its use. This removes increments of an
82 /// aligned IV when used by a instruction that ignores the low bits.
84 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
86 /// Return the operand of IVOperand for this induction variable if IVOperand can
87 /// be folded (in case more folding opportunities have been exposed).
88 /// Otherwise return null.
89 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
92 const SCEV *FoldedExpr = 0;
93 switch (UseInst->getOpcode()) {
96 case Instruction::UDiv:
97 case Instruction::LShr:
98 // We're only interested in the case where we know something about
99 // the numerator and have a constant denominator.
100 if (IVOperand != UseInst->getOperand(OperIdx) ||
101 !isa<ConstantInt>(UseInst->getOperand(1)))
104 // Attempt to fold a binary operator with constant operand.
105 // e.g. ((I + 1) >> 2) => I >> 2
106 if (!isa<BinaryOperator>(IVOperand)
107 || !isa<ConstantInt>(IVOperand->getOperand(1)))
110 IVSrc = IVOperand->getOperand(0);
111 // IVSrc must be the (SCEVable) IV, since the other operand is const.
112 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
114 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
115 if (UseInst->getOpcode() == Instruction::LShr) {
116 // Get a constant for the divisor. See createSCEV.
117 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
118 if (D->getValue().uge(BitWidth))
121 D = ConstantInt::get(UseInst->getContext(),
122 APInt(BitWidth, 1).shl(D->getZExtValue()));
124 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
126 // We have something that might fold it's operand. Compare SCEVs.
127 if (!SE->isSCEVable(UseInst->getType()))
130 // Bypass the operand if SCEV can prove it has no effect.
131 if (SE->getSCEV(UseInst) != FoldedExpr)
134 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
135 << " -> " << *UseInst << '\n');
137 UseInst->setOperand(OperIdx, IVSrc);
138 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
142 if (IVOperand->use_empty())
143 DeadInsts.push_back(IVOperand);
147 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
148 /// comparisons against an induction variable.
149 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
150 unsigned IVOperIdx = 0;
151 ICmpInst::Predicate Pred = ICmp->getPredicate();
152 if (IVOperand != ICmp->getOperand(0)) {
154 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
156 Pred = ICmpInst::getSwappedPredicate(Pred);
159 // Get the SCEVs for the ICmp operands.
160 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
161 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
163 // Simplify unnecessary loops away.
164 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
165 S = SE->getSCEVAtScope(S, ICmpLoop);
166 X = SE->getSCEVAtScope(X, ICmpLoop);
168 // If the condition is always true or always false, replace it with
170 if (SE->isKnownPredicate(Pred, S, X))
171 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
172 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
173 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
177 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
180 DeadInsts.push_back(ICmp);
183 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
184 /// remainder operations operating on an induction variable.
185 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
188 // We're only interested in the case where we know something about
190 if (IVOperand != Rem->getOperand(0))
193 // Get the SCEVs for the ICmp operands.
194 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
195 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
197 // Simplify unnecessary loops away.
198 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
199 S = SE->getSCEVAtScope(S, ICmpLoop);
200 X = SE->getSCEVAtScope(X, ICmpLoop);
202 // i % n --> i if i is in [0,n).
203 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
204 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
206 Rem->replaceAllUsesWith(Rem->getOperand(0));
208 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
209 const SCEV *LessOne =
210 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
211 if (IsSigned && !SE->isKnownNonNegative(LessOne))
214 if (!SE->isKnownPredicate(IsSigned ?
215 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
219 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
220 Rem->getOperand(0), Rem->getOperand(1));
222 SelectInst::Create(ICmp,
223 ConstantInt::get(Rem->getType(), 0),
224 Rem->getOperand(0), "tmp", Rem);
225 Rem->replaceAllUsesWith(Sel);
228 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
231 DeadInsts.push_back(Rem);
234 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
235 /// no observable side-effect given the range of IV values.
236 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
237 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
238 Instruction *IVOperand) {
239 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
240 eliminateIVComparison(ICmp, IVOperand);
243 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
244 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
245 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
246 eliminateIVRemainder(Rem, IVOperand, IsSigned);
251 // Eliminate any operation that SCEV can prove is an identity function.
252 if (!SE->isSCEVable(UseInst->getType()) ||
253 (UseInst->getType() != IVOperand->getType()) ||
254 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
257 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
259 UseInst->replaceAllUsesWith(IVOperand);
262 DeadInsts.push_back(UseInst);
266 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
268 static void pushIVUsers(
270 SmallPtrSet<Instruction*,16> &Simplified,
271 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
273 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
275 Instruction *User = cast<Instruction>(*UI);
277 // Avoid infinite or exponential worklist processing.
278 // Also ensure unique worklist users.
279 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
281 if (User != Def && Simplified.insert(User))
282 SimpleIVUsers.push_back(std::make_pair(User, Def));
286 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
287 /// expression in terms of that IV.
289 /// This is similar to IVUsers' isInteresting() but processes each instruction
290 /// non-recursively when the operand is already known to be a simpleIVUser.
292 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
293 if (!SE->isSCEVable(I->getType()))
296 // Get the symbolic expression for this instruction.
297 const SCEV *S = SE->getSCEV(I);
299 // Only consider affine recurrences.
300 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
301 if (AR && AR->getLoop() == L)
307 /// simplifyUsers - Iteratively perform simplification on a worklist of users
308 /// of the specified induction variable. Each successive simplification may push
309 /// more users which may themselves be candidates for simplification.
311 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
312 /// instructions in-place during analysis. Rather than rewriting induction
313 /// variables bottom-up from their users, it transforms a chain of IVUsers
314 /// top-down, updating the IR only when it encouters a clear optimization
317 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
319 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
320 if (!SE->isSCEVable(CurrIV->getType()))
323 // Instructions processed by SimplifyIndvar for CurrIV.
324 SmallPtrSet<Instruction*,16> Simplified;
326 // Use-def pairs if IV users waiting to be processed for CurrIV.
327 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
329 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
330 // called multiple times for the same LoopPhi. This is the proper thing to
331 // do for loop header phis that use each other.
332 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
334 while (!SimpleIVUsers.empty()) {
335 std::pair<Instruction*, Instruction*> UseOper =
336 SimpleIVUsers.pop_back_val();
337 // Bypass back edges to avoid extra work.
338 if (UseOper.first == CurrIV) continue;
340 Instruction *IVOperand = UseOper.second;
341 for (unsigned N = 0; IVOperand; ++N) {
342 assert(N <= Simplified.size() && "runaway iteration");
344 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
346 break; // done folding
347 IVOperand = dyn_cast<Instruction>(NewOper);
352 if (eliminateIVUser(UseOper.first, IVOperand)) {
353 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
356 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
361 if (isSimpleIVUser(UseOper.first, L, SE)) {
362 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
369 void IVVisitor::anchor() { }
371 /// simplifyUsersOfIV - Simplify instructions that use this induction variable
372 /// by using ScalarEvolution to analyze the IV's recurrence.
373 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
374 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
376 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
377 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
378 SIV.simplifyUsers(CurrIV, V);
379 return SIV.hasChanged();
382 /// simplifyLoopIVs - Simplify users of induction variables within this
383 /// loop. This does not actually change or add IVs.
384 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
385 SmallVectorImpl<WeakVH> &Dead) {
386 bool Changed = false;
387 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
388 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);