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/Analysis/IVUsers.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/LoopPass.h"
24#include "llvm/Analysis/ScalarEvolutionExpressions.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
30
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;
46    ScalarEvolution  *SE;
47    const DataLayout *TD; // May be NULL
48
49    SmallVectorImpl<WeakVH> &DeadInsts;
50
51    bool Changed;
52
53  public:
54    SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
55                   SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
56      L(Loop),
57      LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
58      SE(SE),
59      TD(LPM->getAnalysisIfAvailable<DataLayout>()),
60      DeadInsts(Dead),
61      Changed(false) {
62      assert(LI && "IV simplification requires LoopInfo");
63    }
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
72    Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
73
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.
83///
84/// IVOperand is guaranteed SCEVable, but UseInst may not be.
85///
86/// Return the operand of IVOperand for this induction variable if IVOperand can
87/// be folded (in case more folding opportunities have been exposed).
88/// Otherwise return null.
89Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
90  Value *IVSrc = 0;
91  unsigned OperIdx = 0;
92  const SCEV *FoldedExpr = 0;
93  switch (UseInst->getOpcode()) {
94  default:
95    return 0;
96  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)))
102      return 0;
103
104    // Attempt to fold a binary operator with constant operand.
105    // e.g. ((I + 1) >> 2) => I >> 2
106    if (!isa<BinaryOperator>(IVOperand)
107        || !isa<ConstantInt>(IVOperand->getOperand(1)))
108      return 0;
109
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))
119        return 0;
120
121      D = ConstantInt::get(UseInst->getContext(),
122                           APInt::getOneBitSet(BitWidth, 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()))
128    return 0;
129
130  // Bypass the operand if SCEV can prove it has no effect.
131  if (SE->getSCEV(UseInst) != FoldedExpr)
132    return 0;
133
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);
144  return IVSrc;
145}
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,
220                                  Rem->getOperand(0), Rem->getOperand(1));
221    SelectInst *Sel =
222      SelectInst::Create(ICmp,
223                         ConstantInt::get(Rem->getType(), 0),
224                         Rem->getOperand(0), "tmp", Rem);
225    Rem->replaceAllUsesWith(Sel);
226  }
227
228  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.
236/// IVOperand is guaranteed SCEVable, but UseInst may not be.
237bool 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///
289/// This is similar to IVUsers' isInteresting() but processes each instruction
290/// 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) {
320  if (!SE->isSCEVable(CurrIV->getType()))
321    return;
322
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    Instruction *IVOperand = UseOper.second;
341    for (unsigned N = 0; IVOperand; ++N) {
342      assert(N <= Simplified.size() && "runaway iteration");
343
344      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);
354      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
369void IVVisitor::anchor() { }
370
371/// simplifyUsersOfIV - Simplify instructions that use this induction variable
372/// by using ScalarEvolution to analyze the IV's recurrence.
373bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
374                       SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
375{
376  LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
377  SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
378  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.
384bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
385                     SmallVectorImpl<WeakVH> &Dead) {
386  bool Changed = false;
387  for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
388    Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
389  }
390  return Changed;
391}
392
393} // namespace llvm
394