blob: 41c207c3d5cb9c428fd93269ac995b647b3a2998 [file] [log] [blame]
Andrew Trick4b4bb712011-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
16#define DEBUG_TYPE "indvars"
17
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Utils/SimplifyIndVar.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Andrew Trick4b4bb712011-08-10 03:46:27 +000021#include "llvm/Analysis/IVUsers.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/LoopPass.h"
24#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Instructions.h"
Andrew Trick4b4bb712011-08-10 03:46:27 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Andrew Trick4b4bb712011-08-10 03:46:27 +000030
31using namespace llvm;
32
33STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
34STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
35STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
36STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
37
38namespace {
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 {
44 Loop *L;
45 LoopInfo *LI;
Andrew Trick4b4bb712011-08-10 03:46:27 +000046 ScalarEvolution *SE;
Micah Villmow3574eca2012-10-08 16:38:25 +000047 const DataLayout *TD; // May be NULL
Andrew Trick4b4bb712011-08-10 03:46:27 +000048
49 SmallVectorImpl<WeakVH> &DeadInsts;
50
51 bool Changed;
52
53 public:
Andrew Trickbddb7f82011-08-10 04:22:26 +000054 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +000055 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
56 L(Loop),
57 LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
Andrew Trickbddb7f82011-08-10 04:22:26 +000058 SE(SE),
Micah Villmow3574eca2012-10-08 16:38:25 +000059 TD(LPM->getAnalysisIfAvailable<DataLayout>()),
Andrew Trick4b4bb712011-08-10 03:46:27 +000060 DeadInsts(Dead),
61 Changed(false) {
Andrew Trickbddb7f82011-08-10 04:22:26 +000062 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick4b4bb712011-08-10 03:46:27 +000063 }
64
65 bool hasChanged() const { return Changed; }
66
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);
71
Andrew Trickea23daa2011-08-10 04:01:31 +000072 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick4b4bb712011-08-10 03:46:27 +000073
74 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
75 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
76 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
77 bool IsSigned);
78 };
79}
80
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.
Andrew Trickea23daa2011-08-10 04:01:31 +000083///
Andrew Trick24f48ec2011-09-19 17:54:39 +000084/// IVOperand is guaranteed SCEVable, but UseInst may not be.
85///
Andrew Trickea23daa2011-08-10 04:01:31 +000086/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick7cb3dcb2011-08-10 18:07:05 +000087/// be folded (in case more folding opportunities have been exposed).
Andrew Trickea23daa2011-08-10 04:01:31 +000088/// Otherwise return null.
89Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Andrew Trick4b4bb712011-08-10 03:46:27 +000090 Value *IVSrc = 0;
91 unsigned OperIdx = 0;
92 const SCEV *FoldedExpr = 0;
93 switch (UseInst->getOpcode()) {
94 default:
Andrew Trickea23daa2011-08-10 04:01:31 +000095 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +000096 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)))
Andrew Trickea23daa2011-08-10 04:01:31 +0000102 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000103
104 // Attempt to fold a binary operator with constant operand.
105 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick4f305242011-11-17 23:36:35 +0000106 if (!isa<BinaryOperator>(IVOperand)
107 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Andrew Trickea23daa2011-08-10 04:01:31 +0000108 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000109
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");
113
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))
Andrew Trickea23daa2011-08-10 04:01:31 +0000119 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000120
121 D = ConstantInt::get(UseInst->getContext(),
122 APInt(BitWidth, 1).shl(D->getZExtValue()));
123 }
124 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
125 }
126 // We have something that might fold it's operand. Compare SCEVs.
127 if (!SE->isSCEVable(UseInst->getType()))
Andrew Trickea23daa2011-08-10 04:01:31 +0000128 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000129
130 // Bypass the operand if SCEV can prove it has no effect.
131 if (SE->getSCEV(UseInst) != FoldedExpr)
Andrew Trickea23daa2011-08-10 04:01:31 +0000132 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000133
134 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
135 << " -> " << *UseInst << '\n');
136
137 UseInst->setOperand(OperIdx, IVSrc);
138 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
139
140 ++NumElimOperand;
141 Changed = true;
142 if (IVOperand->use_empty())
143 DeadInsts.push_back(IVOperand);
Andrew Trickea23daa2011-08-10 04:01:31 +0000144 return IVSrc;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000145}
146
147/// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
148/// comparisons against an induction variable.
149void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
150 unsigned IVOperIdx = 0;
151 ICmpInst::Predicate Pred = ICmp->getPredicate();
152 if (IVOperand != ICmp->getOperand(0)) {
153 // Swapped
154 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
155 IVOperIdx = 1;
156 Pred = ICmpInst::getSwappedPredicate(Pred);
157 }
158
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));
162
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);
167
168 // If the condition is always true or always false, replace it with
169 // a constant value.
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()));
174 else
175 return;
176
177 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
178 ++NumElimCmp;
179 Changed = true;
180 DeadInsts.push_back(ICmp);
181}
182
183/// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
184/// remainder operations operating on an induction variable.
185void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
186 Value *IVOperand,
187 bool IsSigned) {
188 // We're only interested in the case where we know something about
189 // the numerator.
190 if (IVOperand != Rem->getOperand(0))
191 return;
192
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));
196
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);
201
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,
205 S, X))
206 Rem->replaceAllUsesWith(Rem->getOperand(0));
207 else {
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))
212 return;
213
214 if (!SE->isKnownPredicate(IsSigned ?
215 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
216 LessOne, X))
217 return;
218
219 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000220 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick4b4bb712011-08-10 03:46:27 +0000221 SelectInst *Sel =
222 SelectInst::Create(ICmp,
223 ConstantInt::get(Rem->getType(), 0),
224 Rem->getOperand(0), "tmp", Rem);
225 Rem->replaceAllUsesWith(Sel);
226 }
227
Andrew Trick4b4bb712011-08-10 03:46:27 +0000228 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
229 ++NumElimRem;
230 Changed = true;
231 DeadInsts.push_back(Rem);
232}
233
234/// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
235/// no observable side-effect given the range of IV values.
Andrew Trick24f48ec2011-09-19 17:54:39 +0000236/// IVOperand is guaranteed SCEVable, but UseInst may not be.
Andrew Trick4b4bb712011-08-10 03:46:27 +0000237bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
238 Instruction *IVOperand) {
239 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
240 eliminateIVComparison(ICmp, IVOperand);
241 return true;
242 }
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);
247 return true;
248 }
249 }
250
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)))
255 return false;
256
257 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
258
259 UseInst->replaceAllUsesWith(IVOperand);
260 ++NumElimIdentity;
261 Changed = true;
262 DeadInsts.push_back(UseInst);
263 return true;
264}
265
266/// pushIVUsers - Add all uses of Def to the current IV's worklist.
267///
268static void pushIVUsers(
269 Instruction *Def,
270 SmallPtrSet<Instruction*,16> &Simplified,
271 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
272
273 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
274 UI != E; ++UI) {
275 Instruction *User = cast<Instruction>(*UI);
276
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
280 // self edges first.
281 if (User != Def && Simplified.insert(User))
282 SimpleIVUsers.push_back(std::make_pair(User, Def));
283 }
284}
285
286/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
287/// expression in terms of that IV.
288///
Andrew Trick7cb3dcb2011-08-10 18:07:05 +0000289/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick4b4bb712011-08-10 03:46:27 +0000290/// non-recursively when the operand is already known to be a simpleIVUser.
291///
292static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
293 if (!SE->isSCEVable(I->getType()))
294 return false;
295
296 // Get the symbolic expression for this instruction.
297 const SCEV *S = SE->getSCEV(I);
298
299 // Only consider affine recurrences.
300 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
301 if (AR && AR->getLoop() == L)
302 return true;
303
304 return false;
305}
306
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.
310///
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
315/// opportunitiy.
316///
317/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
318///
319void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick24f48ec2011-09-19 17:54:39 +0000320 if (!SE->isSCEVable(CurrIV->getType()))
321 return;
322
Andrew Trick4b4bb712011-08-10 03:46:27 +0000323 // Instructions processed by SimplifyIndvar for CurrIV.
324 SmallPtrSet<Instruction*,16> Simplified;
325
326 // Use-def pairs if IV users waiting to be processed for CurrIV.
327 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
328
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);
333
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;
339
Andrew Trickea23daa2011-08-10 04:01:31 +0000340 Instruction *IVOperand = UseOper.second;
341 for (unsigned N = 0; IVOperand; ++N) {
342 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick4b4bb712011-08-10 03:46:27 +0000343
Andrew Trickea23daa2011-08-10 04:01:31 +0000344 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
345 if (!NewOper)
346 break; // done folding
347 IVOperand = dyn_cast<Instruction>(NewOper);
348 }
349 if (!IVOperand)
350 continue;
351
352 if (eliminateIVUser(UseOper.first, IVOperand)) {
353 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000354 continue;
355 }
356 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
357 if (V && Cast) {
358 V->visitCast(Cast);
359 continue;
360 }
361 if (isSimpleIVUser(UseOper.first, L, SE)) {
362 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
363 }
364 }
365}
366
367namespace llvm {
368
David Blaikie2d24e2a2011-12-20 02:50:00 +0000369void IVVisitor::anchor() { }
370
Andrew Trick4b4bb712011-08-10 03:46:27 +0000371/// simplifyUsersOfIV - Simplify instructions that use this induction variable
372/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Trickbddb7f82011-08-10 04:22:26 +0000373bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +0000374 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
375{
376 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
Andrew Trickbddb7f82011-08-10 04:22:26 +0000377 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000378 SIV.simplifyUsers(CurrIV, V);
379 return SIV.hasChanged();
380}
381
382/// simplifyLoopIVs - Simplify users of induction variables within this
383/// loop. This does not actually change or add IVs.
Andrew Trickbddb7f82011-08-10 04:22:26 +0000384bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +0000385 SmallVectorImpl<WeakVH> &Dead) {
386 bool Changed = false;
387 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Trickbddb7f82011-08-10 04:22:26 +0000388 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000389 }
390 return Changed;
391}
392
Andrew Trick4b4bb712011-08-10 03:46:27 +0000393} // namespace llvm