LLVM API Documentation

SimplifyIndVar.cpp
Go to the documentation of this file.
00001 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements induction variable simplification. It does
00011 // not define any actual pass or policy, but provides a single function to
00012 // simplify a loop's induction variables based on ScalarEvolution.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/IVUsers.h"
00021 #include "llvm/Analysis/LoopInfo.h"
00022 #include "llvm/Analysis/LoopPass.h"
00023 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/Dominators.h"
00026 #include "llvm/IR/IRBuilder.h"
00027 #include "llvm/IR/Instructions.h"
00028 #include "llvm/IR/IntrinsicInst.h"
00029 #include "llvm/Support/CommandLine.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 
00033 using namespace llvm;
00034 
00035 #define DEBUG_TYPE "indvars"
00036 
00037 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
00038 STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
00039 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
00040 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
00041 
00042 namespace {
00043   /// This is a utility for simplifying induction variables
00044   /// based on ScalarEvolution. It is the primary instrument of the
00045   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
00046   /// other loop passes that preserve SCEV.
00047   class SimplifyIndvar {
00048     Loop             *L;
00049     LoopInfo         *LI;
00050     ScalarEvolution  *SE;
00051 
00052     SmallVectorImpl<WeakVH> &DeadInsts;
00053 
00054     bool Changed;
00055 
00056   public:
00057     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LoopInfo *LI,
00058                    SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = nullptr)
00059         : L(Loop), LI(LI), SE(SE), DeadInsts(Dead), Changed(false) {
00060       assert(LI && "IV simplification requires LoopInfo");
00061     }
00062 
00063     bool hasChanged() const { return Changed; }
00064 
00065     /// Iteratively perform simplification on a worklist of users of the
00066     /// specified induction variable. This is the top-level driver that applies
00067     /// all simplicitions to users of an IV.
00068     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
00069 
00070     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
00071 
00072     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
00073     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
00074     void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
00075                               bool IsSigned);
00076     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
00077 
00078     Instruction *splitOverflowIntrinsic(Instruction *IVUser,
00079                                         const DominatorTree *DT);
00080   };
00081 }
00082 
00083 /// Fold an IV operand into its use.  This removes increments of an
00084 /// aligned IV when used by a instruction that ignores the low bits.
00085 ///
00086 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
00087 ///
00088 /// Return the operand of IVOperand for this induction variable if IVOperand can
00089 /// be folded (in case more folding opportunities have been exposed).
00090 /// Otherwise return null.
00091 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
00092   Value *IVSrc = nullptr;
00093   unsigned OperIdx = 0;
00094   const SCEV *FoldedExpr = nullptr;
00095   switch (UseInst->getOpcode()) {
00096   default:
00097     return nullptr;
00098   case Instruction::UDiv:
00099   case Instruction::LShr:
00100     // We're only interested in the case where we know something about
00101     // the numerator and have a constant denominator.
00102     if (IVOperand != UseInst->getOperand(OperIdx) ||
00103         !isa<ConstantInt>(UseInst->getOperand(1)))
00104       return nullptr;
00105 
00106     // Attempt to fold a binary operator with constant operand.
00107     // e.g. ((I + 1) >> 2) => I >> 2
00108     if (!isa<BinaryOperator>(IVOperand)
00109         || !isa<ConstantInt>(IVOperand->getOperand(1)))
00110       return nullptr;
00111 
00112     IVSrc = IVOperand->getOperand(0);
00113     // IVSrc must be the (SCEVable) IV, since the other operand is const.
00114     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
00115 
00116     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
00117     if (UseInst->getOpcode() == Instruction::LShr) {
00118       // Get a constant for the divisor. See createSCEV.
00119       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
00120       if (D->getValue().uge(BitWidth))
00121         return nullptr;
00122 
00123       D = ConstantInt::get(UseInst->getContext(),
00124                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
00125     }
00126     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
00127   }
00128   // We have something that might fold it's operand. Compare SCEVs.
00129   if (!SE->isSCEVable(UseInst->getType()))
00130     return nullptr;
00131 
00132   // Bypass the operand if SCEV can prove it has no effect.
00133   if (SE->getSCEV(UseInst) != FoldedExpr)
00134     return nullptr;
00135 
00136   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
00137         << " -> " << *UseInst << '\n');
00138 
00139   UseInst->setOperand(OperIdx, IVSrc);
00140   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
00141 
00142   ++NumElimOperand;
00143   Changed = true;
00144   if (IVOperand->use_empty())
00145     DeadInsts.push_back(IVOperand);
00146   return IVSrc;
00147 }
00148 
00149 /// SimplifyIVUsers helper for eliminating useless
00150 /// comparisons against an induction variable.
00151 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
00152   unsigned IVOperIdx = 0;
00153   ICmpInst::Predicate Pred = ICmp->getPredicate();
00154   if (IVOperand != ICmp->getOperand(0)) {
00155     // Swapped
00156     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
00157     IVOperIdx = 1;
00158     Pred = ICmpInst::getSwappedPredicate(Pred);
00159   }
00160 
00161   // Get the SCEVs for the ICmp operands.
00162   const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
00163   const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
00164 
00165   // Simplify unnecessary loops away.
00166   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
00167   S = SE->getSCEVAtScope(S, ICmpLoop);
00168   X = SE->getSCEVAtScope(X, ICmpLoop);
00169 
00170   // If the condition is always true or always false, replace it with
00171   // a constant value.
00172   if (SE->isKnownPredicate(Pred, S, X))
00173     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
00174   else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
00175     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
00176   else
00177     return;
00178 
00179   DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
00180   ++NumElimCmp;
00181   Changed = true;
00182   DeadInsts.push_back(ICmp);
00183 }
00184 
00185 /// SimplifyIVUsers helper for eliminating useless
00186 /// remainder operations operating on an induction variable.
00187 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
00188                                       Value *IVOperand,
00189                                       bool IsSigned) {
00190   // We're only interested in the case where we know something about
00191   // the numerator.
00192   if (IVOperand != Rem->getOperand(0))
00193     return;
00194 
00195   // Get the SCEVs for the ICmp operands.
00196   const SCEV *S = SE->getSCEV(Rem->getOperand(0));
00197   const SCEV *X = SE->getSCEV(Rem->getOperand(1));
00198 
00199   // Simplify unnecessary loops away.
00200   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
00201   S = SE->getSCEVAtScope(S, ICmpLoop);
00202   X = SE->getSCEVAtScope(X, ICmpLoop);
00203 
00204   // i % n  -->  i  if i is in [0,n).
00205   if ((!IsSigned || SE->isKnownNonNegative(S)) &&
00206       SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
00207                            S, X))
00208     Rem->replaceAllUsesWith(Rem->getOperand(0));
00209   else {
00210     // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
00211     const SCEV *LessOne =
00212       SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
00213     if (IsSigned && !SE->isKnownNonNegative(LessOne))
00214       return;
00215 
00216     if (!SE->isKnownPredicate(IsSigned ?
00217                               ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
00218                               LessOne, X))
00219       return;
00220 
00221     ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
00222                                   Rem->getOperand(0), Rem->getOperand(1));
00223     SelectInst *Sel =
00224       SelectInst::Create(ICmp,
00225                          ConstantInt::get(Rem->getType(), 0),
00226                          Rem->getOperand(0), "tmp", Rem);
00227     Rem->replaceAllUsesWith(Sel);
00228   }
00229 
00230   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
00231   ++NumElimRem;
00232   Changed = true;
00233   DeadInsts.push_back(Rem);
00234 }
00235 
00236 /// Eliminate an operation that consumes a simple IV and has
00237 /// no observable side-effect given the range of IV values.
00238 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
00239 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
00240                                      Instruction *IVOperand) {
00241   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
00242     eliminateIVComparison(ICmp, IVOperand);
00243     return true;
00244   }
00245   if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
00246     bool IsSigned = Rem->getOpcode() == Instruction::SRem;
00247     if (IsSigned || Rem->getOpcode() == Instruction::URem) {
00248       eliminateIVRemainder(Rem, IVOperand, IsSigned);
00249       return true;
00250     }
00251   }
00252 
00253   // Eliminate any operation that SCEV can prove is an identity function.
00254   if (!SE->isSCEVable(UseInst->getType()) ||
00255       (UseInst->getType() != IVOperand->getType()) ||
00256       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
00257     return false;
00258 
00259   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
00260 
00261   UseInst->replaceAllUsesWith(IVOperand);
00262   ++NumElimIdentity;
00263   Changed = true;
00264   DeadInsts.push_back(UseInst);
00265   return true;
00266 }
00267 
00268 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
00269 /// unsigned-overflow.  Returns true if anything changed, false otherwise.
00270 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
00271                                                     Value *IVOperand) {
00272 
00273   // Currently we only handle instructions of the form "add <indvar> <value>"
00274   unsigned Op = BO->getOpcode();
00275   if (Op != Instruction::Add)
00276     return false;
00277 
00278   // If BO is already both nuw and nsw then there is nothing left to do
00279   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
00280     return false;
00281 
00282   IntegerType *IT = cast<IntegerType>(IVOperand->getType());
00283   Value *OtherOperand = nullptr;
00284   if (BO->getOperand(0) == IVOperand) {
00285     OtherOperand = BO->getOperand(1);
00286   } else {
00287     assert(BO->getOperand(1) == IVOperand && "only other use!");
00288     OtherOperand = BO->getOperand(0);
00289   }
00290 
00291   bool Changed = false;
00292   const SCEV *OtherOpSCEV = SE->getSCEV(OtherOperand);
00293   if (OtherOpSCEV == SE->getCouldNotCompute())
00294     return false;
00295 
00296   const SCEV *IVOpSCEV = SE->getSCEV(IVOperand);
00297   const SCEV *ZeroSCEV = SE->getConstant(IVOpSCEV->getType(), 0);
00298 
00299   if (!BO->hasNoSignedWrap()) {
00300     // Upgrade the add to an "add nsw" if we can prove that it will never
00301     // sign-overflow or sign-underflow.
00302 
00303     const SCEV *SignedMax =
00304       SE->getConstant(APInt::getSignedMaxValue(IT->getBitWidth()));
00305     const SCEV *SignedMin =
00306       SE->getConstant(APInt::getSignedMinValue(IT->getBitWidth()));
00307 
00308     // The addition "IVOperand + OtherOp" does not sign-overflow if the result
00309     // is sign-representable in 2's complement in the given bit-width.
00310     //
00311     // If OtherOp is SLT 0, then for an IVOperand in [SignedMin - OtherOp,
00312     // SignedMax], "IVOperand + OtherOp" is in [SignedMin, SignedMax + OtherOp].
00313     // Everything in [SignedMin, SignedMax + OtherOp] is representable since
00314     // SignedMax + OtherOp is at least -1.
00315     //
00316     // If OtherOp is SGE 0, then for an IVOperand in [SignedMin, SignedMax -
00317     // OtherOp], "IVOperand + OtherOp" is in [SignedMin + OtherOp, SignedMax].
00318     // Everything in [SignedMin + OtherOp, SignedMax] is representable since
00319     // SignedMin + OtherOp is at most -1.
00320     //
00321     // It follows that for all values of IVOperand in [SignedMin - smin(0,
00322     // OtherOp), SignedMax - smax(0, OtherOp)] the result of the add is
00323     // representable (i.e. there is no sign-overflow).
00324 
00325     const SCEV *UpperDelta = SE->getSMaxExpr(ZeroSCEV, OtherOpSCEV);
00326     const SCEV *UpperLimit = SE->getMinusSCEV(SignedMax, UpperDelta);
00327 
00328     bool NeverSignedOverflows =
00329       SE->isKnownPredicate(ICmpInst::ICMP_SLE, IVOpSCEV, UpperLimit);
00330 
00331     if (NeverSignedOverflows) {
00332       const SCEV *LowerDelta = SE->getSMinExpr(ZeroSCEV, OtherOpSCEV);
00333       const SCEV *LowerLimit = SE->getMinusSCEV(SignedMin, LowerDelta);
00334 
00335       bool NeverSignedUnderflows =
00336         SE->isKnownPredicate(ICmpInst::ICMP_SGE, IVOpSCEV, LowerLimit);
00337       if (NeverSignedUnderflows) {
00338         BO->setHasNoSignedWrap(true);
00339         Changed = true;
00340       }
00341     }
00342   }
00343 
00344   if (!BO->hasNoUnsignedWrap()) {
00345     // Upgrade the add computing "IVOperand + OtherOp" to an "add nuw" if we can
00346     // prove that it will never unsigned-overflow (i.e. the result will always
00347     // be representable in the given bit-width).
00348     //
00349     // "IVOperand + OtherOp" is unsigned-representable in 2's complement iff it
00350     // does not produce a carry.  "IVOperand + OtherOp" produces no carry iff
00351     // IVOperand ULE (UnsignedMax - OtherOp).
00352 
00353     const SCEV *UnsignedMax =
00354       SE->getConstant(APInt::getMaxValue(IT->getBitWidth()));
00355     const SCEV *UpperLimit = SE->getMinusSCEV(UnsignedMax, OtherOpSCEV);
00356 
00357     bool NeverUnsignedOverflows =
00358         SE->isKnownPredicate(ICmpInst::ICMP_ULE, IVOpSCEV, UpperLimit);
00359 
00360     if (NeverUnsignedOverflows) {
00361       BO->setHasNoUnsignedWrap(true);
00362       Changed = true;
00363     }
00364   }
00365 
00366   return Changed;
00367 }
00368 
00369 /// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
00370 /// analysis and optimization.
00371 ///
00372 /// \return A new value representing the non-overflowing add if possible,
00373 /// otherwise return the original value.
00374 Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
00375                                                     const DominatorTree *DT) {
00376   IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
00377   if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
00378     return IVUser;
00379 
00380   // Find a branch guarded by the overflow check.
00381   BranchInst *Branch = nullptr;
00382   Instruction *AddVal = nullptr;
00383   for (User *U : II->users()) {
00384     if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
00385       if (ExtractInst->getNumIndices() != 1)
00386         continue;
00387       if (ExtractInst->getIndices()[0] == 0)
00388         AddVal = ExtractInst;
00389       else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
00390         Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
00391     }
00392   }
00393   if (!AddVal || !Branch)
00394     return IVUser;
00395 
00396   BasicBlock *ContinueBB = Branch->getSuccessor(1);
00397   if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
00398     return IVUser;
00399 
00400   // Check if all users of the add are provably NSW.
00401   bool AllNSW = true;
00402   for (Use &U : AddVal->uses()) {
00403     if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
00404       BasicBlock *UseBB = UseInst->getParent();
00405       if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
00406         UseBB = PHI->getIncomingBlock(U);
00407       if (!DT->dominates(ContinueBB, UseBB)) {
00408         AllNSW = false;
00409         break;
00410       }
00411     }
00412   }
00413   if (!AllNSW)
00414     return IVUser;
00415 
00416   // Go for it...
00417   IRBuilder<> Builder(IVUser);
00418   Instruction *AddInst = dyn_cast<Instruction>(
00419     Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
00420 
00421   // The caller expects the new add to have the same form as the intrinsic. The
00422   // IV operand position must be the same.
00423   assert((AddInst->getOpcode() == Instruction::Add &&
00424           AddInst->getOperand(0) == II->getOperand(0)) &&
00425          "Bad add instruction created from overflow intrinsic.");
00426 
00427   AddVal->replaceAllUsesWith(AddInst);
00428   DeadInsts.push_back(AddVal);
00429   return AddInst;
00430 }
00431 
00432 /// Add all uses of Def to the current IV's worklist.
00433 static void pushIVUsers(
00434   Instruction *Def,
00435   SmallPtrSet<Instruction*,16> &Simplified,
00436   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
00437 
00438   for (User *U : Def->users()) {
00439     Instruction *UI = cast<Instruction>(U);
00440 
00441     // Avoid infinite or exponential worklist processing.
00442     // Also ensure unique worklist users.
00443     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
00444     // self edges first.
00445     if (UI != Def && Simplified.insert(UI).second)
00446       SimpleIVUsers.push_back(std::make_pair(UI, Def));
00447   }
00448 }
00449 
00450 /// Return true if this instruction generates a simple SCEV
00451 /// expression in terms of that IV.
00452 ///
00453 /// This is similar to IVUsers' isInteresting() but processes each instruction
00454 /// non-recursively when the operand is already known to be a simpleIVUser.
00455 ///
00456 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
00457   if (!SE->isSCEVable(I->getType()))
00458     return false;
00459 
00460   // Get the symbolic expression for this instruction.
00461   const SCEV *S = SE->getSCEV(I);
00462 
00463   // Only consider affine recurrences.
00464   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
00465   if (AR && AR->getLoop() == L)
00466     return true;
00467 
00468   return false;
00469 }
00470 
00471 /// Iteratively perform simplification on a worklist of users
00472 /// of the specified induction variable. Each successive simplification may push
00473 /// more users which may themselves be candidates for simplification.
00474 ///
00475 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
00476 /// instructions in-place during analysis. Rather than rewriting induction
00477 /// variables bottom-up from their users, it transforms a chain of IVUsers
00478 /// top-down, updating the IR only when it encouters a clear optimization
00479 /// opportunitiy.
00480 ///
00481 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
00482 ///
00483 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
00484   if (!SE->isSCEVable(CurrIV->getType()))
00485     return;
00486 
00487   // Instructions processed by SimplifyIndvar for CurrIV.
00488   SmallPtrSet<Instruction*,16> Simplified;
00489 
00490   // Use-def pairs if IV users waiting to be processed for CurrIV.
00491   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
00492 
00493   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
00494   // called multiple times for the same LoopPhi. This is the proper thing to
00495   // do for loop header phis that use each other.
00496   pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
00497 
00498   while (!SimpleIVUsers.empty()) {
00499     std::pair<Instruction*, Instruction*> UseOper =
00500       SimpleIVUsers.pop_back_val();
00501     Instruction *UseInst = UseOper.first;
00502 
00503     // Bypass back edges to avoid extra work.
00504     if (UseInst == CurrIV) continue;
00505 
00506     if (V && V->shouldSplitOverflowInstrinsics()) {
00507       UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
00508       if (!UseInst)
00509         continue;
00510     }
00511 
00512     Instruction *IVOperand = UseOper.second;
00513     for (unsigned N = 0; IVOperand; ++N) {
00514       assert(N <= Simplified.size() && "runaway iteration");
00515 
00516       Value *NewOper = foldIVUser(UseOper.first, IVOperand);
00517       if (!NewOper)
00518         break; // done folding
00519       IVOperand = dyn_cast<Instruction>(NewOper);
00520     }
00521     if (!IVOperand)
00522       continue;
00523 
00524     if (eliminateIVUser(UseOper.first, IVOperand)) {
00525       pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
00526       continue;
00527     }
00528 
00529     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
00530       if (isa<OverflowingBinaryOperator>(BO) &&
00531           strengthenOverflowingOperation(BO, IVOperand)) {
00532         // re-queue uses of the now modified binary operator and fall
00533         // through to the checks that remain.
00534         pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
00535       }
00536     }
00537 
00538     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
00539     if (V && Cast) {
00540       V->visitCast(Cast);
00541       continue;
00542     }
00543     if (isSimpleIVUser(UseOper.first, L, SE)) {
00544       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
00545     }
00546   }
00547 }
00548 
00549 namespace llvm {
00550 
00551 void IVVisitor::anchor() { }
00552 
00553 /// Simplify instructions that use this induction variable
00554 /// by using ScalarEvolution to analyze the IV's recurrence.
00555 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
00556                        SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
00557 {
00558   LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00559   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI, Dead);
00560   SIV.simplifyUsers(CurrIV, V);
00561   return SIV.hasChanged();
00562 }
00563 
00564 /// Simplify users of induction variables within this
00565 /// loop. This does not actually change or add IVs.
00566 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
00567                      SmallVectorImpl<WeakVH> &Dead) {
00568   bool Changed = false;
00569   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
00570     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
00571   }
00572   return Changed;
00573 }
00574 
00575 } // namespace llvm