blob: 5ee1eb189799faefc37e15146d51576392d4936c [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
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"
31
32using namespace llvm;
33
34STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
35STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
36STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
37STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
38
39namespace {
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 {
45 Loop *L;
46 LoopInfo *LI;
47 DominatorTree *DT;
48 ScalarEvolution *SE;
49 IVUsers *IU; // NULL for DisableIVRewrite
50 const TargetData *TD; // May be NULL
51
52 SmallVectorImpl<WeakVH> &DeadInsts;
53
54 bool Changed;
55
56 public:
Andrew Trickbddb7f82011-08-10 04:22:26 +000057 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +000058 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
59 L(Loop),
60 LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
Andrew Trickbddb7f82011-08-10 04:22:26 +000061 SE(SE),
Andrew Trick4b4bb712011-08-10 03:46:27 +000062 IU(IVU),
63 TD(LPM->getAnalysisIfAvailable<TargetData>()),
64 DeadInsts(Dead),
65 Changed(false) {
Andrew Trickbddb7f82011-08-10 04:22:26 +000066 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick4b4bb712011-08-10 03:46:27 +000067 }
68
69 bool hasChanged() const { return Changed; }
70
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);
75
Andrew Trickea23daa2011-08-10 04:01:31 +000076 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick4b4bb712011-08-10 03:46:27 +000077
78 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
79 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
80 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
81 bool IsSigned);
82 };
83}
84
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.
Andrew Trickea23daa2011-08-10 04:01:31 +000087///
Andrew Trick24f48ec2011-09-19 17:54:39 +000088/// IVOperand is guaranteed SCEVable, but UseInst may not be.
89///
Andrew Trickea23daa2011-08-10 04:01:31 +000090/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick7cb3dcb2011-08-10 18:07:05 +000091/// be folded (in case more folding opportunities have been exposed).
Andrew Trickea23daa2011-08-10 04:01:31 +000092/// Otherwise return null.
93Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Andrew Trick4b4bb712011-08-10 03:46:27 +000094 Value *IVSrc = 0;
95 unsigned OperIdx = 0;
96 const SCEV *FoldedExpr = 0;
97 switch (UseInst->getOpcode()) {
98 default:
Andrew Trickea23daa2011-08-10 04:01:31 +000099 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000100 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)))
Andrew Trickea23daa2011-08-10 04:01:31 +0000106 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000107
108 // Attempt to fold a binary operator with constant operand.
109 // e.g. ((I + 1) >> 2) => I >> 2
110 if (IVOperand->getNumOperands() != 2 ||
111 !isa<ConstantInt>(IVOperand->getOperand(1)))
Andrew Trickea23daa2011-08-10 04:01:31 +0000112 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000113
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");
117
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))
Andrew Trickea23daa2011-08-10 04:01:31 +0000123 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000124
125 D = ConstantInt::get(UseInst->getContext(),
126 APInt(BitWidth, 1).shl(D->getZExtValue()));
127 }
128 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
129 }
130 // We have something that might fold it's operand. Compare SCEVs.
131 if (!SE->isSCEVable(UseInst->getType()))
Andrew Trickea23daa2011-08-10 04:01:31 +0000132 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000133
134 // Bypass the operand if SCEV can prove it has no effect.
135 if (SE->getSCEV(UseInst) != FoldedExpr)
Andrew Trickea23daa2011-08-10 04:01:31 +0000136 return 0;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000137
138 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
139 << " -> " << *UseInst << '\n');
140
141 UseInst->setOperand(OperIdx, IVSrc);
142 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
143
144 ++NumElimOperand;
145 Changed = true;
146 if (IVOperand->use_empty())
147 DeadInsts.push_back(IVOperand);
Andrew Trickea23daa2011-08-10 04:01:31 +0000148 return IVSrc;
Andrew Trick4b4bb712011-08-10 03:46:27 +0000149}
150
151/// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
152/// comparisons against an induction variable.
153void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
154 unsigned IVOperIdx = 0;
155 ICmpInst::Predicate Pred = ICmp->getPredicate();
156 if (IVOperand != ICmp->getOperand(0)) {
157 // Swapped
158 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
159 IVOperIdx = 1;
160 Pred = ICmpInst::getSwappedPredicate(Pred);
161 }
162
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));
166
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);
171
172 // If the condition is always true or always false, replace it with
173 // a constant value.
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()));
178 else
179 return;
180
181 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
182 ++NumElimCmp;
183 Changed = true;
184 DeadInsts.push_back(ICmp);
185}
186
187/// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
188/// remainder operations operating on an induction variable.
189void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
190 Value *IVOperand,
191 bool IsSigned) {
192 // We're only interested in the case where we know something about
193 // the numerator.
194 if (IVOperand != Rem->getOperand(0))
195 return;
196
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));
200
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);
205
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,
209 S, X))
210 Rem->replaceAllUsesWith(Rem->getOperand(0));
211 else {
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))
216 return;
217
218 if (!SE->isKnownPredicate(IsSigned ?
219 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
220 LessOne, X))
221 return;
222
223 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
224 Rem->getOperand(0), Rem->getOperand(1),
225 "tmp");
226 SelectInst *Sel =
227 SelectInst::Create(ICmp,
228 ConstantInt::get(Rem->getType(), 0),
229 Rem->getOperand(0), "tmp", Rem);
230 Rem->replaceAllUsesWith(Sel);
231 }
232
233 // Inform IVUsers about the new users.
234 if (IU) {
235 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
236 IU->AddUsersIfInteresting(I);
237 }
238 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
239 ++NumElimRem;
240 Changed = true;
241 DeadInsts.push_back(Rem);
242}
243
244/// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
245/// no observable side-effect given the range of IV values.
Andrew Trick24f48ec2011-09-19 17:54:39 +0000246/// IVOperand is guaranteed SCEVable, but UseInst may not be.
Andrew Trick4b4bb712011-08-10 03:46:27 +0000247bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
248 Instruction *IVOperand) {
249 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
250 eliminateIVComparison(ICmp, IVOperand);
251 return true;
252 }
253 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
254 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
255 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
256 eliminateIVRemainder(Rem, IVOperand, IsSigned);
257 return true;
258 }
259 }
260
261 // Eliminate any operation that SCEV can prove is an identity function.
262 if (!SE->isSCEVable(UseInst->getType()) ||
263 (UseInst->getType() != IVOperand->getType()) ||
264 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
265 return false;
266
267 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
268
269 UseInst->replaceAllUsesWith(IVOperand);
270 ++NumElimIdentity;
271 Changed = true;
272 DeadInsts.push_back(UseInst);
273 return true;
274}
275
276/// pushIVUsers - Add all uses of Def to the current IV's worklist.
277///
278static void pushIVUsers(
279 Instruction *Def,
280 SmallPtrSet<Instruction*,16> &Simplified,
281 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
282
283 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
284 UI != E; ++UI) {
285 Instruction *User = cast<Instruction>(*UI);
286
287 // Avoid infinite or exponential worklist processing.
288 // Also ensure unique worklist users.
289 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
290 // self edges first.
291 if (User != Def && Simplified.insert(User))
292 SimpleIVUsers.push_back(std::make_pair(User, Def));
293 }
294}
295
296/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
297/// expression in terms of that IV.
298///
Andrew Trick7cb3dcb2011-08-10 18:07:05 +0000299/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick4b4bb712011-08-10 03:46:27 +0000300/// non-recursively when the operand is already known to be a simpleIVUser.
301///
302static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
303 if (!SE->isSCEVable(I->getType()))
304 return false;
305
306 // Get the symbolic expression for this instruction.
307 const SCEV *S = SE->getSCEV(I);
308
309 // Only consider affine recurrences.
310 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
311 if (AR && AR->getLoop() == L)
312 return true;
313
314 return false;
315}
316
317/// simplifyUsers - Iteratively perform simplification on a worklist of users
318/// of the specified induction variable. Each successive simplification may push
319/// more users which may themselves be candidates for simplification.
320///
321/// This algorithm does not require IVUsers analysis. Instead, it simplifies
322/// instructions in-place during analysis. Rather than rewriting induction
323/// variables bottom-up from their users, it transforms a chain of IVUsers
324/// top-down, updating the IR only when it encouters a clear optimization
325/// opportunitiy.
326///
327/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
328///
329void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick24f48ec2011-09-19 17:54:39 +0000330 if (!SE->isSCEVable(CurrIV->getType()))
331 return;
332
Andrew Trick4b4bb712011-08-10 03:46:27 +0000333 // Instructions processed by SimplifyIndvar for CurrIV.
334 SmallPtrSet<Instruction*,16> Simplified;
335
336 // Use-def pairs if IV users waiting to be processed for CurrIV.
337 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
338
339 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
340 // called multiple times for the same LoopPhi. This is the proper thing to
341 // do for loop header phis that use each other.
342 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
343
344 while (!SimpleIVUsers.empty()) {
345 std::pair<Instruction*, Instruction*> UseOper =
346 SimpleIVUsers.pop_back_val();
347 // Bypass back edges to avoid extra work.
348 if (UseOper.first == CurrIV) continue;
349
Andrew Trickea23daa2011-08-10 04:01:31 +0000350 Instruction *IVOperand = UseOper.second;
351 for (unsigned N = 0; IVOperand; ++N) {
352 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick4b4bb712011-08-10 03:46:27 +0000353
Andrew Trickea23daa2011-08-10 04:01:31 +0000354 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
355 if (!NewOper)
356 break; // done folding
357 IVOperand = dyn_cast<Instruction>(NewOper);
358 }
359 if (!IVOperand)
360 continue;
361
362 if (eliminateIVUser(UseOper.first, IVOperand)) {
363 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000364 continue;
365 }
366 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
367 if (V && Cast) {
368 V->visitCast(Cast);
369 continue;
370 }
371 if (isSimpleIVUser(UseOper.first, L, SE)) {
372 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
373 }
374 }
375}
376
377namespace llvm {
378
379/// simplifyUsersOfIV - Simplify instructions that use this induction variable
380/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Trickbddb7f82011-08-10 04:22:26 +0000381bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +0000382 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
383{
384 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
Andrew Trickbddb7f82011-08-10 04:22:26 +0000385 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000386 SIV.simplifyUsers(CurrIV, V);
387 return SIV.hasChanged();
388}
389
390/// simplifyLoopIVs - Simplify users of induction variables within this
391/// loop. This does not actually change or add IVs.
Andrew Trickbddb7f82011-08-10 04:22:26 +0000392bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +0000393 SmallVectorImpl<WeakVH> &Dead) {
394 bool Changed = false;
395 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Trickbddb7f82011-08-10 04:22:26 +0000396 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000397 }
398 return Changed;
399}
400
401/// simplifyIVUsers - Perform simplification on instructions recorded by the
402/// IVUsers pass.
403///
404/// This is the old approach to IV simplification to be replaced by
405/// SimplifyLoopIVs.
Andrew Trickbddb7f82011-08-10 04:22:26 +0000406bool simplifyIVUsers(IVUsers *IU, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick4b4bb712011-08-10 03:46:27 +0000407 SmallVectorImpl<WeakVH> &Dead) {
Andrew Trickbddb7f82011-08-10 04:22:26 +0000408 SimplifyIndvar SIV(IU->getLoop(), SE, LPM, Dead);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000409
410 // Each round of simplification involves a round of eliminating operations
411 // followed by a round of widening IVs. A single IVUsers worklist is used
412 // across all rounds. The inner loop advances the user. If widening exposes
413 // more uses, then another pass through the outer loop is triggered.
414 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
415 Instruction *UseInst = I->getUser();
416 Value *IVOperand = I->getOperandValToReplace();
417
418 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
419 SIV.eliminateIVComparison(ICmp, IVOperand);
420 continue;
421 }
422 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
423 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
424 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
425 SIV.eliminateIVRemainder(Rem, IVOperand, IsSigned);
426 continue;
427 }
428 }
429 }
430 return SIV.hasChanged();
431}
432
433} // namespace llvm