16122f3e6SDimitry Andric //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
26122f3e6SDimitry Andric //
36122f3e6SDimitry Andric //                     The LLVM Compiler Infrastructure
46122f3e6SDimitry Andric //
56122f3e6SDimitry Andric // This file is distributed under the University of Illinois Open Source
66122f3e6SDimitry Andric // License. See LICENSE.TXT for details.
76122f3e6SDimitry Andric //
86122f3e6SDimitry Andric //===----------------------------------------------------------------------===//
96122f3e6SDimitry Andric //
106122f3e6SDimitry Andric // This file implements induction variable simplification. It does
116122f3e6SDimitry Andric // not define any actual pass or policy, but provides a single function to
126122f3e6SDimitry Andric // simplify a loop's induction variables based on ScalarEvolution.
136122f3e6SDimitry Andric //
146122f3e6SDimitry Andric //===----------------------------------------------------------------------===//
156122f3e6SDimitry Andric 
16139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
1791bc56edSDimitry Andric #include "llvm/ADT/STLExtras.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h"
19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
206122f3e6SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
212cab237bSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpander.h"
22139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
2391bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
2491bc56edSDimitry Andric #include "llvm/IR/IRBuilder.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
26c4394386SDimitry Andric #include "llvm/IR/PatternMatch.h"
276122f3e6SDimitry Andric #include "llvm/Support/Debug.h"
286122f3e6SDimitry Andric #include "llvm/Support/raw_ostream.h"
294ba319b5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
306122f3e6SDimitry Andric 
316122f3e6SDimitry Andric using namespace llvm;
326122f3e6SDimitry Andric 
3391bc56edSDimitry Andric #define DEBUG_TYPE "indvars"
3491bc56edSDimitry Andric 
356122f3e6SDimitry Andric STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
366122f3e6SDimitry Andric STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
372cab237bSDimitry Andric STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
386122f3e6SDimitry Andric STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
397a7e6055SDimitry Andric STATISTIC(
407a7e6055SDimitry Andric     NumSimplifiedSDiv,
417a7e6055SDimitry Andric     "Number of IV signed division operations converted to unsigned division");
422cab237bSDimitry Andric STATISTIC(
432cab237bSDimitry Andric     NumSimplifiedSRem,
442cab237bSDimitry Andric     "Number of IV signed remainder operations converted to unsigned remainder");
456122f3e6SDimitry Andric STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
466122f3e6SDimitry Andric 
476122f3e6SDimitry Andric namespace {
4839d628a0SDimitry Andric   /// This is a utility for simplifying induction variables
496122f3e6SDimitry Andric   /// based on ScalarEvolution. It is the primary instrument of the
506122f3e6SDimitry Andric   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
516122f3e6SDimitry Andric   /// other loop passes that preserve SCEV.
526122f3e6SDimitry Andric   class SimplifyIndvar {
536122f3e6SDimitry Andric     Loop             *L;
546122f3e6SDimitry Andric     LoopInfo         *LI;
556122f3e6SDimitry Andric     ScalarEvolution  *SE;
567d523365SDimitry Andric     DominatorTree    *DT;
572cab237bSDimitry Andric     SCEVExpander     &Rewriter;
58f37b6182SDimitry Andric     SmallVectorImpl<WeakTrackingVH> &DeadInsts;
596122f3e6SDimitry Andric 
606122f3e6SDimitry Andric     bool Changed;
616122f3e6SDimitry Andric 
626122f3e6SDimitry Andric   public:
SimplifyIndvar(Loop * Loop,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,SCEVExpander & Rewriter,SmallVectorImpl<WeakTrackingVH> & Dead)637d523365SDimitry Andric     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
642cab237bSDimitry Andric                    LoopInfo *LI, SCEVExpander &Rewriter,
652cab237bSDimitry Andric                    SmallVectorImpl<WeakTrackingVH> &Dead)
662cab237bSDimitry Andric         : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
672cab237bSDimitry Andric           Changed(false) {
686122f3e6SDimitry Andric       assert(LI && "IV simplification requires LoopInfo");
696122f3e6SDimitry Andric     }
706122f3e6SDimitry Andric 
hasChanged() const716122f3e6SDimitry Andric     bool hasChanged() const { return Changed; }
726122f3e6SDimitry Andric 
736122f3e6SDimitry Andric     /// Iteratively perform simplification on a worklist of users of the
746122f3e6SDimitry Andric     /// specified induction variable. This is the top-level driver that applies
757d523365SDimitry Andric     /// all simplifications to users of an IV.
7691bc56edSDimitry Andric     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
776122f3e6SDimitry Andric 
786122f3e6SDimitry Andric     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
796122f3e6SDimitry Andric 
807d523365SDimitry Andric     bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
812cab237bSDimitry Andric     bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
827d523365SDimitry Andric 
833ca95b02SDimitry Andric     bool eliminateOverflowIntrinsic(CallInst *CI);
844ba319b5SDimitry Andric     bool eliminateTrunc(TruncInst *TI);
856122f3e6SDimitry Andric     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
862cab237bSDimitry Andric     bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
876122f3e6SDimitry Andric     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
882cab237bSDimitry Andric     void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
896122f3e6SDimitry Andric                              bool IsSigned);
902cab237bSDimitry Andric     void replaceRemWithNumerator(BinaryOperator *Rem);
912cab237bSDimitry Andric     void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
922cab237bSDimitry Andric     void replaceSRemWithURem(BinaryOperator *Rem);
937a7e6055SDimitry Andric     bool eliminateSDiv(BinaryOperator *SDiv);
9439d628a0SDimitry Andric     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
95c4394386SDimitry Andric     bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
966122f3e6SDimitry Andric   };
973dac3a9bSDimitry Andric }
986122f3e6SDimitry Andric 
9939d628a0SDimitry Andric /// Fold an IV operand into its use.  This removes increments of an
1006122f3e6SDimitry Andric /// aligned IV when used by a instruction that ignores the low bits.
1016122f3e6SDimitry Andric ///
1026122f3e6SDimitry Andric /// IVOperand is guaranteed SCEVable, but UseInst may not be.
1036122f3e6SDimitry Andric ///
1046122f3e6SDimitry Andric /// Return the operand of IVOperand for this induction variable if IVOperand can
1056122f3e6SDimitry Andric /// be folded (in case more folding opportunities have been exposed).
1066122f3e6SDimitry Andric /// Otherwise return null.
foldIVUser(Instruction * UseInst,Instruction * IVOperand)1076122f3e6SDimitry Andric Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
10891bc56edSDimitry Andric   Value *IVSrc = nullptr;
109*b5893f02SDimitry Andric   const unsigned OperIdx = 0;
11091bc56edSDimitry Andric   const SCEV *FoldedExpr = nullptr;
111*b5893f02SDimitry Andric   bool MustDropExactFlag = false;
1126122f3e6SDimitry Andric   switch (UseInst->getOpcode()) {
1136122f3e6SDimitry Andric   default:
11491bc56edSDimitry Andric     return nullptr;
1156122f3e6SDimitry Andric   case Instruction::UDiv:
1166122f3e6SDimitry Andric   case Instruction::LShr:
1176122f3e6SDimitry Andric     // We're only interested in the case where we know something about
1186122f3e6SDimitry Andric     // the numerator and have a constant denominator.
1196122f3e6SDimitry Andric     if (IVOperand != UseInst->getOperand(OperIdx) ||
1206122f3e6SDimitry Andric         !isa<ConstantInt>(UseInst->getOperand(1)))
12191bc56edSDimitry Andric       return nullptr;
1226122f3e6SDimitry Andric 
1236122f3e6SDimitry Andric     // Attempt to fold a binary operator with constant operand.
1246122f3e6SDimitry Andric     // e.g. ((I + 1) >> 2) => I >> 2
125dff0c46cSDimitry Andric     if (!isa<BinaryOperator>(IVOperand)
126dff0c46cSDimitry Andric         || !isa<ConstantInt>(IVOperand->getOperand(1)))
12791bc56edSDimitry Andric       return nullptr;
1286122f3e6SDimitry Andric 
1296122f3e6SDimitry Andric     IVSrc = IVOperand->getOperand(0);
1306122f3e6SDimitry Andric     // IVSrc must be the (SCEVable) IV, since the other operand is const.
1316122f3e6SDimitry Andric     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
1326122f3e6SDimitry Andric 
1336122f3e6SDimitry Andric     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
1346122f3e6SDimitry Andric     if (UseInst->getOpcode() == Instruction::LShr) {
1356122f3e6SDimitry Andric       // Get a constant for the divisor. See createSCEV.
1366122f3e6SDimitry Andric       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
1376122f3e6SDimitry Andric       if (D->getValue().uge(BitWidth))
13891bc56edSDimitry Andric         return nullptr;
1396122f3e6SDimitry Andric 
1406122f3e6SDimitry Andric       D = ConstantInt::get(UseInst->getContext(),
141f785676fSDimitry Andric                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
1426122f3e6SDimitry Andric     }
1436122f3e6SDimitry Andric     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
144*b5893f02SDimitry Andric     // We might have 'exact' flag set at this point which will no longer be
145*b5893f02SDimitry Andric     // correct after we make the replacement.
146*b5893f02SDimitry Andric     if (UseInst->isExact() &&
147*b5893f02SDimitry Andric         SE->getSCEV(IVSrc) != SE->getMulExpr(FoldedExpr, SE->getSCEV(D)))
148*b5893f02SDimitry Andric       MustDropExactFlag = true;
1496122f3e6SDimitry Andric   }
1506122f3e6SDimitry Andric   // We have something that might fold it's operand. Compare SCEVs.
1516122f3e6SDimitry Andric   if (!SE->isSCEVable(UseInst->getType()))
15291bc56edSDimitry Andric     return nullptr;
1536122f3e6SDimitry Andric 
1546122f3e6SDimitry Andric   // Bypass the operand if SCEV can prove it has no effect.
1556122f3e6SDimitry Andric   if (SE->getSCEV(UseInst) != FoldedExpr)
15691bc56edSDimitry Andric     return nullptr;
1576122f3e6SDimitry Andric 
1584ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
1596122f3e6SDimitry Andric                     << " -> " << *UseInst << '\n');
1606122f3e6SDimitry Andric 
1616122f3e6SDimitry Andric   UseInst->setOperand(OperIdx, IVSrc);
1626122f3e6SDimitry Andric   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
1636122f3e6SDimitry Andric 
164*b5893f02SDimitry Andric   if (MustDropExactFlag)
165*b5893f02SDimitry Andric     UseInst->dropPoisonGeneratingFlags();
166*b5893f02SDimitry Andric 
1676122f3e6SDimitry Andric   ++NumElimOperand;
1686122f3e6SDimitry Andric   Changed = true;
1696122f3e6SDimitry Andric   if (IVOperand->use_empty())
17097bc6c73SDimitry Andric     DeadInsts.emplace_back(IVOperand);
1716122f3e6SDimitry Andric   return IVSrc;
1726122f3e6SDimitry Andric }
1736122f3e6SDimitry Andric 
makeIVComparisonInvariant(ICmpInst * ICmp,Value * IVOperand)1742cab237bSDimitry Andric bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
1752cab237bSDimitry Andric                                                Value *IVOperand) {
1762cab237bSDimitry Andric   unsigned IVOperIdx = 0;
1772cab237bSDimitry Andric   ICmpInst::Predicate Pred = ICmp->getPredicate();
1782cab237bSDimitry Andric   if (IVOperand != ICmp->getOperand(0)) {
1792cab237bSDimitry Andric     // Swapped
1802cab237bSDimitry Andric     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1812cab237bSDimitry Andric     IVOperIdx = 1;
1822cab237bSDimitry Andric     Pred = ICmpInst::getSwappedPredicate(Pred);
1832cab237bSDimitry Andric   }
1842cab237bSDimitry Andric 
1852cab237bSDimitry Andric   // Get the SCEVs for the ICmp operands (in the specific context of the
1862cab237bSDimitry Andric   // current loop)
1872cab237bSDimitry Andric   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1882cab237bSDimitry Andric   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
1892cab237bSDimitry Andric   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
1902cab237bSDimitry Andric 
1912cab237bSDimitry Andric   ICmpInst::Predicate InvariantPredicate;
1922cab237bSDimitry Andric   const SCEV *InvariantLHS, *InvariantRHS;
1932cab237bSDimitry Andric 
1942cab237bSDimitry Andric   auto *PN = dyn_cast<PHINode>(IVOperand);
1952cab237bSDimitry Andric   if (!PN)
1962cab237bSDimitry Andric     return false;
1972cab237bSDimitry Andric   if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
1982cab237bSDimitry Andric                                     InvariantLHS, InvariantRHS))
1992cab237bSDimitry Andric     return false;
2002cab237bSDimitry Andric 
2012cab237bSDimitry Andric   // Rewrite the comparison to a loop invariant comparison if it can be done
2022cab237bSDimitry Andric   // cheaply, where cheaply means "we don't need to emit any new
2032cab237bSDimitry Andric   // instructions".
2042cab237bSDimitry Andric 
2052cab237bSDimitry Andric   SmallDenseMap<const SCEV*, Value*> CheapExpansions;
2062cab237bSDimitry Andric   CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
2072cab237bSDimitry Andric   CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
2082cab237bSDimitry Andric 
2092cab237bSDimitry Andric   // TODO: Support multiple entry loops?  (We currently bail out of these in
2102cab237bSDimitry Andric   // the IndVarSimplify pass)
2112cab237bSDimitry Andric   if (auto *BB = L->getLoopPredecessor()) {
2122cab237bSDimitry Andric     const int Idx = PN->getBasicBlockIndex(BB);
2132cab237bSDimitry Andric     if (Idx >= 0) {
2142cab237bSDimitry Andric       Value *Incoming = PN->getIncomingValue(Idx);
2152cab237bSDimitry Andric       const SCEV *IncomingS = SE->getSCEV(Incoming);
2162cab237bSDimitry Andric       CheapExpansions[IncomingS] = Incoming;
2172cab237bSDimitry Andric     }
2182cab237bSDimitry Andric   }
2192cab237bSDimitry Andric   Value *NewLHS = CheapExpansions[InvariantLHS];
2202cab237bSDimitry Andric   Value *NewRHS = CheapExpansions[InvariantRHS];
2212cab237bSDimitry Andric 
2222cab237bSDimitry Andric   if (!NewLHS)
2232cab237bSDimitry Andric     if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
2242cab237bSDimitry Andric       NewLHS = ConstLHS->getValue();
2252cab237bSDimitry Andric   if (!NewRHS)
2262cab237bSDimitry Andric     if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
2272cab237bSDimitry Andric       NewRHS = ConstRHS->getValue();
2282cab237bSDimitry Andric 
2292cab237bSDimitry Andric   if (!NewLHS || !NewRHS)
2302cab237bSDimitry Andric     // We could not find an existing value to replace either LHS or RHS.
2312cab237bSDimitry Andric     // Generating new instructions has subtler tradeoffs, so avoid doing that
2322cab237bSDimitry Andric     // for now.
2332cab237bSDimitry Andric     return false;
2342cab237bSDimitry Andric 
2354ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
2362cab237bSDimitry Andric   ICmp->setPredicate(InvariantPredicate);
2372cab237bSDimitry Andric   ICmp->setOperand(0, NewLHS);
2382cab237bSDimitry Andric   ICmp->setOperand(1, NewRHS);
2392cab237bSDimitry Andric   return true;
2402cab237bSDimitry Andric }
2412cab237bSDimitry Andric 
24239d628a0SDimitry Andric /// SimplifyIVUsers helper for eliminating useless
2436122f3e6SDimitry Andric /// comparisons against an induction variable.
eliminateIVComparison(ICmpInst * ICmp,Value * IVOperand)2446122f3e6SDimitry Andric void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
2456122f3e6SDimitry Andric   unsigned IVOperIdx = 0;
2466122f3e6SDimitry Andric   ICmpInst::Predicate Pred = ICmp->getPredicate();
247c4394386SDimitry Andric   ICmpInst::Predicate OriginalPred = Pred;
2486122f3e6SDimitry Andric   if (IVOperand != ICmp->getOperand(0)) {
2496122f3e6SDimitry Andric     // Swapped
2506122f3e6SDimitry Andric     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
2516122f3e6SDimitry Andric     IVOperIdx = 1;
2526122f3e6SDimitry Andric     Pred = ICmpInst::getSwappedPredicate(Pred);
2536122f3e6SDimitry Andric   }
2546122f3e6SDimitry Andric 
2552cab237bSDimitry Andric   // Get the SCEVs for the ICmp operands (in the specific context of the
2562cab237bSDimitry Andric   // current loop)
2576122f3e6SDimitry Andric   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
2582cab237bSDimitry Andric   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
2592cab237bSDimitry Andric   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
2607d523365SDimitry Andric 
2616122f3e6SDimitry Andric   // If the condition is always true or always false, replace it with
2626122f3e6SDimitry Andric   // a constant value.
2637d523365SDimitry Andric   if (SE->isKnownPredicate(Pred, S, X)) {
2646122f3e6SDimitry Andric     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
2657d523365SDimitry Andric     DeadInsts.emplace_back(ICmp);
2664ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
2677d523365SDimitry Andric   } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
2686122f3e6SDimitry Andric     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
2697d523365SDimitry Andric     DeadInsts.emplace_back(ICmp);
2704ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
2712cab237bSDimitry Andric   } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
2722cab237bSDimitry Andric     // fallthrough to end of function
273c4394386SDimitry Andric   } else if (ICmpInst::isSigned(OriginalPred) &&
274c4394386SDimitry Andric              SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
275c4394386SDimitry Andric     // If we were unable to make anything above, all we can is to canonicalize
276c4394386SDimitry Andric     // the comparison hoping that it will open the doors for other
277c4394386SDimitry Andric     // optimizations. If we find out that we compare two non-negative values,
278c4394386SDimitry Andric     // we turn the instruction's predicate to its unsigned version. Note that
279c4394386SDimitry Andric     // we cannot rely on Pred here unless we check if we have swapped it.
280c4394386SDimitry Andric     assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
2814ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
2824ba319b5SDimitry Andric                       << '\n');
283c4394386SDimitry Andric     ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
2847d523365SDimitry Andric   } else
2857d523365SDimitry Andric     return;
2867d523365SDimitry Andric 
2876122f3e6SDimitry Andric   ++NumElimCmp;
2886122f3e6SDimitry Andric   Changed = true;
2896122f3e6SDimitry Andric }
2906122f3e6SDimitry Andric 
eliminateSDiv(BinaryOperator * SDiv)2917a7e6055SDimitry Andric bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
2927a7e6055SDimitry Andric   // Get the SCEVs for the ICmp operands.
2937a7e6055SDimitry Andric   auto *N = SE->getSCEV(SDiv->getOperand(0));
2947a7e6055SDimitry Andric   auto *D = SE->getSCEV(SDiv->getOperand(1));
2957a7e6055SDimitry Andric 
2967a7e6055SDimitry Andric   // Simplify unnecessary loops away.
2977a7e6055SDimitry Andric   const Loop *L = LI->getLoopFor(SDiv->getParent());
2987a7e6055SDimitry Andric   N = SE->getSCEVAtScope(N, L);
2997a7e6055SDimitry Andric   D = SE->getSCEVAtScope(D, L);
3007a7e6055SDimitry Andric 
3017a7e6055SDimitry Andric   // Replace sdiv by udiv if both of the operands are non-negative
3027a7e6055SDimitry Andric   if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
3037a7e6055SDimitry Andric     auto *UDiv = BinaryOperator::Create(
3047a7e6055SDimitry Andric         BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
3057a7e6055SDimitry Andric         SDiv->getName() + ".udiv", SDiv);
3067a7e6055SDimitry Andric     UDiv->setIsExact(SDiv->isExact());
3077a7e6055SDimitry Andric     SDiv->replaceAllUsesWith(UDiv);
3084ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
3097a7e6055SDimitry Andric     ++NumSimplifiedSDiv;
3107a7e6055SDimitry Andric     Changed = true;
3117a7e6055SDimitry Andric     DeadInsts.push_back(SDiv);
3127a7e6055SDimitry Andric     return true;
3137a7e6055SDimitry Andric   }
3147a7e6055SDimitry Andric 
3157a7e6055SDimitry Andric   return false;
3167a7e6055SDimitry Andric }
3177a7e6055SDimitry Andric 
3182cab237bSDimitry Andric // i %s n -> i %u n if i >= 0 and n >= 0
replaceSRemWithURem(BinaryOperator * Rem)3192cab237bSDimitry Andric void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
3202cab237bSDimitry Andric   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
3212cab237bSDimitry Andric   auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
3222cab237bSDimitry Andric                                       Rem->getName() + ".urem", Rem);
3232cab237bSDimitry Andric   Rem->replaceAllUsesWith(URem);
3244ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
3252cab237bSDimitry Andric   ++NumSimplifiedSRem;
3262cab237bSDimitry Andric   Changed = true;
3272cab237bSDimitry Andric   DeadInsts.emplace_back(Rem);
3286122f3e6SDimitry Andric }
3296122f3e6SDimitry Andric 
3302cab237bSDimitry Andric // i % n  -->  i  if i is in [0,n).
replaceRemWithNumerator(BinaryOperator * Rem)3312cab237bSDimitry Andric void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
3322cab237bSDimitry Andric   Rem->replaceAllUsesWith(Rem->getOperand(0));
3334ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
3346122f3e6SDimitry Andric   ++NumElimRem;
3356122f3e6SDimitry Andric   Changed = true;
33697bc6c73SDimitry Andric   DeadInsts.emplace_back(Rem);
3376122f3e6SDimitry Andric }
3386122f3e6SDimitry Andric 
3392cab237bSDimitry Andric // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
replaceRemWithNumeratorOrZero(BinaryOperator * Rem)3402cab237bSDimitry Andric void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
3412cab237bSDimitry Andric   auto *T = Rem->getType();
3422cab237bSDimitry Andric   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
3432cab237bSDimitry Andric   ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
3442cab237bSDimitry Andric   SelectInst *Sel =
3452cab237bSDimitry Andric       SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
3462cab237bSDimitry Andric   Rem->replaceAllUsesWith(Sel);
3474ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
3482cab237bSDimitry Andric   ++NumElimRem;
3492cab237bSDimitry Andric   Changed = true;
3502cab237bSDimitry Andric   DeadInsts.emplace_back(Rem);
3512cab237bSDimitry Andric }
3522cab237bSDimitry Andric 
3532cab237bSDimitry Andric /// SimplifyIVUsers helper for eliminating useless remainder operations
3542cab237bSDimitry Andric /// operating on an induction variable or replacing srem by urem.
simplifyIVRemainder(BinaryOperator * Rem,Value * IVOperand,bool IsSigned)3552cab237bSDimitry Andric void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
3562cab237bSDimitry Andric                                          bool IsSigned) {
3572cab237bSDimitry Andric   auto *NValue = Rem->getOperand(0);
3582cab237bSDimitry Andric   auto *DValue = Rem->getOperand(1);
3592cab237bSDimitry Andric   // We're only interested in the case where we know something about
3602cab237bSDimitry Andric   // the numerator, unless it is a srem, because we want to replace srem by urem
3612cab237bSDimitry Andric   // in general.
3622cab237bSDimitry Andric   bool UsedAsNumerator = IVOperand == NValue;
3632cab237bSDimitry Andric   if (!UsedAsNumerator && !IsSigned)
3642cab237bSDimitry Andric     return;
3652cab237bSDimitry Andric 
3662cab237bSDimitry Andric   const SCEV *N = SE->getSCEV(NValue);
3672cab237bSDimitry Andric 
3682cab237bSDimitry Andric   // Simplify unnecessary loops away.
3692cab237bSDimitry Andric   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
3702cab237bSDimitry Andric   N = SE->getSCEVAtScope(N, ICmpLoop);
3712cab237bSDimitry Andric 
3722cab237bSDimitry Andric   bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
3732cab237bSDimitry Andric 
3742cab237bSDimitry Andric   // Do not proceed if the Numerator may be negative
3752cab237bSDimitry Andric   if (!IsNumeratorNonNegative)
3762cab237bSDimitry Andric     return;
3772cab237bSDimitry Andric 
3782cab237bSDimitry Andric   const SCEV *D = SE->getSCEV(DValue);
3792cab237bSDimitry Andric   D = SE->getSCEVAtScope(D, ICmpLoop);
3802cab237bSDimitry Andric 
3812cab237bSDimitry Andric   if (UsedAsNumerator) {
3822cab237bSDimitry Andric     auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
3832cab237bSDimitry Andric     if (SE->isKnownPredicate(LT, N, D)) {
3842cab237bSDimitry Andric       replaceRemWithNumerator(Rem);
3852cab237bSDimitry Andric       return;
3862cab237bSDimitry Andric     }
3872cab237bSDimitry Andric 
3882cab237bSDimitry Andric     auto *T = Rem->getType();
3892cab237bSDimitry Andric     const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
3902cab237bSDimitry Andric     if (SE->isKnownPredicate(LT, NLessOne, D)) {
3912cab237bSDimitry Andric       replaceRemWithNumeratorOrZero(Rem);
3922cab237bSDimitry Andric       return;
3932cab237bSDimitry Andric     }
3942cab237bSDimitry Andric   }
3952cab237bSDimitry Andric 
3962cab237bSDimitry Andric   // Try to replace SRem with URem, if both N and D are known non-negative.
3972cab237bSDimitry Andric   // Since we had already check N, we only need to check D now
3982cab237bSDimitry Andric   if (!IsSigned || !SE->isKnownNonNegative(D))
3992cab237bSDimitry Andric     return;
4002cab237bSDimitry Andric 
4012cab237bSDimitry Andric   replaceSRemWithURem(Rem);
4022cab237bSDimitry Andric }
4032cab237bSDimitry Andric 
eliminateOverflowIntrinsic(CallInst * CI)4043ca95b02SDimitry Andric bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
4053ca95b02SDimitry Andric   auto *F = CI->getCalledFunction();
4063ca95b02SDimitry Andric   if (!F)
4073ca95b02SDimitry Andric     return false;
4083ca95b02SDimitry Andric 
4093ca95b02SDimitry Andric   typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
41024d58133SDimitry Andric       const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
4113ca95b02SDimitry Andric   typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
412a580b014SDimitry Andric       const SCEV *, Type *, unsigned);
4133ca95b02SDimitry Andric 
4143ca95b02SDimitry Andric   OperationFunctionTy Operation;
4153ca95b02SDimitry Andric   ExtensionFunctionTy Extension;
4163ca95b02SDimitry Andric 
4173ca95b02SDimitry Andric   Instruction::BinaryOps RawOp;
4183ca95b02SDimitry Andric 
4193ca95b02SDimitry Andric   // We always have exactly one of nsw or nuw.  If NoSignedOverflow is false, we
4203ca95b02SDimitry Andric   // have nuw.
4213ca95b02SDimitry Andric   bool NoSignedOverflow;
4223ca95b02SDimitry Andric 
4233ca95b02SDimitry Andric   switch (F->getIntrinsicID()) {
4243ca95b02SDimitry Andric   default:
4253ca95b02SDimitry Andric     return false;
4263ca95b02SDimitry Andric 
4273ca95b02SDimitry Andric   case Intrinsic::sadd_with_overflow:
4283ca95b02SDimitry Andric     Operation = &ScalarEvolution::getAddExpr;
4293ca95b02SDimitry Andric     Extension = &ScalarEvolution::getSignExtendExpr;
4303ca95b02SDimitry Andric     RawOp = Instruction::Add;
4313ca95b02SDimitry Andric     NoSignedOverflow = true;
4323ca95b02SDimitry Andric     break;
4333ca95b02SDimitry Andric 
4343ca95b02SDimitry Andric   case Intrinsic::uadd_with_overflow:
4353ca95b02SDimitry Andric     Operation = &ScalarEvolution::getAddExpr;
4363ca95b02SDimitry Andric     Extension = &ScalarEvolution::getZeroExtendExpr;
4373ca95b02SDimitry Andric     RawOp = Instruction::Add;
4383ca95b02SDimitry Andric     NoSignedOverflow = false;
4393ca95b02SDimitry Andric     break;
4403ca95b02SDimitry Andric 
4413ca95b02SDimitry Andric   case Intrinsic::ssub_with_overflow:
4423ca95b02SDimitry Andric     Operation = &ScalarEvolution::getMinusSCEV;
4433ca95b02SDimitry Andric     Extension = &ScalarEvolution::getSignExtendExpr;
4443ca95b02SDimitry Andric     RawOp = Instruction::Sub;
4453ca95b02SDimitry Andric     NoSignedOverflow = true;
4463ca95b02SDimitry Andric     break;
4473ca95b02SDimitry Andric 
4483ca95b02SDimitry Andric   case Intrinsic::usub_with_overflow:
4493ca95b02SDimitry Andric     Operation = &ScalarEvolution::getMinusSCEV;
4503ca95b02SDimitry Andric     Extension = &ScalarEvolution::getZeroExtendExpr;
4513ca95b02SDimitry Andric     RawOp = Instruction::Sub;
4523ca95b02SDimitry Andric     NoSignedOverflow = false;
4533ca95b02SDimitry Andric     break;
4543ca95b02SDimitry Andric   }
4553ca95b02SDimitry Andric 
4563ca95b02SDimitry Andric   const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
4573ca95b02SDimitry Andric   const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
4583ca95b02SDimitry Andric 
4593ca95b02SDimitry Andric   auto *NarrowTy = cast<IntegerType>(LHS->getType());
4603ca95b02SDimitry Andric   auto *WideTy =
4613ca95b02SDimitry Andric     IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
4623ca95b02SDimitry Andric 
4633ca95b02SDimitry Andric   const SCEV *A =
464a580b014SDimitry Andric       (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
465a580b014SDimitry Andric                        WideTy, 0);
4663ca95b02SDimitry Andric   const SCEV *B =
467a580b014SDimitry Andric       (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
468a580b014SDimitry Andric                        (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
4693ca95b02SDimitry Andric 
4703ca95b02SDimitry Andric   if (A != B)
4713ca95b02SDimitry Andric     return false;
4723ca95b02SDimitry Andric 
4733ca95b02SDimitry Andric   // Proved no overflow, nuke the overflow check and, if possible, the overflow
4743ca95b02SDimitry Andric   // intrinsic as well.
4753ca95b02SDimitry Andric 
4763ca95b02SDimitry Andric   BinaryOperator *NewResult = BinaryOperator::Create(
4773ca95b02SDimitry Andric       RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
4783ca95b02SDimitry Andric 
4793ca95b02SDimitry Andric   if (NoSignedOverflow)
4803ca95b02SDimitry Andric     NewResult->setHasNoSignedWrap(true);
4813ca95b02SDimitry Andric   else
4823ca95b02SDimitry Andric     NewResult->setHasNoUnsignedWrap(true);
4833ca95b02SDimitry Andric 
4843ca95b02SDimitry Andric   SmallVector<ExtractValueInst *, 4> ToDelete;
4853ca95b02SDimitry Andric 
4863ca95b02SDimitry Andric   for (auto *U : CI->users()) {
4873ca95b02SDimitry Andric     if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4883ca95b02SDimitry Andric       if (EVI->getIndices()[0] == 1)
4893ca95b02SDimitry Andric         EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
4903ca95b02SDimitry Andric       else {
4913ca95b02SDimitry Andric         assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
4923ca95b02SDimitry Andric         EVI->replaceAllUsesWith(NewResult);
4933ca95b02SDimitry Andric       }
4943ca95b02SDimitry Andric       ToDelete.push_back(EVI);
4953ca95b02SDimitry Andric     }
4963ca95b02SDimitry Andric   }
4973ca95b02SDimitry Andric 
4983ca95b02SDimitry Andric   for (auto *EVI : ToDelete)
4993ca95b02SDimitry Andric     EVI->eraseFromParent();
5003ca95b02SDimitry Andric 
5013ca95b02SDimitry Andric   if (CI->use_empty())
5023ca95b02SDimitry Andric     CI->eraseFromParent();
5033ca95b02SDimitry Andric 
5043ca95b02SDimitry Andric   return true;
5053ca95b02SDimitry Andric }
5063ca95b02SDimitry Andric 
eliminateTrunc(TruncInst * TI)5074ba319b5SDimitry Andric bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
5084ba319b5SDimitry Andric   // It is always legal to replace
5094ba319b5SDimitry Andric   //   icmp <pred> i32 trunc(iv), n
5104ba319b5SDimitry Andric   // with
5114ba319b5SDimitry Andric   //   icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
5124ba319b5SDimitry Andric   // Or with
5134ba319b5SDimitry Andric   //   icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
5144ba319b5SDimitry Andric   // Or with either of these if pred is an equality predicate.
5154ba319b5SDimitry Andric   //
5164ba319b5SDimitry Andric   // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
5174ba319b5SDimitry Andric   // every comparison which uses trunc, it means that we can replace each of
5184ba319b5SDimitry Andric   // them with comparison of iv against sext/zext(n). We no longer need trunc
5194ba319b5SDimitry Andric   // after that.
5204ba319b5SDimitry Andric   //
5214ba319b5SDimitry Andric   // TODO: Should we do this if we can widen *some* comparisons, but not all
5224ba319b5SDimitry Andric   // of them? Sometimes it is enough to enable other optimizations, but the
5234ba319b5SDimitry Andric   // trunc instruction will stay in the loop.
5244ba319b5SDimitry Andric   Value *IV = TI->getOperand(0);
5254ba319b5SDimitry Andric   Type *IVTy = IV->getType();
5264ba319b5SDimitry Andric   const SCEV *IVSCEV = SE->getSCEV(IV);
5274ba319b5SDimitry Andric   const SCEV *TISCEV = SE->getSCEV(TI);
5284ba319b5SDimitry Andric 
5294ba319b5SDimitry Andric   // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
5304ba319b5SDimitry Andric   // get rid of trunc
5314ba319b5SDimitry Andric   bool DoesSExtCollapse = false;
5324ba319b5SDimitry Andric   bool DoesZExtCollapse = false;
5334ba319b5SDimitry Andric   if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
5344ba319b5SDimitry Andric     DoesSExtCollapse = true;
5354ba319b5SDimitry Andric   if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
5364ba319b5SDimitry Andric     DoesZExtCollapse = true;
5374ba319b5SDimitry Andric 
5384ba319b5SDimitry Andric   // If neither sext nor zext does collapse, it is not profitable to do any
5394ba319b5SDimitry Andric   // transform. Bail.
5404ba319b5SDimitry Andric   if (!DoesSExtCollapse && !DoesZExtCollapse)
5414ba319b5SDimitry Andric     return false;
5424ba319b5SDimitry Andric 
5434ba319b5SDimitry Andric   // Collect users of the trunc that look like comparisons against invariants.
5444ba319b5SDimitry Andric   // Bail if we find something different.
5454ba319b5SDimitry Andric   SmallVector<ICmpInst *, 4> ICmpUsers;
5464ba319b5SDimitry Andric   for (auto *U : TI->users()) {
5474ba319b5SDimitry Andric     // We don't care about users in unreachable blocks.
5484ba319b5SDimitry Andric     if (isa<Instruction>(U) &&
5494ba319b5SDimitry Andric         !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
5504ba319b5SDimitry Andric       continue;
5514ba319b5SDimitry Andric     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
5524ba319b5SDimitry Andric       if (ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) {
5534ba319b5SDimitry Andric         assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
5544ba319b5SDimitry Andric         // If we cannot get rid of trunc, bail.
5554ba319b5SDimitry Andric         if (ICI->isSigned() && !DoesSExtCollapse)
5564ba319b5SDimitry Andric           return false;
5574ba319b5SDimitry Andric         if (ICI->isUnsigned() && !DoesZExtCollapse)
5584ba319b5SDimitry Andric           return false;
5594ba319b5SDimitry Andric         // For equality, either signed or unsigned works.
5604ba319b5SDimitry Andric         ICmpUsers.push_back(ICI);
5614ba319b5SDimitry Andric       } else
5624ba319b5SDimitry Andric         return false;
5634ba319b5SDimitry Andric     } else
5644ba319b5SDimitry Andric       return false;
5654ba319b5SDimitry Andric   }
5664ba319b5SDimitry Andric 
5674ba319b5SDimitry Andric   auto CanUseZExt = [&](ICmpInst *ICI) {
5684ba319b5SDimitry Andric     // Unsigned comparison can be widened as unsigned.
5694ba319b5SDimitry Andric     if (ICI->isUnsigned())
5704ba319b5SDimitry Andric       return true;
5714ba319b5SDimitry Andric     // Is it profitable to do zext?
5724ba319b5SDimitry Andric     if (!DoesZExtCollapse)
5734ba319b5SDimitry Andric       return false;
5744ba319b5SDimitry Andric     // For equality, we can safely zext both parts.
5754ba319b5SDimitry Andric     if (ICI->isEquality())
5764ba319b5SDimitry Andric       return true;
5774ba319b5SDimitry Andric     // Otherwise we can only use zext when comparing two non-negative or two
5784ba319b5SDimitry Andric     // negative values. But in practice, we will never pass DoesZExtCollapse
5794ba319b5SDimitry Andric     // check for a negative value, because zext(trunc(x)) is non-negative. So
5804ba319b5SDimitry Andric     // it only make sense to check for non-negativity here.
5814ba319b5SDimitry Andric     const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
5824ba319b5SDimitry Andric     const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
5834ba319b5SDimitry Andric     return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
5844ba319b5SDimitry Andric   };
5854ba319b5SDimitry Andric   // Replace all comparisons against trunc with comparisons against IV.
5864ba319b5SDimitry Andric   for (auto *ICI : ICmpUsers) {
5874ba319b5SDimitry Andric     auto *Op1 = ICI->getOperand(1);
5884ba319b5SDimitry Andric     Instruction *Ext = nullptr;
5894ba319b5SDimitry Andric     // For signed/unsigned predicate, replace the old comparison with comparison
5904ba319b5SDimitry Andric     // of immediate IV against sext/zext of the invariant argument. If we can
5914ba319b5SDimitry Andric     // use either sext or zext (i.e. we are dealing with equality predicate),
5924ba319b5SDimitry Andric     // then prefer zext as a more canonical form.
5934ba319b5SDimitry Andric     // TODO: If we see a signed comparison which can be turned into unsigned,
5944ba319b5SDimitry Andric     // we can do it here for canonicalization purposes.
5954ba319b5SDimitry Andric     ICmpInst::Predicate Pred = ICI->getPredicate();
5964ba319b5SDimitry Andric     if (CanUseZExt(ICI)) {
5974ba319b5SDimitry Andric       assert(DoesZExtCollapse && "Unprofitable zext?");
5984ba319b5SDimitry Andric       Ext = new ZExtInst(Op1, IVTy, "zext", ICI);
5994ba319b5SDimitry Andric       Pred = ICmpInst::getUnsignedPredicate(Pred);
6004ba319b5SDimitry Andric     } else {
6014ba319b5SDimitry Andric       assert(DoesSExtCollapse && "Unprofitable sext?");
6024ba319b5SDimitry Andric       Ext = new SExtInst(Op1, IVTy, "sext", ICI);
6034ba319b5SDimitry Andric       assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
6044ba319b5SDimitry Andric     }
6054ba319b5SDimitry Andric     bool Changed;
6064ba319b5SDimitry Andric     L->makeLoopInvariant(Ext, Changed);
6074ba319b5SDimitry Andric     (void)Changed;
6084ba319b5SDimitry Andric     ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext);
6094ba319b5SDimitry Andric     ICI->replaceAllUsesWith(NewICI);
6104ba319b5SDimitry Andric     DeadInsts.emplace_back(ICI);
6114ba319b5SDimitry Andric   }
6124ba319b5SDimitry Andric 
6134ba319b5SDimitry Andric   // Trunc no longer needed.
6144ba319b5SDimitry Andric   TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
6154ba319b5SDimitry Andric   DeadInsts.emplace_back(TI);
6164ba319b5SDimitry Andric   return true;
6174ba319b5SDimitry Andric }
6184ba319b5SDimitry Andric 
6197d523365SDimitry Andric /// Eliminate an operation that consumes a simple IV and has no observable
6207d523365SDimitry Andric /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
6217d523365SDimitry Andric /// but UseInst may not be.
eliminateIVUser(Instruction * UseInst,Instruction * IVOperand)6226122f3e6SDimitry Andric bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
6236122f3e6SDimitry Andric                                      Instruction *IVOperand) {
6246122f3e6SDimitry Andric   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
6256122f3e6SDimitry Andric     eliminateIVComparison(ICmp, IVOperand);
6266122f3e6SDimitry Andric     return true;
6276122f3e6SDimitry Andric   }
6287a7e6055SDimitry Andric   if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
6297a7e6055SDimitry Andric     bool IsSRem = Bin->getOpcode() == Instruction::SRem;
6307a7e6055SDimitry Andric     if (IsSRem || Bin->getOpcode() == Instruction::URem) {
6312cab237bSDimitry Andric       simplifyIVRemainder(Bin, IVOperand, IsSRem);
6326122f3e6SDimitry Andric       return true;
6336122f3e6SDimitry Andric     }
6347a7e6055SDimitry Andric 
6357a7e6055SDimitry Andric     if (Bin->getOpcode() == Instruction::SDiv)
6367a7e6055SDimitry Andric       return eliminateSDiv(Bin);
6376122f3e6SDimitry Andric   }
6386122f3e6SDimitry Andric 
6393ca95b02SDimitry Andric   if (auto *CI = dyn_cast<CallInst>(UseInst))
6403ca95b02SDimitry Andric     if (eliminateOverflowIntrinsic(CI))
6413ca95b02SDimitry Andric       return true;
6423ca95b02SDimitry Andric 
6434ba319b5SDimitry Andric   if (auto *TI = dyn_cast<TruncInst>(UseInst))
6444ba319b5SDimitry Andric     if (eliminateTrunc(TI))
6454ba319b5SDimitry Andric       return true;
6464ba319b5SDimitry Andric 
6477d523365SDimitry Andric   if (eliminateIdentitySCEV(UseInst, IVOperand))
6487d523365SDimitry Andric     return true;
6497d523365SDimitry Andric 
6507d523365SDimitry Andric   return false;
6517d523365SDimitry Andric }
6527d523365SDimitry Andric 
GetLoopInvariantInsertPosition(Loop * L,Instruction * Hint)6532cab237bSDimitry Andric static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
6542cab237bSDimitry Andric   if (auto *BB = L->getLoopPreheader())
6552cab237bSDimitry Andric     return BB->getTerminator();
6562cab237bSDimitry Andric 
6572cab237bSDimitry Andric   return Hint;
6582cab237bSDimitry Andric }
6592cab237bSDimitry Andric 
6602cab237bSDimitry Andric /// Replace the UseInst with a constant if possible.
replaceIVUserWithLoopInvariant(Instruction * I)6612cab237bSDimitry Andric bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
6622cab237bSDimitry Andric   if (!SE->isSCEVable(I->getType()))
6632cab237bSDimitry Andric     return false;
6642cab237bSDimitry Andric 
6652cab237bSDimitry Andric   // Get the symbolic expression for this instruction.
6662cab237bSDimitry Andric   const SCEV *S = SE->getSCEV(I);
6672cab237bSDimitry Andric 
6682cab237bSDimitry Andric   if (!SE->isLoopInvariant(S, L))
6692cab237bSDimitry Andric     return false;
6702cab237bSDimitry Andric 
6712cab237bSDimitry Andric   // Do not generate something ridiculous even if S is loop invariant.
6722cab237bSDimitry Andric   if (Rewriter.isHighCostExpansion(S, L, I))
6732cab237bSDimitry Andric     return false;
6742cab237bSDimitry Andric 
6752cab237bSDimitry Andric   auto *IP = GetLoopInvariantInsertPosition(L, I);
6762cab237bSDimitry Andric   auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
6772cab237bSDimitry Andric 
6782cab237bSDimitry Andric   I->replaceAllUsesWith(Invariant);
6794ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
6802cab237bSDimitry Andric                     << " with loop invariant: " << *S << '\n');
6812cab237bSDimitry Andric   ++NumFoldedUser;
6822cab237bSDimitry Andric   Changed = true;
6832cab237bSDimitry Andric   DeadInsts.emplace_back(I);
6842cab237bSDimitry Andric   return true;
6852cab237bSDimitry Andric }
6862cab237bSDimitry Andric 
6877d523365SDimitry Andric /// Eliminate any operation that SCEV can prove is an identity function.
eliminateIdentitySCEV(Instruction * UseInst,Instruction * IVOperand)6887d523365SDimitry Andric bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
6897d523365SDimitry Andric                                            Instruction *IVOperand) {
6906122f3e6SDimitry Andric   if (!SE->isSCEVable(UseInst->getType()) ||
6916122f3e6SDimitry Andric       (UseInst->getType() != IVOperand->getType()) ||
6926122f3e6SDimitry Andric       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
6936122f3e6SDimitry Andric     return false;
6946122f3e6SDimitry Andric 
6957d523365SDimitry Andric   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
6967d523365SDimitry Andric   // dominator tree, even if X is an operand to Y.  For instance, in
6977d523365SDimitry Andric   //
6987d523365SDimitry Andric   //     %iv = phi i32 {0,+,1}
6997d523365SDimitry Andric   //     br %cond, label %left, label %merge
7007d523365SDimitry Andric   //
7017d523365SDimitry Andric   //   left:
7027d523365SDimitry Andric   //     %X = add i32 %iv, 0
7037d523365SDimitry Andric   //     br label %merge
7047d523365SDimitry Andric   //
7057d523365SDimitry Andric   //   merge:
7067d523365SDimitry Andric   //     %M = phi (%X, %iv)
7077d523365SDimitry Andric   //
7087d523365SDimitry Andric   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
7097d523365SDimitry Andric   // %M.replaceAllUsesWith(%X) would be incorrect.
7107d523365SDimitry Andric 
7117d523365SDimitry Andric   if (isa<PHINode>(UseInst))
7127d523365SDimitry Andric     // If UseInst is not a PHI node then we know that IVOperand dominates
7137d523365SDimitry Andric     // UseInst directly from the legality of SSA.
7147d523365SDimitry Andric     if (!DT || !DT->dominates(IVOperand, UseInst))
7157d523365SDimitry Andric       return false;
7167d523365SDimitry Andric 
7177d523365SDimitry Andric   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
7187d523365SDimitry Andric     return false;
7197d523365SDimitry Andric 
7204ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
7216122f3e6SDimitry Andric 
7226122f3e6SDimitry Andric   UseInst->replaceAllUsesWith(IVOperand);
7236122f3e6SDimitry Andric   ++NumElimIdentity;
7246122f3e6SDimitry Andric   Changed = true;
72597bc6c73SDimitry Andric   DeadInsts.emplace_back(UseInst);
7266122f3e6SDimitry Andric   return true;
7276122f3e6SDimitry Andric }
7286122f3e6SDimitry Andric 
72939d628a0SDimitry Andric /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
73039d628a0SDimitry Andric /// unsigned-overflow.  Returns true if anything changed, false otherwise.
strengthenOverflowingOperation(BinaryOperator * BO,Value * IVOperand)73139d628a0SDimitry Andric bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
73239d628a0SDimitry Andric                                                     Value *IVOperand) {
73339d628a0SDimitry Andric 
734ff0cc061SDimitry Andric   // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
73539d628a0SDimitry Andric   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
73639d628a0SDimitry Andric     return false;
73739d628a0SDimitry Andric 
738ff0cc061SDimitry Andric   const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
73924d58133SDimitry Andric                                                SCEV::NoWrapFlags, unsigned);
740ff0cc061SDimitry Andric   switch (BO->getOpcode()) {
741ff0cc061SDimitry Andric   default:
74239d628a0SDimitry Andric     return false;
74339d628a0SDimitry Andric 
744ff0cc061SDimitry Andric   case Instruction::Add:
745ff0cc061SDimitry Andric     GetExprForBO = &ScalarEvolution::getAddExpr;
746ff0cc061SDimitry Andric     break;
74739d628a0SDimitry Andric 
748ff0cc061SDimitry Andric   case Instruction::Sub:
749ff0cc061SDimitry Andric     GetExprForBO = &ScalarEvolution::getMinusSCEV;
750ff0cc061SDimitry Andric     break;
75139d628a0SDimitry Andric 
752ff0cc061SDimitry Andric   case Instruction::Mul:
753ff0cc061SDimitry Andric     GetExprForBO = &ScalarEvolution::getMulExpr;
754ff0cc061SDimitry Andric     break;
755ff0cc061SDimitry Andric   }
75639d628a0SDimitry Andric 
757ff0cc061SDimitry Andric   unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
758ff0cc061SDimitry Andric   Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
759ff0cc061SDimitry Andric   const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
760ff0cc061SDimitry Andric   const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
76139d628a0SDimitry Andric 
762ff0cc061SDimitry Andric   bool Changed = false;
76339d628a0SDimitry Andric 
764ff0cc061SDimitry Andric   if (!BO->hasNoUnsignedWrap()) {
765ff0cc061SDimitry Andric     const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
766ff0cc061SDimitry Andric     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
767ff0cc061SDimitry Andric       SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
76824d58133SDimitry Andric       SCEV::FlagAnyWrap, 0u);
769ff0cc061SDimitry Andric     if (ExtendAfterOp == OpAfterExtend) {
770ff0cc061SDimitry Andric       BO->setHasNoUnsignedWrap();
771ff0cc061SDimitry Andric       SE->forgetValue(BO);
77239d628a0SDimitry Andric       Changed = true;
77339d628a0SDimitry Andric     }
77439d628a0SDimitry Andric   }
77539d628a0SDimitry Andric 
776ff0cc061SDimitry Andric   if (!BO->hasNoSignedWrap()) {
777ff0cc061SDimitry Andric     const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
778ff0cc061SDimitry Andric     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
779ff0cc061SDimitry Andric       SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
78024d58133SDimitry Andric       SCEV::FlagAnyWrap, 0u);
781ff0cc061SDimitry Andric     if (ExtendAfterOp == OpAfterExtend) {
782ff0cc061SDimitry Andric       BO->setHasNoSignedWrap();
783ff0cc061SDimitry Andric       SE->forgetValue(BO);
78439d628a0SDimitry Andric       Changed = true;
78539d628a0SDimitry Andric     }
78639d628a0SDimitry Andric   }
78739d628a0SDimitry Andric 
78839d628a0SDimitry Andric   return Changed;
78939d628a0SDimitry Andric }
79039d628a0SDimitry Andric 
791c4394386SDimitry Andric /// Annotate the Shr in (X << IVOperand) >> C as exact using the
792c4394386SDimitry Andric /// information from the IV's range. Returns true if anything changed, false
793c4394386SDimitry Andric /// otherwise.
strengthenRightShift(BinaryOperator * BO,Value * IVOperand)794c4394386SDimitry Andric bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
795c4394386SDimitry Andric                                           Value *IVOperand) {
796c4394386SDimitry Andric   using namespace llvm::PatternMatch;
797c4394386SDimitry Andric 
798c4394386SDimitry Andric   if (BO->getOpcode() == Instruction::Shl) {
799c4394386SDimitry Andric     bool Changed = false;
800c4394386SDimitry Andric     ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
801c4394386SDimitry Andric     for (auto *U : BO->users()) {
802c4394386SDimitry Andric       const APInt *C;
803c4394386SDimitry Andric       if (match(U,
804c4394386SDimitry Andric                 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
805c4394386SDimitry Andric           match(U,
806c4394386SDimitry Andric                 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
807c4394386SDimitry Andric         BinaryOperator *Shr = cast<BinaryOperator>(U);
808c4394386SDimitry Andric         if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
809c4394386SDimitry Andric           Shr->setIsExact(true);
810c4394386SDimitry Andric           Changed = true;
811c4394386SDimitry Andric         }
812c4394386SDimitry Andric       }
813c4394386SDimitry Andric     }
814c4394386SDimitry Andric     return Changed;
815c4394386SDimitry Andric   }
816c4394386SDimitry Andric 
817c4394386SDimitry Andric   return false;
818c4394386SDimitry Andric }
819c4394386SDimitry Andric 
82039d628a0SDimitry Andric /// Add all uses of Def to the current IV's worklist.
pushIVUsers(Instruction * Def,Loop * L,SmallPtrSet<Instruction *,16> & Simplified,SmallVectorImpl<std::pair<Instruction *,Instruction * >> & SimpleIVUsers)8216122f3e6SDimitry Andric static void pushIVUsers(
8222cab237bSDimitry Andric   Instruction *Def, Loop *L,
8236122f3e6SDimitry Andric   SmallPtrSet<Instruction*,16> &Simplified,
8246122f3e6SDimitry Andric   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
8256122f3e6SDimitry Andric 
82691bc56edSDimitry Andric   for (User *U : Def->users()) {
82791bc56edSDimitry Andric     Instruction *UI = cast<Instruction>(U);
8286122f3e6SDimitry Andric 
8296122f3e6SDimitry Andric     // Avoid infinite or exponential worklist processing.
8306122f3e6SDimitry Andric     // Also ensure unique worklist users.
8316122f3e6SDimitry Andric     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
8326122f3e6SDimitry Andric     // self edges first.
8332cab237bSDimitry Andric     if (UI == Def)
8342cab237bSDimitry Andric       continue;
8352cab237bSDimitry Andric 
8362cab237bSDimitry Andric     // Only change the current Loop, do not change the other parts (e.g. other
8372cab237bSDimitry Andric     // Loops).
8382cab237bSDimitry Andric     if (!L->contains(UI))
8392cab237bSDimitry Andric       continue;
8402cab237bSDimitry Andric 
8412cab237bSDimitry Andric     // Do not push the same instruction more than once.
8422cab237bSDimitry Andric     if (!Simplified.insert(UI).second)
8432cab237bSDimitry Andric       continue;
8442cab237bSDimitry Andric 
84591bc56edSDimitry Andric     SimpleIVUsers.push_back(std::make_pair(UI, Def));
8466122f3e6SDimitry Andric   }
8476122f3e6SDimitry Andric }
8486122f3e6SDimitry Andric 
84939d628a0SDimitry Andric /// Return true if this instruction generates a simple SCEV
8506122f3e6SDimitry Andric /// expression in terms of that IV.
8516122f3e6SDimitry Andric ///
8526122f3e6SDimitry Andric /// This is similar to IVUsers' isInteresting() but processes each instruction
8536122f3e6SDimitry Andric /// non-recursively when the operand is already known to be a simpleIVUser.
8546122f3e6SDimitry Andric ///
isSimpleIVUser(Instruction * I,const Loop * L,ScalarEvolution * SE)8556122f3e6SDimitry Andric static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
8566122f3e6SDimitry Andric   if (!SE->isSCEVable(I->getType()))
8576122f3e6SDimitry Andric     return false;
8586122f3e6SDimitry Andric 
8596122f3e6SDimitry Andric   // Get the symbolic expression for this instruction.
8606122f3e6SDimitry Andric   const SCEV *S = SE->getSCEV(I);
8616122f3e6SDimitry Andric 
8626122f3e6SDimitry Andric   // Only consider affine recurrences.
8636122f3e6SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
8646122f3e6SDimitry Andric   if (AR && AR->getLoop() == L)
8656122f3e6SDimitry Andric     return true;
8666122f3e6SDimitry Andric 
8676122f3e6SDimitry Andric   return false;
8686122f3e6SDimitry Andric }
8696122f3e6SDimitry Andric 
87039d628a0SDimitry Andric /// Iteratively perform simplification on a worklist of users
8716122f3e6SDimitry Andric /// of the specified induction variable. Each successive simplification may push
8726122f3e6SDimitry Andric /// more users which may themselves be candidates for simplification.
8736122f3e6SDimitry Andric ///
8746122f3e6SDimitry Andric /// This algorithm does not require IVUsers analysis. Instead, it simplifies
8756122f3e6SDimitry Andric /// instructions in-place during analysis. Rather than rewriting induction
8766122f3e6SDimitry Andric /// variables bottom-up from their users, it transforms a chain of IVUsers
8777d523365SDimitry Andric /// top-down, updating the IR only when it encounters a clear optimization
8787d523365SDimitry Andric /// opportunity.
8796122f3e6SDimitry Andric ///
8806122f3e6SDimitry Andric /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
8816122f3e6SDimitry Andric ///
simplifyUsers(PHINode * CurrIV,IVVisitor * V)8826122f3e6SDimitry Andric void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
8836122f3e6SDimitry Andric   if (!SE->isSCEVable(CurrIV->getType()))
8846122f3e6SDimitry Andric     return;
8856122f3e6SDimitry Andric 
8866122f3e6SDimitry Andric   // Instructions processed by SimplifyIndvar for CurrIV.
8876122f3e6SDimitry Andric   SmallPtrSet<Instruction*,16> Simplified;
8886122f3e6SDimitry Andric 
8896122f3e6SDimitry Andric   // Use-def pairs if IV users waiting to be processed for CurrIV.
8906122f3e6SDimitry Andric   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
8916122f3e6SDimitry Andric 
8926122f3e6SDimitry Andric   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
8936122f3e6SDimitry Andric   // called multiple times for the same LoopPhi. This is the proper thing to
8946122f3e6SDimitry Andric   // do for loop header phis that use each other.
8952cab237bSDimitry Andric   pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
8966122f3e6SDimitry Andric 
8976122f3e6SDimitry Andric   while (!SimpleIVUsers.empty()) {
8986122f3e6SDimitry Andric     std::pair<Instruction*, Instruction*> UseOper =
8996122f3e6SDimitry Andric       SimpleIVUsers.pop_back_val();
90091bc56edSDimitry Andric     Instruction *UseInst = UseOper.first;
90191bc56edSDimitry Andric 
9024ba319b5SDimitry Andric     // If a user of the IndVar is trivially dead, we prefer just to mark it dead
9034ba319b5SDimitry Andric     // rather than try to do some complex analysis or transformation (such as
9044ba319b5SDimitry Andric     // widening) basing on it.
9054ba319b5SDimitry Andric     // TODO: Propagate TLI and pass it here to handle more cases.
9064ba319b5SDimitry Andric     if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
9074ba319b5SDimitry Andric       DeadInsts.emplace_back(UseInst);
9084ba319b5SDimitry Andric       continue;
9094ba319b5SDimitry Andric     }
9104ba319b5SDimitry Andric 
9116122f3e6SDimitry Andric     // Bypass back edges to avoid extra work.
91291bc56edSDimitry Andric     if (UseInst == CurrIV) continue;
91391bc56edSDimitry Andric 
9142cab237bSDimitry Andric     // Try to replace UseInst with a loop invariant before any other
9152cab237bSDimitry Andric     // simplifications.
9162cab237bSDimitry Andric     if (replaceIVUserWithLoopInvariant(UseInst))
9172cab237bSDimitry Andric       continue;
9182cab237bSDimitry Andric 
9196122f3e6SDimitry Andric     Instruction *IVOperand = UseOper.second;
9206122f3e6SDimitry Andric     for (unsigned N = 0; IVOperand; ++N) {
9216122f3e6SDimitry Andric       assert(N <= Simplified.size() && "runaway iteration");
9226122f3e6SDimitry Andric 
9234ba319b5SDimitry Andric       Value *NewOper = foldIVUser(UseInst, IVOperand);
9246122f3e6SDimitry Andric       if (!NewOper)
9256122f3e6SDimitry Andric         break; // done folding
9266122f3e6SDimitry Andric       IVOperand = dyn_cast<Instruction>(NewOper);
9276122f3e6SDimitry Andric     }
9286122f3e6SDimitry Andric     if (!IVOperand)
9296122f3e6SDimitry Andric       continue;
9306122f3e6SDimitry Andric 
9314ba319b5SDimitry Andric     if (eliminateIVUser(UseInst, IVOperand)) {
9322cab237bSDimitry Andric       pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
9336122f3e6SDimitry Andric       continue;
9346122f3e6SDimitry Andric     }
93539d628a0SDimitry Andric 
9364ba319b5SDimitry Andric     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
937c4394386SDimitry Andric       if ((isa<OverflowingBinaryOperator>(BO) &&
938c4394386SDimitry Andric            strengthenOverflowingOperation(BO, IVOperand)) ||
939c4394386SDimitry Andric           (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
94039d628a0SDimitry Andric         // re-queue uses of the now modified binary operator and fall
94139d628a0SDimitry Andric         // through to the checks that remain.
9422cab237bSDimitry Andric         pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
94339d628a0SDimitry Andric       }
94439d628a0SDimitry Andric     }
94539d628a0SDimitry Andric 
9464ba319b5SDimitry Andric     CastInst *Cast = dyn_cast<CastInst>(UseInst);
9476122f3e6SDimitry Andric     if (V && Cast) {
9486122f3e6SDimitry Andric       V->visitCast(Cast);
9496122f3e6SDimitry Andric       continue;
9506122f3e6SDimitry Andric     }
9514ba319b5SDimitry Andric     if (isSimpleIVUser(UseInst, L, SE)) {
9524ba319b5SDimitry Andric       pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
9536122f3e6SDimitry Andric     }
9546122f3e6SDimitry Andric   }
9556122f3e6SDimitry Andric }
9566122f3e6SDimitry Andric 
9576122f3e6SDimitry Andric namespace llvm {
9586122f3e6SDimitry Andric 
anchor()959dff0c46cSDimitry Andric void IVVisitor::anchor() { }
960dff0c46cSDimitry Andric 
96139d628a0SDimitry Andric /// Simplify instructions that use this induction variable
9626122f3e6SDimitry Andric /// by using ScalarEvolution to analyze the IV's recurrence.
simplifyUsersOfIV(PHINode * CurrIV,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,SmallVectorImpl<WeakTrackingVH> & Dead,SCEVExpander & Rewriter,IVVisitor * V)9637d523365SDimitry Andric bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
964f37b6182SDimitry Andric                        LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
9652cab237bSDimitry Andric                        SCEVExpander &Rewriter, IVVisitor *V) {
9662cab237bSDimitry Andric   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
9672cab237bSDimitry Andric                      Dead);
9686122f3e6SDimitry Andric   SIV.simplifyUsers(CurrIV, V);
9696122f3e6SDimitry Andric   return SIV.hasChanged();
9706122f3e6SDimitry Andric }
9716122f3e6SDimitry Andric 
97239d628a0SDimitry Andric /// Simplify users of induction variables within this
9736122f3e6SDimitry Andric /// loop. This does not actually change or add IVs.
simplifyLoopIVs(Loop * L,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,SmallVectorImpl<WeakTrackingVH> & Dead)9747d523365SDimitry Andric bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
975f37b6182SDimitry Andric                      LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
9762cab237bSDimitry Andric   SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
9772cab237bSDimitry Andric #ifndef NDEBUG
9782cab237bSDimitry Andric   Rewriter.setDebugType(DEBUG_TYPE);
9792cab237bSDimitry Andric #endif
9806122f3e6SDimitry Andric   bool Changed = false;
9816122f3e6SDimitry Andric   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
9822cab237bSDimitry Andric     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
9836122f3e6SDimitry Andric   }
9846122f3e6SDimitry Andric   return Changed;
9856122f3e6SDimitry Andric }
9866122f3e6SDimitry Andric 
9876122f3e6SDimitry Andric } // namespace llvm
988