Added a SimplifyIndVar utility to simplify induction variable users
[oota-llvm.git] / lib / Transforms / Utils / SimplifyIndVar.cpp
1 //===-- 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
32 using namespace llvm;
33
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");
38
39 namespace {
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:
57     SimplifyIndvar(Loop *Loop, LPPassManager *LPM,
58                    SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
59       L(Loop),
60       LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
61       SE(LPM->getAnalysisIfAvailable<ScalarEvolution>()),
62       IU(IVU),
63       TD(LPM->getAnalysisIfAvailable<TargetData>()),
64       DeadInsts(Dead),
65       Changed(false) {
66       assert(LI && SE && "IV simplification requires ScalarEvolution");
67     }
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
76     bool foldIVUser(Instruction *UseInst, Instruction *IVOperand);
77
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.
87 bool SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
88   Value *IVSrc = 0;
89   unsigned OperIdx = 0;
90   const SCEV *FoldedExpr = 0;
91   switch (UseInst->getOpcode()) {
92   default:
93     return false;
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)))
100       return false;
101
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)))
106       return false;
107
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");
111
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))
117         return false;
118
119       D = ConstantInt::get(UseInst->getContext(),
120                            APInt(BitWidth, 1).shl(D->getZExtValue()));
121     }
122     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
123   }
124   // We have something that might fold it's operand. Compare SCEVs.
125   if (!SE->isSCEVable(UseInst->getType()))
126     return false;
127
128   // Bypass the operand if SCEV can prove it has no effect.
129   if (SE->getSCEV(UseInst) != FoldedExpr)
130     return false;
131
132   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
133         << " -> " << *UseInst << '\n');
134
135   UseInst->setOperand(OperIdx, IVSrc);
136   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
137
138   ++NumElimOperand;
139   Changed = true;
140   if (IVOperand->use_empty())
141     DeadInsts.push_back(IVOperand);
142   return true;
143 }
144
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)) {
151     // Swapped
152     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
153     IVOperIdx = 1;
154     Pred = ICmpInst::getSwappedPredicate(Pred);
155   }
156
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));
160
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);
165
166   // If the condition is always true or always false, replace it with
167   // a constant value.
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()));
172   else
173     return;
174
175   DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
176   ++NumElimCmp;
177   Changed = true;
178   DeadInsts.push_back(ICmp);
179 }
180
181 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
182 /// remainder operations operating on an induction variable.
183 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
184                                       Value *IVOperand,
185                                       bool IsSigned) {
186   // We're only interested in the case where we know something about
187   // the numerator.
188   if (IVOperand != Rem->getOperand(0))
189     return;
190
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));
194
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);
199
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,
203                            S, X))
204     Rem->replaceAllUsesWith(Rem->getOperand(0));
205   else {
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))
210       return;
211
212     if (!SE->isKnownPredicate(IsSigned ?
213                               ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
214                               LessOne, X))
215       return;
216
217     ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
218                                   Rem->getOperand(0), Rem->getOperand(1),
219                                   "tmp");
220     SelectInst *Sel =
221       SelectInst::Create(ICmp,
222                          ConstantInt::get(Rem->getType(), 0),
223                          Rem->getOperand(0), "tmp", Rem);
224     Rem->replaceAllUsesWith(Sel);
225   }
226
227   // Inform IVUsers about the new users.
228   if (IU) {
229     if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
230       IU->AddUsersIfInteresting(I);
231   }
232   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
233   ++NumElimRem;
234   Changed = true;
235   DeadInsts.push_back(Rem);
236 }
237
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);
244     return true;
245   }
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);
250       return true;
251     }
252   }
253
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)))
258     return false;
259
260   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
261
262   UseInst->replaceAllUsesWith(IVOperand);
263   ++NumElimIdentity;
264   Changed = true;
265   DeadInsts.push_back(UseInst);
266   return true;
267 }
268
269 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
270 ///
271 static void pushIVUsers(
272   Instruction *Def,
273   SmallPtrSet<Instruction*,16> &Simplified,
274   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
275
276   for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
277        UI != E; ++UI) {
278     Instruction *User = cast<Instruction>(*UI);
279
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
283     // self edges first.
284     if (User != Def && Simplified.insert(User))
285       SimpleIVUsers.push_back(std::make_pair(User, Def));
286   }
287 }
288
289 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
290 /// expression in terms of that IV.
291 ///
292 /// This is similar to IVUsers' isInsteresting() but processes each instruction
293 /// non-recursively when the operand is already known to be a simpleIVUser.
294 ///
295 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
296   if (!SE->isSCEVable(I->getType()))
297     return false;
298
299   // Get the symbolic expression for this instruction.
300   const SCEV *S = SE->getSCEV(I);
301
302   // Only consider affine recurrences.
303   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
304   if (AR && AR->getLoop() == L)
305     return true;
306
307   return false;
308 }
309
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.
313 ///
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
318 /// opportunitiy.
319 ///
320 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
321 ///
322 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
323   // 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
340     foldIVUser(UseOper.first, UseOper.second);
341
342     if (eliminateIVUser(UseOper.first, UseOper.second)) {
343       pushIVUsers(UseOper.second, Simplified, SimpleIVUsers);
344       continue;
345     }
346     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
347     if (V && Cast) {
348       V->visitCast(Cast);
349       continue;
350     }
351     if (isSimpleIVUser(UseOper.first, L, SE)) {
352       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
353     }
354   }
355 }
356
357 namespace llvm {
358
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)
363 {
364   LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
365   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), LPM, Dead);
366   SIV.simplifyUsers(CurrIV, V);
367   return SIV.hasChanged();
368 }
369
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);
377   }
378   return Changed;
379 }
380
381 /// simplifyIVUsers - Perform simplification on instructions recorded by the
382 /// IVUsers pass.
383 ///
384 /// This is the old approach to IV simplification to be replaced by
385 /// SimplifyLoopIVs.
386 bool simplifyIVUsers(IVUsers *IU, LPPassManager *LPM,
387                      SmallVectorImpl<WeakVH> &Dead) {
388   SimplifyIndvar SIV(IU->getLoop(), LPM, Dead);
389
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();
397
398     if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
399       SIV.eliminateIVComparison(ICmp, IVOperand);
400       continue;
401     }
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);
406         continue;
407       }
408     }
409   }
410   return SIV.hasChanged();
411 }
412
413 } // namespace llvm