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/Instructions.h"
19 #include "llvm/Analysis/Dominators.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/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
34 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
35 STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
36 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
37 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
40 /// SimplifyIndvar - This is a utility for simplifying induction variables
41 /// based on ScalarEvolution. It is the primary instrument of the
42 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
43 /// other loop passes that preserve SCEV.
44 class SimplifyIndvar {
49 IVUsers *IU; // NULL for DisableIVRewrite
50 const TargetData *TD; // May be NULL
52 SmallVectorImpl<WeakVH> &DeadInsts;
57 SimplifyIndvar(Loop *Loop, LPPassManager *LPM,
58 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
60 LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
61 SE(LPM->getAnalysisIfAvailable<ScalarEvolution>()),
63 TD(LPM->getAnalysisIfAvailable<TargetData>()),
66 assert(LI && SE && "IV simplification requires ScalarEvolution");
69 bool hasChanged() const { return Changed; }
71 /// Iteratively perform simplification on a worklist of users of the
72 /// specified induction variable. This is the top-level driver that applies
73 /// all simplicitions to users of an IV.
74 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = NULL);
76 bool foldIVUser(Instruction *UseInst, Instruction *IVOperand);
78 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
79 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
80 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
85 /// foldIVUser - 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.
87 bool SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
90 const SCEV *FoldedExpr = 0;
91 switch (UseInst->getOpcode()) {
94 case Instruction::UDiv:
95 case Instruction::LShr:
96 // We're only interested in the case where we know something about
97 // the numerator and have a constant denominator.
98 if (IVOperand != UseInst->getOperand(OperIdx) ||
99 !isa<ConstantInt>(UseInst->getOperand(1)))
102 // Attempt to fold a binary operator with constant operand.
103 // e.g. ((I + 1) >> 2) => I >> 2
104 if (IVOperand->getNumOperands() != 2 ||
105 !isa<ConstantInt>(IVOperand->getOperand(1)))
108 IVSrc = IVOperand->getOperand(0);
109 // IVSrc must be the (SCEVable) IV, since the other operand is const.
110 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
112 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
113 if (UseInst->getOpcode() == Instruction::LShr) {
114 // Get a constant for the divisor. See createSCEV.
115 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
116 if (D->getValue().uge(BitWidth))
119 D = ConstantInt::get(UseInst->getContext(),
120 APInt(BitWidth, 1).shl(D->getZExtValue()));
122 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
124 // We have something that might fold it's operand. Compare SCEVs.
125 if (!SE->isSCEVable(UseInst->getType()))
128 // Bypass the operand if SCEV can prove it has no effect.
129 if (SE->getSCEV(UseInst) != FoldedExpr)
132 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
133 << " -> " << *UseInst << '\n');
135 UseInst->setOperand(OperIdx, IVSrc);
136 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
140 if (IVOperand->use_empty())
141 DeadInsts.push_back(IVOperand);
145 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
146 /// comparisons against an induction variable.
147 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
148 unsigned IVOperIdx = 0;
149 ICmpInst::Predicate Pred = ICmp->getPredicate();
150 if (IVOperand != ICmp->getOperand(0)) {
152 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
154 Pred = ICmpInst::getSwappedPredicate(Pred);
157 // Get the SCEVs for the ICmp operands.
158 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
159 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
161 // Simplify unnecessary loops away.
162 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
163 S = SE->getSCEVAtScope(S, ICmpLoop);
164 X = SE->getSCEVAtScope(X, ICmpLoop);
166 // If the condition is always true or always false, replace it with
168 if (SE->isKnownPredicate(Pred, S, X))
169 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
170 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
171 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
175 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
178 DeadInsts.push_back(ICmp);
181 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
182 /// remainder operations operating on an induction variable.
183 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
186 // We're only interested in the case where we know something about
188 if (IVOperand != Rem->getOperand(0))
191 // Get the SCEVs for the ICmp operands.
192 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
193 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
195 // Simplify unnecessary loops away.
196 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
197 S = SE->getSCEVAtScope(S, ICmpLoop);
198 X = SE->getSCEVAtScope(X, ICmpLoop);
200 // i % n --> i if i is in [0,n).
201 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
202 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
204 Rem->replaceAllUsesWith(Rem->getOperand(0));
206 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
207 const SCEV *LessOne =
208 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
209 if (IsSigned && !SE->isKnownNonNegative(LessOne))
212 if (!SE->isKnownPredicate(IsSigned ?
213 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
217 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
218 Rem->getOperand(0), Rem->getOperand(1),
221 SelectInst::Create(ICmp,
222 ConstantInt::get(Rem->getType(), 0),
223 Rem->getOperand(0), "tmp", Rem);
224 Rem->replaceAllUsesWith(Sel);
227 // Inform IVUsers about the new users.
229 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
230 IU->AddUsersIfInteresting(I);
232 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
235 DeadInsts.push_back(Rem);
238 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
239 /// no observable side-effect given the range of IV values.
240 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
241 Instruction *IVOperand) {
242 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
243 eliminateIVComparison(ICmp, IVOperand);
246 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
247 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
248 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
249 eliminateIVRemainder(Rem, IVOperand, IsSigned);
254 // Eliminate any operation that SCEV can prove is an identity function.
255 if (!SE->isSCEVable(UseInst->getType()) ||
256 (UseInst->getType() != IVOperand->getType()) ||
257 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
260 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
262 UseInst->replaceAllUsesWith(IVOperand);
265 DeadInsts.push_back(UseInst);
269 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
271 static void pushIVUsers(
273 SmallPtrSet<Instruction*,16> &Simplified,
274 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
276 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
278 Instruction *User = cast<Instruction>(*UI);
280 // Avoid infinite or exponential worklist processing.
281 // Also ensure unique worklist users.
282 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
284 if (User != Def && Simplified.insert(User))
285 SimpleIVUsers.push_back(std::make_pair(User, Def));
289 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
290 /// expression in terms of that IV.
292 /// This is similar to IVUsers' isInsteresting() but processes each instruction
293 /// non-recursively when the operand is already known to be a simpleIVUser.
295 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
296 if (!SE->isSCEVable(I->getType()))
299 // Get the symbolic expression for this instruction.
300 const SCEV *S = SE->getSCEV(I);
302 // Only consider affine recurrences.
303 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
304 if (AR && AR->getLoop() == L)
310 /// simplifyUsers - Iteratively perform simplification on a worklist of users
311 /// of the specified induction variable. Each successive simplification may push
312 /// more users which may themselves be candidates for simplification.
314 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
315 /// instructions in-place during analysis. Rather than rewriting induction
316 /// variables bottom-up from their users, it transforms a chain of IVUsers
317 /// top-down, updating the IR only when it encouters a clear optimization
320 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
322 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
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 foldIVUser(UseOper.first, UseOper.second);
342 if (eliminateIVUser(UseOper.first, UseOper.second)) {
343 pushIVUsers(UseOper.second, Simplified, SimpleIVUsers);
346 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
351 if (isSimpleIVUser(UseOper.first, L, SE)) {
352 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
359 /// simplifyUsersOfIV - Simplify instructions that use this induction variable
360 /// by using ScalarEvolution to analyze the IV's recurrence.
361 bool simplifyUsersOfIV(PHINode *CurrIV, LPPassManager *LPM,
362 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
364 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
365 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), LPM, Dead);
366 SIV.simplifyUsers(CurrIV, V);
367 return SIV.hasChanged();
370 /// simplifyLoopIVs - Simplify users of induction variables within this
371 /// loop. This does not actually change or add IVs.
372 bool simplifyLoopIVs(Loop *L, LPPassManager *LPM,
373 SmallVectorImpl<WeakVH> &Dead) {
374 bool Changed = false;
375 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
376 Changed |= simplifyUsersOfIV(cast<PHINode>(I), LPM, Dead);
381 /// simplifyIVUsers - Perform simplification on instructions recorded by the
384 /// This is the old approach to IV simplification to be replaced by
386 bool simplifyIVUsers(IVUsers *IU, LPPassManager *LPM,
387 SmallVectorImpl<WeakVH> &Dead) {
388 SimplifyIndvar SIV(IU->getLoop(), LPM, Dead);
390 // Each round of simplification involves a round of eliminating operations
391 // followed by a round of widening IVs. A single IVUsers worklist is used
392 // across all rounds. The inner loop advances the user. If widening exposes
393 // more uses, then another pass through the outer loop is triggered.
394 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
395 Instruction *UseInst = I->getUser();
396 Value *IVOperand = I->getOperandValToReplace();
398 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
399 SIV.eliminateIVComparison(ICmp, IVOperand);
402 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
403 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
404 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
405 SIV.eliminateIVRemainder(Rem, IVOperand, IsSigned);
410 return SIV.hasChanged();