Add support to indvars for optimizing sadd.with.overflow.
[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/Transforms/Utils/SimplifyIndVar.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/IVUsers.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 using namespace llvm;
36
37 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
38 STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
39 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
40 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
41
42 namespace {
43   /// SimplifyIndvar - This is a utility for simplifying induction variables
44   /// based on ScalarEvolution. It is the primary instrument of the
45   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
46   /// other loop passes that preserve SCEV.
47   class SimplifyIndvar {
48     Loop             *L;
49     LoopInfo         *LI;
50     ScalarEvolution  *SE;
51     const DataLayout *TD; // May be NULL
52
53     SmallVectorImpl<WeakVH> &DeadInsts;
54
55     bool Changed;
56
57   public:
58     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
59                    SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
60       L(Loop),
61       LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
62       SE(SE),
63       TD(LPM->getAnalysisIfAvailable<DataLayout>()),
64       DeadInsts(Dead),
65       Changed(false) {
66       assert(LI && "IV simplification requires LoopInfo");
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     Value *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     Instruction *splitOverflowIntrinsic(Instruction *IVUser,
84                                         const DominatorTree *DT);
85   };
86 }
87
88 /// foldIVUser - Fold an IV operand into its use.  This removes increments of an
89 /// aligned IV when used by a instruction that ignores the low bits.
90 ///
91 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
92 ///
93 /// Return the operand of IVOperand for this induction variable if IVOperand can
94 /// be folded (in case more folding opportunities have been exposed).
95 /// Otherwise return null.
96 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
97   Value *IVSrc = 0;
98   unsigned OperIdx = 0;
99   const SCEV *FoldedExpr = 0;
100   switch (UseInst->getOpcode()) {
101   default:
102     return 0;
103   case Instruction::UDiv:
104   case Instruction::LShr:
105     // We're only interested in the case where we know something about
106     // the numerator and have a constant denominator.
107     if (IVOperand != UseInst->getOperand(OperIdx) ||
108         !isa<ConstantInt>(UseInst->getOperand(1)))
109       return 0;
110
111     // Attempt to fold a binary operator with constant operand.
112     // e.g. ((I + 1) >> 2) => I >> 2
113     if (!isa<BinaryOperator>(IVOperand)
114         || !isa<ConstantInt>(IVOperand->getOperand(1)))
115       return 0;
116
117     IVSrc = IVOperand->getOperand(0);
118     // IVSrc must be the (SCEVable) IV, since the other operand is const.
119     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
120
121     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
122     if (UseInst->getOpcode() == Instruction::LShr) {
123       // Get a constant for the divisor. See createSCEV.
124       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
125       if (D->getValue().uge(BitWidth))
126         return 0;
127
128       D = ConstantInt::get(UseInst->getContext(),
129                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
130     }
131     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
132   }
133   // We have something that might fold it's operand. Compare SCEVs.
134   if (!SE->isSCEVable(UseInst->getType()))
135     return 0;
136
137   // Bypass the operand if SCEV can prove it has no effect.
138   if (SE->getSCEV(UseInst) != FoldedExpr)
139     return 0;
140
141   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
142         << " -> " << *UseInst << '\n');
143
144   UseInst->setOperand(OperIdx, IVSrc);
145   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
146
147   ++NumElimOperand;
148   Changed = true;
149   if (IVOperand->use_empty())
150     DeadInsts.push_back(IVOperand);
151   return IVSrc;
152 }
153
154 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
155 /// comparisons against an induction variable.
156 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
157   unsigned IVOperIdx = 0;
158   ICmpInst::Predicate Pred = ICmp->getPredicate();
159   if (IVOperand != ICmp->getOperand(0)) {
160     // Swapped
161     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
162     IVOperIdx = 1;
163     Pred = ICmpInst::getSwappedPredicate(Pred);
164   }
165
166   // Get the SCEVs for the ICmp operands.
167   const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
168   const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
169
170   // Simplify unnecessary loops away.
171   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
172   S = SE->getSCEVAtScope(S, ICmpLoop);
173   X = SE->getSCEVAtScope(X, ICmpLoop);
174
175   // If the condition is always true or always false, replace it with
176   // a constant value.
177   if (SE->isKnownPredicate(Pred, S, X))
178     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
179   else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
180     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
181   else
182     return;
183
184   DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
185   ++NumElimCmp;
186   Changed = true;
187   DeadInsts.push_back(ICmp);
188 }
189
190 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
191 /// remainder operations operating on an induction variable.
192 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
193                                       Value *IVOperand,
194                                       bool IsSigned) {
195   // We're only interested in the case where we know something about
196   // the numerator.
197   if (IVOperand != Rem->getOperand(0))
198     return;
199
200   // Get the SCEVs for the ICmp operands.
201   const SCEV *S = SE->getSCEV(Rem->getOperand(0));
202   const SCEV *X = SE->getSCEV(Rem->getOperand(1));
203
204   // Simplify unnecessary loops away.
205   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
206   S = SE->getSCEVAtScope(S, ICmpLoop);
207   X = SE->getSCEVAtScope(X, ICmpLoop);
208
209   // i % n  -->  i  if i is in [0,n).
210   if ((!IsSigned || SE->isKnownNonNegative(S)) &&
211       SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
212                            S, X))
213     Rem->replaceAllUsesWith(Rem->getOperand(0));
214   else {
215     // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
216     const SCEV *LessOne =
217       SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
218     if (IsSigned && !SE->isKnownNonNegative(LessOne))
219       return;
220
221     if (!SE->isKnownPredicate(IsSigned ?
222                               ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
223                               LessOne, X))
224       return;
225
226     ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
227                                   Rem->getOperand(0), Rem->getOperand(1));
228     SelectInst *Sel =
229       SelectInst::Create(ICmp,
230                          ConstantInt::get(Rem->getType(), 0),
231                          Rem->getOperand(0), "tmp", Rem);
232     Rem->replaceAllUsesWith(Sel);
233   }
234
235   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
236   ++NumElimRem;
237   Changed = true;
238   DeadInsts.push_back(Rem);
239 }
240
241 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
242 /// no observable side-effect given the range of IV values.
243 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
244 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
245                                      Instruction *IVOperand) {
246   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
247     eliminateIVComparison(ICmp, IVOperand);
248     return true;
249   }
250   if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
251     bool IsSigned = Rem->getOpcode() == Instruction::SRem;
252     if (IsSigned || Rem->getOpcode() == Instruction::URem) {
253       eliminateIVRemainder(Rem, IVOperand, IsSigned);
254       return true;
255     }
256   }
257
258   // Eliminate any operation that SCEV can prove is an identity function.
259   if (!SE->isSCEVable(UseInst->getType()) ||
260       (UseInst->getType() != IVOperand->getType()) ||
261       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
262     return false;
263
264   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
265
266   UseInst->replaceAllUsesWith(IVOperand);
267   ++NumElimIdentity;
268   Changed = true;
269   DeadInsts.push_back(UseInst);
270   return true;
271 }
272
273 /// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
274 /// analysis and optimization.
275 ///
276 /// \return A new value representing the non-overflowing add if possible,
277 /// otherwise return the original value.
278 Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
279                                                     const DominatorTree *DT) {
280   IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
281   if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
282     return IVUser;
283
284   // Find a branch guarded by the overflow check.
285   BranchInst *Branch = 0;
286   Instruction *AddVal = 0;
287   for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
288        UI != E; ++UI) {
289     if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(*UI)) {
290       if (ExtractInst->getNumIndices() != 1)
291         continue;
292       if (ExtractInst->getIndices()[0] == 0)
293         AddVal = ExtractInst;
294       else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
295         Branch = dyn_cast<BranchInst>(ExtractInst->use_back());
296     }
297   }
298   if (!AddVal || !Branch)
299     return IVUser;
300
301   BasicBlock *ContinueBB = Branch->getSuccessor(1);
302   if (llvm::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
303     return IVUser;
304
305   // Check if all users of the add are provably NSW.
306   bool AllNSW = true;
307   for (Value::use_iterator UI = AddVal->use_begin(), E = AddVal->use_end();
308        UI != E; ++UI) {
309     if (Instruction *UseInst = dyn_cast<Instruction>(*UI)) {
310       BasicBlock *UseBB = UseInst->getParent();
311       if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
312         UseBB = PHI->getIncomingBlock(UI);
313       if (!DT->dominates(ContinueBB, UseBB)) {
314         AllNSW = false;
315         break;
316       }
317     }
318   }
319   if (!AllNSW)
320     return IVUser;
321
322   // Go for it...
323   IRBuilder<> Builder(IVUser);
324   Instruction *AddInst = dyn_cast<Instruction>(
325     Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
326
327   // The caller expects the new add to have the same form as the intrinsic. The
328   // IV operand position must be the same.
329   assert((AddInst->getOpcode() == Instruction::Add &&
330           AddInst->getOperand(0) == II->getOperand(0)) &&
331          "Bad add instruction created from overflow intrinsic.");
332
333   AddVal->replaceAllUsesWith(AddInst);
334   DeadInsts.push_back(AddVal);
335   return AddInst;
336 }
337
338 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
339 ///
340 static void pushIVUsers(
341   Instruction *Def,
342   SmallPtrSet<Instruction*,16> &Simplified,
343   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
344
345   for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
346        UI != E; ++UI) {
347     Instruction *User = cast<Instruction>(*UI);
348
349     // Avoid infinite or exponential worklist processing.
350     // Also ensure unique worklist users.
351     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
352     // self edges first.
353     if (User != Def && Simplified.insert(User))
354       SimpleIVUsers.push_back(std::make_pair(User, Def));
355   }
356 }
357
358 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
359 /// expression in terms of that IV.
360 ///
361 /// This is similar to IVUsers' isInteresting() but processes each instruction
362 /// non-recursively when the operand is already known to be a simpleIVUser.
363 ///
364 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
365   if (!SE->isSCEVable(I->getType()))
366     return false;
367
368   // Get the symbolic expression for this instruction.
369   const SCEV *S = SE->getSCEV(I);
370
371   // Only consider affine recurrences.
372   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
373   if (AR && AR->getLoop() == L)
374     return true;
375
376   return false;
377 }
378
379 /// simplifyUsers - Iteratively perform simplification on a worklist of users
380 /// of the specified induction variable. Each successive simplification may push
381 /// more users which may themselves be candidates for simplification.
382 ///
383 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
384 /// instructions in-place during analysis. Rather than rewriting induction
385 /// variables bottom-up from their users, it transforms a chain of IVUsers
386 /// top-down, updating the IR only when it encouters a clear optimization
387 /// opportunitiy.
388 ///
389 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
390 ///
391 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
392   if (!SE->isSCEVable(CurrIV->getType()))
393     return;
394
395   // Instructions processed by SimplifyIndvar for CurrIV.
396   SmallPtrSet<Instruction*,16> Simplified;
397
398   // Use-def pairs if IV users waiting to be processed for CurrIV.
399   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
400
401   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
402   // called multiple times for the same LoopPhi. This is the proper thing to
403   // do for loop header phis that use each other.
404   pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
405
406   while (!SimpleIVUsers.empty()) {
407     std::pair<Instruction*, Instruction*> UseOper =
408       SimpleIVUsers.pop_back_val();
409     Instruction *UseInst = UseOper.first;
410
411     // Bypass back edges to avoid extra work.
412     if (UseInst == CurrIV) continue;
413
414     if (V && V->shouldSplitOverflowInstrinsics()) {
415       UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
416       if (!UseInst)
417         continue;
418     }
419
420     Instruction *IVOperand = UseOper.second;
421     for (unsigned N = 0; IVOperand; ++N) {
422       assert(N <= Simplified.size() && "runaway iteration");
423
424       Value *NewOper = foldIVUser(UseOper.first, IVOperand);
425       if (!NewOper)
426         break; // done folding
427       IVOperand = dyn_cast<Instruction>(NewOper);
428     }
429     if (!IVOperand)
430       continue;
431
432     if (eliminateIVUser(UseOper.first, IVOperand)) {
433       pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
434       continue;
435     }
436     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
437     if (V && Cast) {
438       V->visitCast(Cast);
439       continue;
440     }
441     if (isSimpleIVUser(UseOper.first, L, SE)) {
442       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
443     }
444   }
445 }
446
447 namespace llvm {
448
449 void IVVisitor::anchor() { }
450
451 /// simplifyUsersOfIV - Simplify instructions that use this induction variable
452 /// by using ScalarEvolution to analyze the IV's recurrence.
453 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
454                        SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
455 {
456   LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
457   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
458   SIV.simplifyUsers(CurrIV, V);
459   return SIV.hasChanged();
460 }
461
462 /// simplifyLoopIVs - Simplify users of induction variables within this
463 /// loop. This does not actually change or add IVs.
464 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
465                      SmallVectorImpl<WeakVH> &Dead) {
466   bool Changed = false;
467   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
468     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
469   }
470   return Changed;
471 }
472
473 } // namespace llvm