LLVM API Documentation

ScalarEvolution.cpp
Go to the documentation of this file.
00001 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
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 contains the implementation of the scalar evolution analysis
00011 // engine, which is used primarily to analyze expressions involving induction
00012 // variables in loops.
00013 //
00014 // There are several aspects to this library.  First is the representation of
00015 // scalar expressions, which are represented as subclasses of the SCEV class.
00016 // These classes are used to represent certain types of subexpressions that we
00017 // can handle. We only create one SCEV of a particular shape, so
00018 // pointer-comparisons for equality are legal.
00019 //
00020 // One important aspect of the SCEV objects is that they are never cyclic, even
00021 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
00022 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
00023 // recurrence) then we represent it directly as a recurrence node, otherwise we
00024 // represent it as a SCEVUnknown node.
00025 //
00026 // In addition to being able to represent expressions of various types, we also
00027 // have folders that are used to build the *canonical* representation for a
00028 // particular expression.  These folders are capable of using a variety of
00029 // rewrite rules to simplify the expressions.
00030 //
00031 // Once the folders are defined, we can implement the more interesting
00032 // higher-level code, such as the code that recognizes PHI nodes of various
00033 // types, computes the execution count of a loop, etc.
00034 //
00035 // TODO: We should use these routines and value representations to implement
00036 // dependence analysis!
00037 //
00038 //===----------------------------------------------------------------------===//
00039 //
00040 // There are several good references for the techniques used in this analysis.
00041 //
00042 //  Chains of recurrences -- a method to expedite the evaluation
00043 //  of closed-form functions
00044 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
00045 //
00046 //  On computational properties of chains of recurrences
00047 //  Eugene V. Zima
00048 //
00049 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
00050 //  Robert A. van Engelen
00051 //
00052 //  Efficient Symbolic Analysis for Optimizing Compilers
00053 //  Robert A. van Engelen
00054 //
00055 //  Using the chains of recurrences algebra for data dependence testing and
00056 //  induction variable substitution
00057 //  MS Thesis, Johnie Birch
00058 //
00059 //===----------------------------------------------------------------------===//
00060 
00061 #include "llvm/Analysis/ScalarEvolution.h"
00062 #include "llvm/ADT/STLExtras.h"
00063 #include "llvm/ADT/SmallPtrSet.h"
00064 #include "llvm/ADT/Statistic.h"
00065 #include "llvm/Analysis/ConstantFolding.h"
00066 #include "llvm/Analysis/InstructionSimplify.h"
00067 #include "llvm/Analysis/LoopInfo.h"
00068 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00069 #include "llvm/Analysis/ValueTracking.h"
00070 #include "llvm/IR/ConstantRange.h"
00071 #include "llvm/IR/Constants.h"
00072 #include "llvm/IR/DataLayout.h"
00073 #include "llvm/IR/DerivedTypes.h"
00074 #include "llvm/IR/Dominators.h"
00075 #include "llvm/IR/GetElementPtrTypeIterator.h"
00076 #include "llvm/IR/GlobalAlias.h"
00077 #include "llvm/IR/GlobalVariable.h"
00078 #include "llvm/IR/InstIterator.h"
00079 #include "llvm/IR/Instructions.h"
00080 #include "llvm/IR/LLVMContext.h"
00081 #include "llvm/IR/Operator.h"
00082 #include "llvm/Support/CommandLine.h"
00083 #include "llvm/Support/Debug.h"
00084 #include "llvm/Support/ErrorHandling.h"
00085 #include "llvm/Support/MathExtras.h"
00086 #include "llvm/Support/raw_ostream.h"
00087 #include "llvm/Target/TargetLibraryInfo.h"
00088 #include <algorithm>
00089 using namespace llvm;
00090 
00091 #define DEBUG_TYPE "scalar-evolution"
00092 
00093 STATISTIC(NumArrayLenItCounts,
00094           "Number of trip counts computed with array length");
00095 STATISTIC(NumTripCountsComputed,
00096           "Number of loops with predictable loop counts");
00097 STATISTIC(NumTripCountsNotComputed,
00098           "Number of loops without predictable loop counts");
00099 STATISTIC(NumBruteForceTripCountsComputed,
00100           "Number of loops with trip counts computed by force");
00101 
00102 static cl::opt<unsigned>
00103 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
00104                         cl::desc("Maximum number of iterations SCEV will "
00105                                  "symbolically execute a constant "
00106                                  "derived loop"),
00107                         cl::init(100));
00108 
00109 // FIXME: Enable this with XDEBUG when the test suite is clean.
00110 static cl::opt<bool>
00111 VerifySCEV("verify-scev",
00112            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
00113 
00114 INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
00115                 "Scalar Evolution Analysis", false, true)
00116 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00117 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00118 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00119 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
00120                 "Scalar Evolution Analysis", false, true)
00121 char ScalarEvolution::ID = 0;
00122 
00123 //===----------------------------------------------------------------------===//
00124 //                           SCEV class definitions
00125 //===----------------------------------------------------------------------===//
00126 
00127 //===----------------------------------------------------------------------===//
00128 // Implementation of the SCEV class.
00129 //
00130 
00131 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00132 void SCEV::dump() const {
00133   print(dbgs());
00134   dbgs() << '\n';
00135 }
00136 #endif
00137 
00138 void SCEV::print(raw_ostream &OS) const {
00139   switch (static_cast<SCEVTypes>(getSCEVType())) {
00140   case scConstant:
00141     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
00142     return;
00143   case scTruncate: {
00144     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
00145     const SCEV *Op = Trunc->getOperand();
00146     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
00147        << *Trunc->getType() << ")";
00148     return;
00149   }
00150   case scZeroExtend: {
00151     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
00152     const SCEV *Op = ZExt->getOperand();
00153     OS << "(zext " << *Op->getType() << " " << *Op << " to "
00154        << *ZExt->getType() << ")";
00155     return;
00156   }
00157   case scSignExtend: {
00158     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
00159     const SCEV *Op = SExt->getOperand();
00160     OS << "(sext " << *Op->getType() << " " << *Op << " to "
00161        << *SExt->getType() << ")";
00162     return;
00163   }
00164   case scAddRecExpr: {
00165     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
00166     OS << "{" << *AR->getOperand(0);
00167     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
00168       OS << ",+," << *AR->getOperand(i);
00169     OS << "}<";
00170     if (AR->getNoWrapFlags(FlagNUW))
00171       OS << "nuw><";
00172     if (AR->getNoWrapFlags(FlagNSW))
00173       OS << "nsw><";
00174     if (AR->getNoWrapFlags(FlagNW) &&
00175         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
00176       OS << "nw><";
00177     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
00178     OS << ">";
00179     return;
00180   }
00181   case scAddExpr:
00182   case scMulExpr:
00183   case scUMaxExpr:
00184   case scSMaxExpr: {
00185     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
00186     const char *OpStr = nullptr;
00187     switch (NAry->getSCEVType()) {
00188     case scAddExpr: OpStr = " + "; break;
00189     case scMulExpr: OpStr = " * "; break;
00190     case scUMaxExpr: OpStr = " umax "; break;
00191     case scSMaxExpr: OpStr = " smax "; break;
00192     }
00193     OS << "(";
00194     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
00195          I != E; ++I) {
00196       OS << **I;
00197       if (std::next(I) != E)
00198         OS << OpStr;
00199     }
00200     OS << ")";
00201     switch (NAry->getSCEVType()) {
00202     case scAddExpr:
00203     case scMulExpr:
00204       if (NAry->getNoWrapFlags(FlagNUW))
00205         OS << "<nuw>";
00206       if (NAry->getNoWrapFlags(FlagNSW))
00207         OS << "<nsw>";
00208     }
00209     return;
00210   }
00211   case scUDivExpr: {
00212     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
00213     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
00214     return;
00215   }
00216   case scUnknown: {
00217     const SCEVUnknown *U = cast<SCEVUnknown>(this);
00218     Type *AllocTy;
00219     if (U->isSizeOf(AllocTy)) {
00220       OS << "sizeof(" << *AllocTy << ")";
00221       return;
00222     }
00223     if (U->isAlignOf(AllocTy)) {
00224       OS << "alignof(" << *AllocTy << ")";
00225       return;
00226     }
00227 
00228     Type *CTy;
00229     Constant *FieldNo;
00230     if (U->isOffsetOf(CTy, FieldNo)) {
00231       OS << "offsetof(" << *CTy << ", ";
00232       FieldNo->printAsOperand(OS, false);
00233       OS << ")";
00234       return;
00235     }
00236 
00237     // Otherwise just print it normally.
00238     U->getValue()->printAsOperand(OS, false);
00239     return;
00240   }
00241   case scCouldNotCompute:
00242     OS << "***COULDNOTCOMPUTE***";
00243     return;
00244   }
00245   llvm_unreachable("Unknown SCEV kind!");
00246 }
00247 
00248 Type *SCEV::getType() const {
00249   switch (static_cast<SCEVTypes>(getSCEVType())) {
00250   case scConstant:
00251     return cast<SCEVConstant>(this)->getType();
00252   case scTruncate:
00253   case scZeroExtend:
00254   case scSignExtend:
00255     return cast<SCEVCastExpr>(this)->getType();
00256   case scAddRecExpr:
00257   case scMulExpr:
00258   case scUMaxExpr:
00259   case scSMaxExpr:
00260     return cast<SCEVNAryExpr>(this)->getType();
00261   case scAddExpr:
00262     return cast<SCEVAddExpr>(this)->getType();
00263   case scUDivExpr:
00264     return cast<SCEVUDivExpr>(this)->getType();
00265   case scUnknown:
00266     return cast<SCEVUnknown>(this)->getType();
00267   case scCouldNotCompute:
00268     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
00269   }
00270   llvm_unreachable("Unknown SCEV kind!");
00271 }
00272 
00273 bool SCEV::isZero() const {
00274   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00275     return SC->getValue()->isZero();
00276   return false;
00277 }
00278 
00279 bool SCEV::isOne() const {
00280   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00281     return SC->getValue()->isOne();
00282   return false;
00283 }
00284 
00285 bool SCEV::isAllOnesValue() const {
00286   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
00287     return SC->getValue()->isAllOnesValue();
00288   return false;
00289 }
00290 
00291 /// isNonConstantNegative - Return true if the specified scev is negated, but
00292 /// not a constant.
00293 bool SCEV::isNonConstantNegative() const {
00294   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
00295   if (!Mul) return false;
00296 
00297   // If there is a constant factor, it will be first.
00298   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
00299   if (!SC) return false;
00300 
00301   // Return true if the value is negative, this matches things like (-42 * V).
00302   return SC->getValue()->getValue().isNegative();
00303 }
00304 
00305 SCEVCouldNotCompute::SCEVCouldNotCompute() :
00306   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
00307 
00308 bool SCEVCouldNotCompute::classof(const SCEV *S) {
00309   return S->getSCEVType() == scCouldNotCompute;
00310 }
00311 
00312 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
00313   FoldingSetNodeID ID;
00314   ID.AddInteger(scConstant);
00315   ID.AddPointer(V);
00316   void *IP = nullptr;
00317   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
00318   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
00319   UniqueSCEVs.InsertNode(S, IP);
00320   return S;
00321 }
00322 
00323 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
00324   return getConstant(ConstantInt::get(getContext(), Val));
00325 }
00326 
00327 const SCEV *
00328 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
00329   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
00330   return getConstant(ConstantInt::get(ITy, V, isSigned));
00331 }
00332 
00333 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
00334                            unsigned SCEVTy, const SCEV *op, Type *ty)
00335   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
00336 
00337 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
00338                                    const SCEV *op, Type *ty)
00339   : SCEVCastExpr(ID, scTruncate, op, ty) {
00340   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
00341          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
00342          "Cannot truncate non-integer value!");
00343 }
00344 
00345 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
00346                                        const SCEV *op, Type *ty)
00347   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
00348   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
00349          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
00350          "Cannot zero extend non-integer value!");
00351 }
00352 
00353 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
00354                                        const SCEV *op, Type *ty)
00355   : SCEVCastExpr(ID, scSignExtend, op, ty) {
00356   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
00357          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
00358          "Cannot sign extend non-integer value!");
00359 }
00360 
00361 void SCEVUnknown::deleted() {
00362   // Clear this SCEVUnknown from various maps.
00363   SE->forgetMemoizedResults(this);
00364 
00365   // Remove this SCEVUnknown from the uniquing map.
00366   SE->UniqueSCEVs.RemoveNode(this);
00367 
00368   // Release the value.
00369   setValPtr(nullptr);
00370 }
00371 
00372 void SCEVUnknown::allUsesReplacedWith(Value *New) {
00373   // Clear this SCEVUnknown from various maps.
00374   SE->forgetMemoizedResults(this);
00375 
00376   // Remove this SCEVUnknown from the uniquing map.
00377   SE->UniqueSCEVs.RemoveNode(this);
00378 
00379   // Update this SCEVUnknown to point to the new value. This is needed
00380   // because there may still be outstanding SCEVs which still point to
00381   // this SCEVUnknown.
00382   setValPtr(New);
00383 }
00384 
00385 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
00386   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
00387     if (VCE->getOpcode() == Instruction::PtrToInt)
00388       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
00389         if (CE->getOpcode() == Instruction::GetElementPtr &&
00390             CE->getOperand(0)->isNullValue() &&
00391             CE->getNumOperands() == 2)
00392           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
00393             if (CI->isOne()) {
00394               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
00395                                  ->getElementType();
00396               return true;
00397             }
00398 
00399   return false;
00400 }
00401 
00402 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
00403   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
00404     if (VCE->getOpcode() == Instruction::PtrToInt)
00405       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
00406         if (CE->getOpcode() == Instruction::GetElementPtr &&
00407             CE->getOperand(0)->isNullValue()) {
00408           Type *Ty =
00409             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
00410           if (StructType *STy = dyn_cast<StructType>(Ty))
00411             if (!STy->isPacked() &&
00412                 CE->getNumOperands() == 3 &&
00413                 CE->getOperand(1)->isNullValue()) {
00414               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
00415                 if (CI->isOne() &&
00416                     STy->getNumElements() == 2 &&
00417                     STy->getElementType(0)->isIntegerTy(1)) {
00418                   AllocTy = STy->getElementType(1);
00419                   return true;
00420                 }
00421             }
00422         }
00423 
00424   return false;
00425 }
00426 
00427 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
00428   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
00429     if (VCE->getOpcode() == Instruction::PtrToInt)
00430       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
00431         if (CE->getOpcode() == Instruction::GetElementPtr &&
00432             CE->getNumOperands() == 3 &&
00433             CE->getOperand(0)->isNullValue() &&
00434             CE->getOperand(1)->isNullValue()) {
00435           Type *Ty =
00436             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
00437           // Ignore vector types here so that ScalarEvolutionExpander doesn't
00438           // emit getelementptrs that index into vectors.
00439           if (Ty->isStructTy() || Ty->isArrayTy()) {
00440             CTy = Ty;
00441             FieldNo = CE->getOperand(2);
00442             return true;
00443           }
00444         }
00445 
00446   return false;
00447 }
00448 
00449 //===----------------------------------------------------------------------===//
00450 //                               SCEV Utilities
00451 //===----------------------------------------------------------------------===//
00452 
00453 namespace {
00454   /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
00455   /// than the complexity of the RHS.  This comparator is used to canonicalize
00456   /// expressions.
00457   class SCEVComplexityCompare {
00458     const LoopInfo *const LI;
00459   public:
00460     explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
00461 
00462     // Return true or false if LHS is less than, or at least RHS, respectively.
00463     bool operator()(const SCEV *LHS, const SCEV *RHS) const {
00464       return compare(LHS, RHS) < 0;
00465     }
00466 
00467     // Return negative, zero, or positive, if LHS is less than, equal to, or
00468     // greater than RHS, respectively. A three-way result allows recursive
00469     // comparisons to be more efficient.
00470     int compare(const SCEV *LHS, const SCEV *RHS) const {
00471       // Fast-path: SCEVs are uniqued so we can do a quick equality check.
00472       if (LHS == RHS)
00473         return 0;
00474 
00475       // Primarily, sort the SCEVs by their getSCEVType().
00476       unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
00477       if (LType != RType)
00478         return (int)LType - (int)RType;
00479 
00480       // Aside from the getSCEVType() ordering, the particular ordering
00481       // isn't very important except that it's beneficial to be consistent,
00482       // so that (a + b) and (b + a) don't end up as different expressions.
00483       switch (static_cast<SCEVTypes>(LType)) {
00484       case scUnknown: {
00485         const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
00486         const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
00487 
00488         // Sort SCEVUnknown values with some loose heuristics. TODO: This is
00489         // not as complete as it could be.
00490         const Value *LV = LU->getValue(), *RV = RU->getValue();
00491 
00492         // Order pointer values after integer values. This helps SCEVExpander
00493         // form GEPs.
00494         bool LIsPointer = LV->getType()->isPointerTy(),
00495              RIsPointer = RV->getType()->isPointerTy();
00496         if (LIsPointer != RIsPointer)
00497           return (int)LIsPointer - (int)RIsPointer;
00498 
00499         // Compare getValueID values.
00500         unsigned LID = LV->getValueID(),
00501                  RID = RV->getValueID();
00502         if (LID != RID)
00503           return (int)LID - (int)RID;
00504 
00505         // Sort arguments by their position.
00506         if (const Argument *LA = dyn_cast<Argument>(LV)) {
00507           const Argument *RA = cast<Argument>(RV);
00508           unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
00509           return (int)LArgNo - (int)RArgNo;
00510         }
00511 
00512         // For instructions, compare their loop depth, and their operand
00513         // count.  This is pretty loose.
00514         if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
00515           const Instruction *RInst = cast<Instruction>(RV);
00516 
00517           // Compare loop depths.
00518           const BasicBlock *LParent = LInst->getParent(),
00519                            *RParent = RInst->getParent();
00520           if (LParent != RParent) {
00521             unsigned LDepth = LI->getLoopDepth(LParent),
00522                      RDepth = LI->getLoopDepth(RParent);
00523             if (LDepth != RDepth)
00524               return (int)LDepth - (int)RDepth;
00525           }
00526 
00527           // Compare the number of operands.
00528           unsigned LNumOps = LInst->getNumOperands(),
00529                    RNumOps = RInst->getNumOperands();
00530           return (int)LNumOps - (int)RNumOps;
00531         }
00532 
00533         return 0;
00534       }
00535 
00536       case scConstant: {
00537         const SCEVConstant *LC = cast<SCEVConstant>(LHS);
00538         const SCEVConstant *RC = cast<SCEVConstant>(RHS);
00539 
00540         // Compare constant values.
00541         const APInt &LA = LC->getValue()->getValue();
00542         const APInt &RA = RC->getValue()->getValue();
00543         unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
00544         if (LBitWidth != RBitWidth)
00545           return (int)LBitWidth - (int)RBitWidth;
00546         return LA.ult(RA) ? -1 : 1;
00547       }
00548 
00549       case scAddRecExpr: {
00550         const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
00551         const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
00552 
00553         // Compare addrec loop depths.
00554         const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
00555         if (LLoop != RLoop) {
00556           unsigned LDepth = LLoop->getLoopDepth(),
00557                    RDepth = RLoop->getLoopDepth();
00558           if (LDepth != RDepth)
00559             return (int)LDepth - (int)RDepth;
00560         }
00561 
00562         // Addrec complexity grows with operand count.
00563         unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
00564         if (LNumOps != RNumOps)
00565           return (int)LNumOps - (int)RNumOps;
00566 
00567         // Lexicographically compare.
00568         for (unsigned i = 0; i != LNumOps; ++i) {
00569           long X = compare(LA->getOperand(i), RA->getOperand(i));
00570           if (X != 0)
00571             return X;
00572         }
00573 
00574         return 0;
00575       }
00576 
00577       case scAddExpr:
00578       case scMulExpr:
00579       case scSMaxExpr:
00580       case scUMaxExpr: {
00581         const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
00582         const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
00583 
00584         // Lexicographically compare n-ary expressions.
00585         unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
00586         if (LNumOps != RNumOps)
00587           return (int)LNumOps - (int)RNumOps;
00588 
00589         for (unsigned i = 0; i != LNumOps; ++i) {
00590           if (i >= RNumOps)
00591             return 1;
00592           long X = compare(LC->getOperand(i), RC->getOperand(i));
00593           if (X != 0)
00594             return X;
00595         }
00596         return (int)LNumOps - (int)RNumOps;
00597       }
00598 
00599       case scUDivExpr: {
00600         const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
00601         const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
00602 
00603         // Lexicographically compare udiv expressions.
00604         long X = compare(LC->getLHS(), RC->getLHS());
00605         if (X != 0)
00606           return X;
00607         return compare(LC->getRHS(), RC->getRHS());
00608       }
00609 
00610       case scTruncate:
00611       case scZeroExtend:
00612       case scSignExtend: {
00613         const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
00614         const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
00615 
00616         // Compare cast expressions by operand.
00617         return compare(LC->getOperand(), RC->getOperand());
00618       }
00619 
00620       case scCouldNotCompute:
00621         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
00622       }
00623       llvm_unreachable("Unknown SCEV kind!");
00624     }
00625   };
00626 }
00627 
00628 /// GroupByComplexity - Given a list of SCEV objects, order them by their
00629 /// complexity, and group objects of the same complexity together by value.
00630 /// When this routine is finished, we know that any duplicates in the vector are
00631 /// consecutive and that complexity is monotonically increasing.
00632 ///
00633 /// Note that we go take special precautions to ensure that we get deterministic
00634 /// results from this routine.  In other words, we don't want the results of
00635 /// this to depend on where the addresses of various SCEV objects happened to
00636 /// land in memory.
00637 ///
00638 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
00639                               LoopInfo *LI) {
00640   if (Ops.size() < 2) return;  // Noop
00641   if (Ops.size() == 2) {
00642     // This is the common case, which also happens to be trivially simple.
00643     // Special case it.
00644     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
00645     if (SCEVComplexityCompare(LI)(RHS, LHS))
00646       std::swap(LHS, RHS);
00647     return;
00648   }
00649 
00650   // Do the rough sort by complexity.
00651   std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
00652 
00653   // Now that we are sorted by complexity, group elements of the same
00654   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
00655   // be extremely short in practice.  Note that we take this approach because we
00656   // do not want to depend on the addresses of the objects we are grouping.
00657   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
00658     const SCEV *S = Ops[i];
00659     unsigned Complexity = S->getSCEVType();
00660 
00661     // If there are any objects of the same complexity and same value as this
00662     // one, group them.
00663     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
00664       if (Ops[j] == S) { // Found a duplicate.
00665         // Move it to immediately after i'th element.
00666         std::swap(Ops[i+1], Ops[j]);
00667         ++i;   // no need to rescan it.
00668         if (i == e-2) return;  // Done!
00669       }
00670     }
00671   }
00672 }
00673 
00674 
00675 
00676 //===----------------------------------------------------------------------===//
00677 //                      Simple SCEV method implementations
00678 //===----------------------------------------------------------------------===//
00679 
00680 /// BinomialCoefficient - Compute BC(It, K).  The result has width W.
00681 /// Assume, K > 0.
00682 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
00683                                        ScalarEvolution &SE,
00684                                        Type *ResultTy) {
00685   // Handle the simplest case efficiently.
00686   if (K == 1)
00687     return SE.getTruncateOrZeroExtend(It, ResultTy);
00688 
00689   // We are using the following formula for BC(It, K):
00690   //
00691   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
00692   //
00693   // Suppose, W is the bitwidth of the return value.  We must be prepared for
00694   // overflow.  Hence, we must assure that the result of our computation is
00695   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
00696   // safe in modular arithmetic.
00697   //
00698   // However, this code doesn't use exactly that formula; the formula it uses
00699   // is something like the following, where T is the number of factors of 2 in
00700   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
00701   // exponentiation:
00702   //
00703   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
00704   //
00705   // This formula is trivially equivalent to the previous formula.  However,
00706   // this formula can be implemented much more efficiently.  The trick is that
00707   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
00708   // arithmetic.  To do exact division in modular arithmetic, all we have
00709   // to do is multiply by the inverse.  Therefore, this step can be done at
00710   // width W.
00711   //
00712   // The next issue is how to safely do the division by 2^T.  The way this
00713   // is done is by doing the multiplication step at a width of at least W + T
00714   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
00715   // when we perform the division by 2^T (which is equivalent to a right shift
00716   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
00717   // truncated out after the division by 2^T.
00718   //
00719   // In comparison to just directly using the first formula, this technique
00720   // is much more efficient; using the first formula requires W * K bits,
00721   // but this formula less than W + K bits. Also, the first formula requires
00722   // a division step, whereas this formula only requires multiplies and shifts.
00723   //
00724   // It doesn't matter whether the subtraction step is done in the calculation
00725   // width or the input iteration count's width; if the subtraction overflows,
00726   // the result must be zero anyway.  We prefer here to do it in the width of
00727   // the induction variable because it helps a lot for certain cases; CodeGen
00728   // isn't smart enough to ignore the overflow, which leads to much less
00729   // efficient code if the width of the subtraction is wider than the native
00730   // register width.
00731   //
00732   // (It's possible to not widen at all by pulling out factors of 2 before
00733   // the multiplication; for example, K=2 can be calculated as
00734   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
00735   // extra arithmetic, so it's not an obvious win, and it gets
00736   // much more complicated for K > 3.)
00737 
00738   // Protection from insane SCEVs; this bound is conservative,
00739   // but it probably doesn't matter.
00740   if (K > 1000)
00741     return SE.getCouldNotCompute();
00742 
00743   unsigned W = SE.getTypeSizeInBits(ResultTy);
00744 
00745   // Calculate K! / 2^T and T; we divide out the factors of two before
00746   // multiplying for calculating K! / 2^T to avoid overflow.
00747   // Other overflow doesn't matter because we only care about the bottom
00748   // W bits of the result.
00749   APInt OddFactorial(W, 1);
00750   unsigned T = 1;
00751   for (unsigned i = 3; i <= K; ++i) {
00752     APInt Mult(W, i);
00753     unsigned TwoFactors = Mult.countTrailingZeros();
00754     T += TwoFactors;
00755     Mult = Mult.lshr(TwoFactors);
00756     OddFactorial *= Mult;
00757   }
00758 
00759   // We need at least W + T bits for the multiplication step
00760   unsigned CalculationBits = W + T;
00761 
00762   // Calculate 2^T, at width T+W.
00763   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
00764 
00765   // Calculate the multiplicative inverse of K! / 2^T;
00766   // this multiplication factor will perform the exact division by
00767   // K! / 2^T.
00768   APInt Mod = APInt::getSignedMinValue(W+1);
00769   APInt MultiplyFactor = OddFactorial.zext(W+1);
00770   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
00771   MultiplyFactor = MultiplyFactor.trunc(W);
00772 
00773   // Calculate the product, at width T+W
00774   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
00775                                                       CalculationBits);
00776   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
00777   for (unsigned i = 1; i != K; ++i) {
00778     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
00779     Dividend = SE.getMulExpr(Dividend,
00780                              SE.getTruncateOrZeroExtend(S, CalculationTy));
00781   }
00782 
00783   // Divide by 2^T
00784   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
00785 
00786   // Truncate the result, and divide by K! / 2^T.
00787 
00788   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
00789                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
00790 }
00791 
00792 /// evaluateAtIteration - Return the value of this chain of recurrences at
00793 /// the specified iteration number.  We can evaluate this recurrence by
00794 /// multiplying each element in the chain by the binomial coefficient
00795 /// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
00796 ///
00797 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
00798 ///
00799 /// where BC(It, k) stands for binomial coefficient.
00800 ///
00801 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
00802                                                 ScalarEvolution &SE) const {
00803   const SCEV *Result = getStart();
00804   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
00805     // The computation is correct in the face of overflow provided that the
00806     // multiplication is performed _after_ the evaluation of the binomial
00807     // coefficient.
00808     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
00809     if (isa<SCEVCouldNotCompute>(Coeff))
00810       return Coeff;
00811 
00812     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
00813   }
00814   return Result;
00815 }
00816 
00817 //===----------------------------------------------------------------------===//
00818 //                    SCEV Expression folder implementations
00819 //===----------------------------------------------------------------------===//
00820 
00821 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
00822                                              Type *Ty) {
00823   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
00824          "This is not a truncating conversion!");
00825   assert(isSCEVable(Ty) &&
00826          "This is not a conversion to a SCEVable type!");
00827   Ty = getEffectiveSCEVType(Ty);
00828 
00829   FoldingSetNodeID ID;
00830   ID.AddInteger(scTruncate);
00831   ID.AddPointer(Op);
00832   ID.AddPointer(Ty);
00833   void *IP = nullptr;
00834   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
00835 
00836   // Fold if the operand is constant.
00837   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00838     return getConstant(
00839       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
00840 
00841   // trunc(trunc(x)) --> trunc(x)
00842   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
00843     return getTruncateExpr(ST->getOperand(), Ty);
00844 
00845   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
00846   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
00847     return getTruncateOrSignExtend(SS->getOperand(), Ty);
00848 
00849   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
00850   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
00851     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
00852 
00853   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
00854   // eliminate all the truncates.
00855   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
00856     SmallVector<const SCEV *, 4> Operands;
00857     bool hasTrunc = false;
00858     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
00859       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
00860       hasTrunc = isa<SCEVTruncateExpr>(S);
00861       Operands.push_back(S);
00862     }
00863     if (!hasTrunc)
00864       return getAddExpr(Operands);
00865     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
00866   }
00867 
00868   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
00869   // eliminate all the truncates.
00870   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
00871     SmallVector<const SCEV *, 4> Operands;
00872     bool hasTrunc = false;
00873     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
00874       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
00875       hasTrunc = isa<SCEVTruncateExpr>(S);
00876       Operands.push_back(S);
00877     }
00878     if (!hasTrunc)
00879       return getMulExpr(Operands);
00880     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
00881   }
00882 
00883   // If the input value is a chrec scev, truncate the chrec's operands.
00884   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
00885     SmallVector<const SCEV *, 4> Operands;
00886     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
00887       Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
00888     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
00889   }
00890 
00891   // The cast wasn't folded; create an explicit cast node. We can reuse
00892   // the existing insert position since if we get here, we won't have
00893   // made any changes which would invalidate it.
00894   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
00895                                                  Op, Ty);
00896   UniqueSCEVs.InsertNode(S, IP);
00897   return S;
00898 }
00899 
00900 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
00901                                                Type *Ty) {
00902   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
00903          "This is not an extending conversion!");
00904   assert(isSCEVable(Ty) &&
00905          "This is not a conversion to a SCEVable type!");
00906   Ty = getEffectiveSCEVType(Ty);
00907 
00908   // Fold if the operand is constant.
00909   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
00910     return getConstant(
00911       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
00912 
00913   // zext(zext(x)) --> zext(x)
00914   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
00915     return getZeroExtendExpr(SZ->getOperand(), Ty);
00916 
00917   // Before doing any expensive analysis, check to see if we've already
00918   // computed a SCEV for this Op and Ty.
00919   FoldingSetNodeID ID;
00920   ID.AddInteger(scZeroExtend);
00921   ID.AddPointer(Op);
00922   ID.AddPointer(Ty);
00923   void *IP = nullptr;
00924   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
00925 
00926   // zext(trunc(x)) --> zext(x) or x or trunc(x)
00927   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
00928     // It's possible the bits taken off by the truncate were all zero bits. If
00929     // so, we should be able to simplify this further.
00930     const SCEV *X = ST->getOperand();
00931     ConstantRange CR = getUnsignedRange(X);
00932     unsigned TruncBits = getTypeSizeInBits(ST->getType());
00933     unsigned NewBits = getTypeSizeInBits(Ty);
00934     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
00935             CR.zextOrTrunc(NewBits)))
00936       return getTruncateOrZeroExtend(X, Ty);
00937   }
00938 
00939   // If the input value is a chrec scev, and we can prove that the value
00940   // did not overflow the old, smaller, value, we can zero extend all of the
00941   // operands (often constants).  This allows analysis of something like
00942   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
00943   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
00944     if (AR->isAffine()) {
00945       const SCEV *Start = AR->getStart();
00946       const SCEV *Step = AR->getStepRecurrence(*this);
00947       unsigned BitWidth = getTypeSizeInBits(AR->getType());
00948       const Loop *L = AR->getLoop();
00949 
00950       // If we have special knowledge that this addrec won't overflow,
00951       // we don't need to do any further analysis.
00952       if (AR->getNoWrapFlags(SCEV::FlagNUW))
00953         return getAddRecExpr(getZeroExtendExpr(Start, Ty),
00954                              getZeroExtendExpr(Step, Ty),
00955                              L, AR->getNoWrapFlags());
00956 
00957       // Check whether the backedge-taken count is SCEVCouldNotCompute.
00958       // Note that this serves two purposes: It filters out loops that are
00959       // simply not analyzable, and it covers the case where this code is
00960       // being called from within backedge-taken count analysis, such that
00961       // attempting to ask for the backedge-taken count would likely result
00962       // in infinite recursion. In the later case, the analysis code will
00963       // cope with a conservative value, and it will take care to purge
00964       // that value once it has finished.
00965       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
00966       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
00967         // Manually compute the final value for AR, checking for
00968         // overflow.
00969 
00970         // Check whether the backedge-taken count can be losslessly casted to
00971         // the addrec's type. The count is always unsigned.
00972         const SCEV *CastedMaxBECount =
00973           getTruncateOrZeroExtend(MaxBECount, Start->getType());
00974         const SCEV *RecastedMaxBECount =
00975           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
00976         if (MaxBECount == RecastedMaxBECount) {
00977           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
00978           // Check whether Start+Step*MaxBECount has no unsigned overflow.
00979           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
00980           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
00981           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
00982           const SCEV *WideMaxBECount =
00983             getZeroExtendExpr(CastedMaxBECount, WideTy);
00984           const SCEV *OperandExtendedAdd =
00985             getAddExpr(WideStart,
00986                        getMulExpr(WideMaxBECount,
00987                                   getZeroExtendExpr(Step, WideTy)));
00988           if (ZAdd == OperandExtendedAdd) {
00989             // Cache knowledge of AR NUW, which is propagated to this AddRec.
00990             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
00991             // Return the expression with the addrec on the outside.
00992             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
00993                                  getZeroExtendExpr(Step, Ty),
00994                                  L, AR->getNoWrapFlags());
00995           }
00996           // Similar to above, only this time treat the step value as signed.
00997           // This covers loops that count down.
00998           OperandExtendedAdd =
00999             getAddExpr(WideStart,
01000                        getMulExpr(WideMaxBECount,
01001                                   getSignExtendExpr(Step, WideTy)));
01002           if (ZAdd == OperandExtendedAdd) {
01003             // Cache knowledge of AR NW, which is propagated to this AddRec.
01004             // Negative step causes unsigned wrap, but it still can't self-wrap.
01005             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
01006             // Return the expression with the addrec on the outside.
01007             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
01008                                  getSignExtendExpr(Step, Ty),
01009                                  L, AR->getNoWrapFlags());
01010           }
01011         }
01012 
01013         // If the backedge is guarded by a comparison with the pre-inc value
01014         // the addrec is safe. Also, if the entry is guarded by a comparison
01015         // with the start value and the backedge is guarded by a comparison
01016         // with the post-inc value, the addrec is safe.
01017         if (isKnownPositive(Step)) {
01018           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
01019                                       getUnsignedRange(Step).getUnsignedMax());
01020           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
01021               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
01022                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
01023                                            AR->getPostIncExpr(*this), N))) {
01024             // Cache knowledge of AR NUW, which is propagated to this AddRec.
01025             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
01026             // Return the expression with the addrec on the outside.
01027             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
01028                                  getZeroExtendExpr(Step, Ty),
01029                                  L, AR->getNoWrapFlags());
01030           }
01031         } else if (isKnownNegative(Step)) {
01032           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
01033                                       getSignedRange(Step).getSignedMin());
01034           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
01035               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
01036                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
01037                                            AR->getPostIncExpr(*this), N))) {
01038             // Cache knowledge of AR NW, which is propagated to this AddRec.
01039             // Negative step causes unsigned wrap, but it still can't self-wrap.
01040             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
01041             // Return the expression with the addrec on the outside.
01042             return getAddRecExpr(getZeroExtendExpr(Start, Ty),
01043                                  getSignExtendExpr(Step, Ty),
01044                                  L, AR->getNoWrapFlags());
01045           }
01046         }
01047       }
01048     }
01049 
01050   // The cast wasn't folded; create an explicit cast node.
01051   // Recompute the insert position, as it may have been invalidated.
01052   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
01053   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
01054                                                    Op, Ty);
01055   UniqueSCEVs.InsertNode(S, IP);
01056   return S;
01057 }
01058 
01059 // Get the limit of a recurrence such that incrementing by Step cannot cause
01060 // signed overflow as long as the value of the recurrence within the loop does
01061 // not exceed this limit before incrementing.
01062 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
01063                                            ICmpInst::Predicate *Pred,
01064                                            ScalarEvolution *SE) {
01065   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
01066   if (SE->isKnownPositive(Step)) {
01067     *Pred = ICmpInst::ICMP_SLT;
01068     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
01069                            SE->getSignedRange(Step).getSignedMax());
01070   }
01071   if (SE->isKnownNegative(Step)) {
01072     *Pred = ICmpInst::ICMP_SGT;
01073     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
01074                        SE->getSignedRange(Step).getSignedMin());
01075   }
01076   return nullptr;
01077 }
01078 
01079 // The recurrence AR has been shown to have no signed wrap. Typically, if we can
01080 // prove NSW for AR, then we can just as easily prove NSW for its preincrement
01081 // or postincrement sibling. This allows normalizing a sign extended AddRec as
01082 // such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
01083 // result, the expression "Step + sext(PreIncAR)" is congruent with
01084 // "sext(PostIncAR)"
01085 static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
01086                                             Type *Ty,
01087                                             ScalarEvolution *SE) {
01088   const Loop *L = AR->getLoop();
01089   const SCEV *Start = AR->getStart();
01090   const SCEV *Step = AR->getStepRecurrence(*SE);
01091 
01092   // Check for a simple looking step prior to loop entry.
01093   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
01094   if (!SA)
01095     return nullptr;
01096 
01097   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
01098   // subtraction is expensive. For this purpose, perform a quick and dirty
01099   // difference, by checking for Step in the operand list.
01100   SmallVector<const SCEV *, 4> DiffOps;
01101   for (const SCEV *Op : SA->operands())
01102     if (Op != Step)
01103       DiffOps.push_back(Op);
01104 
01105   if (DiffOps.size() == SA->getNumOperands())
01106     return nullptr;
01107 
01108   // This is a postinc AR. Check for overflow on the preinc recurrence using the
01109   // same three conditions that getSignExtendedExpr checks.
01110 
01111   // 1. NSW flags on the step increment.
01112   const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
01113   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
01114     SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
01115 
01116   if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
01117     return PreStart;
01118 
01119   // 2. Direct overflow check on the step operation's expression.
01120   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
01121   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
01122   const SCEV *OperandExtendedStart =
01123     SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
01124                    SE->getSignExtendExpr(Step, WideTy));
01125   if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
01126     // Cache knowledge of PreAR NSW.
01127     if (PreAR)
01128       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
01129     // FIXME: this optimization needs a unit test
01130     DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
01131     return PreStart;
01132   }
01133 
01134   // 3. Loop precondition.
01135   ICmpInst::Predicate Pred;
01136   const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
01137 
01138   if (OverflowLimit &&
01139       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
01140     return PreStart;
01141   }
01142   return nullptr;
01143 }
01144 
01145 // Get the normalized sign-extended expression for this AddRec's Start.
01146 static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
01147                                             Type *Ty,
01148                                             ScalarEvolution *SE) {
01149   const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
01150   if (!PreStart)
01151     return SE->getSignExtendExpr(AR->getStart(), Ty);
01152 
01153   return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
01154                         SE->getSignExtendExpr(PreStart, Ty));
01155 }
01156 
01157 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
01158                                                Type *Ty) {
01159   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
01160          "This is not an extending conversion!");
01161   assert(isSCEVable(Ty) &&
01162          "This is not a conversion to a SCEVable type!");
01163   Ty = getEffectiveSCEVType(Ty);
01164 
01165   // Fold if the operand is constant.
01166   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
01167     return getConstant(
01168       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
01169 
01170   // sext(sext(x)) --> sext(x)
01171   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
01172     return getSignExtendExpr(SS->getOperand(), Ty);
01173 
01174   // sext(zext(x)) --> zext(x)
01175   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
01176     return getZeroExtendExpr(SZ->getOperand(), Ty);
01177 
01178   // Before doing any expensive analysis, check to see if we've already
01179   // computed a SCEV for this Op and Ty.
01180   FoldingSetNodeID ID;
01181   ID.AddInteger(scSignExtend);
01182   ID.AddPointer(Op);
01183   ID.AddPointer(Ty);
01184   void *IP = nullptr;
01185   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
01186 
01187   // If the input value is provably positive, build a zext instead.
01188   if (isKnownNonNegative(Op))
01189     return getZeroExtendExpr(Op, Ty);
01190 
01191   // sext(trunc(x)) --> sext(x) or x or trunc(x)
01192   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
01193     // It's possible the bits taken off by the truncate were all sign bits. If
01194     // so, we should be able to simplify this further.
01195     const SCEV *X = ST->getOperand();
01196     ConstantRange CR = getSignedRange(X);
01197     unsigned TruncBits = getTypeSizeInBits(ST->getType());
01198     unsigned NewBits = getTypeSizeInBits(Ty);
01199     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
01200             CR.sextOrTrunc(NewBits)))
01201       return getTruncateOrSignExtend(X, Ty);
01202   }
01203 
01204   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
01205   if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
01206     if (SA->getNumOperands() == 2) {
01207       auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
01208       auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
01209       if (SMul && SC1) {
01210         if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
01211           const APInt &C1 = SC1->getValue()->getValue();
01212           const APInt &C2 = SC2->getValue()->getValue();
01213           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
01214               C2.ugt(C1) && C2.isPowerOf2())
01215             return getAddExpr(getSignExtendExpr(SC1, Ty),
01216                               getSignExtendExpr(SMul, Ty));
01217         }
01218       }
01219     }
01220   }
01221   // If the input value is a chrec scev, and we can prove that the value
01222   // did not overflow the old, smaller, value, we can sign extend all of the
01223   // operands (often constants).  This allows analysis of something like
01224   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
01225   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
01226     if (AR->isAffine()) {
01227       const SCEV *Start = AR->getStart();
01228       const SCEV *Step = AR->getStepRecurrence(*this);
01229       unsigned BitWidth = getTypeSizeInBits(AR->getType());
01230       const Loop *L = AR->getLoop();
01231 
01232       // If we have special knowledge that this addrec won't overflow,
01233       // we don't need to do any further analysis.
01234       if (AR->getNoWrapFlags(SCEV::FlagNSW))
01235         return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01236                              getSignExtendExpr(Step, Ty),
01237                              L, SCEV::FlagNSW);
01238 
01239       // Check whether the backedge-taken count is SCEVCouldNotCompute.
01240       // Note that this serves two purposes: It filters out loops that are
01241       // simply not analyzable, and it covers the case where this code is
01242       // being called from within backedge-taken count analysis, such that
01243       // attempting to ask for the backedge-taken count would likely result
01244       // in infinite recursion. In the later case, the analysis code will
01245       // cope with a conservative value, and it will take care to purge
01246       // that value once it has finished.
01247       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
01248       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
01249         // Manually compute the final value for AR, checking for
01250         // overflow.
01251 
01252         // Check whether the backedge-taken count can be losslessly casted to
01253         // the addrec's type. The count is always unsigned.
01254         const SCEV *CastedMaxBECount =
01255           getTruncateOrZeroExtend(MaxBECount, Start->getType());
01256         const SCEV *RecastedMaxBECount =
01257           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
01258         if (MaxBECount == RecastedMaxBECount) {
01259           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
01260           // Check whether Start+Step*MaxBECount has no signed overflow.
01261           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
01262           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
01263           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
01264           const SCEV *WideMaxBECount =
01265             getZeroExtendExpr(CastedMaxBECount, WideTy);
01266           const SCEV *OperandExtendedAdd =
01267             getAddExpr(WideStart,
01268                        getMulExpr(WideMaxBECount,
01269                                   getSignExtendExpr(Step, WideTy)));
01270           if (SAdd == OperandExtendedAdd) {
01271             // Cache knowledge of AR NSW, which is propagated to this AddRec.
01272             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
01273             // Return the expression with the addrec on the outside.
01274             return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01275                                  getSignExtendExpr(Step, Ty),
01276                                  L, AR->getNoWrapFlags());
01277           }
01278           // Similar to above, only this time treat the step value as unsigned.
01279           // This covers loops that count up with an unsigned step.
01280           OperandExtendedAdd =
01281             getAddExpr(WideStart,
01282                        getMulExpr(WideMaxBECount,
01283                                   getZeroExtendExpr(Step, WideTy)));
01284           if (SAdd == OperandExtendedAdd) {
01285             // Cache knowledge of AR NSW, which is propagated to this AddRec.
01286             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
01287             // Return the expression with the addrec on the outside.
01288             return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01289                                  getZeroExtendExpr(Step, Ty),
01290                                  L, AR->getNoWrapFlags());
01291           }
01292         }
01293 
01294         // If the backedge is guarded by a comparison with the pre-inc value
01295         // the addrec is safe. Also, if the entry is guarded by a comparison
01296         // with the start value and the backedge is guarded by a comparison
01297         // with the post-inc value, the addrec is safe.
01298         ICmpInst::Predicate Pred;
01299         const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
01300         if (OverflowLimit &&
01301             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
01302              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
01303               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
01304                                           OverflowLimit)))) {
01305           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
01306           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
01307           return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
01308                                getSignExtendExpr(Step, Ty),
01309                                L, AR->getNoWrapFlags());
01310         }
01311       }
01312       // If Start and Step are constants, check if we can apply this
01313       // transformation:
01314       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
01315       auto SC1 = dyn_cast<SCEVConstant>(Start);
01316       auto SC2 = dyn_cast<SCEVConstant>(Step);
01317       if (SC1 && SC2) {
01318         const APInt &C1 = SC1->getValue()->getValue();
01319         const APInt &C2 = SC2->getValue()->getValue();
01320         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
01321             C2.isPowerOf2()) {
01322           Start = getSignExtendExpr(Start, Ty);
01323           const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
01324                                             L, AR->getNoWrapFlags());
01325           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
01326         }
01327       }
01328     }
01329 
01330   // The cast wasn't folded; create an explicit cast node.
01331   // Recompute the insert position, as it may have been invalidated.
01332   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
01333   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
01334                                                    Op, Ty);
01335   UniqueSCEVs.InsertNode(S, IP);
01336   return S;
01337 }
01338 
01339 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
01340 /// unspecified bits out to the given type.
01341 ///
01342 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
01343                                               Type *Ty) {
01344   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
01345          "This is not an extending conversion!");
01346   assert(isSCEVable(Ty) &&
01347          "This is not a conversion to a SCEVable type!");
01348   Ty = getEffectiveSCEVType(Ty);
01349 
01350   // Sign-extend negative constants.
01351   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
01352     if (SC->getValue()->getValue().isNegative())
01353       return getSignExtendExpr(Op, Ty);
01354 
01355   // Peel off a truncate cast.
01356   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
01357     const SCEV *NewOp = T->getOperand();
01358     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
01359       return getAnyExtendExpr(NewOp, Ty);
01360     return getTruncateOrNoop(NewOp, Ty);
01361   }
01362 
01363   // Next try a zext cast. If the cast is folded, use it.
01364   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
01365   if (!isa<SCEVZeroExtendExpr>(ZExt))
01366     return ZExt;
01367 
01368   // Next try a sext cast. If the cast is folded, use it.
01369   const SCEV *SExt = getSignExtendExpr(Op, Ty);
01370   if (!isa<SCEVSignExtendExpr>(SExt))
01371     return SExt;
01372 
01373   // Force the cast to be folded into the operands of an addrec.
01374   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
01375     SmallVector<const SCEV *, 4> Ops;
01376     for (const SCEV *Op : AR->operands())
01377       Ops.push_back(getAnyExtendExpr(Op, Ty));
01378     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
01379   }
01380 
01381   // If the expression is obviously signed, use the sext cast value.
01382   if (isa<SCEVSMaxExpr>(Op))
01383     return SExt;
01384 
01385   // Absent any other information, use the zext cast value.
01386   return ZExt;
01387 }
01388 
01389 /// CollectAddOperandsWithScales - Process the given Ops list, which is
01390 /// a list of operands to be added under the given scale, update the given
01391 /// map. This is a helper function for getAddRecExpr. As an example of
01392 /// what it does, given a sequence of operands that would form an add
01393 /// expression like this:
01394 ///
01395 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
01396 ///
01397 /// where A and B are constants, update the map with these values:
01398 ///
01399 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
01400 ///
01401 /// and add 13 + A*B*29 to AccumulatedConstant.
01402 /// This will allow getAddRecExpr to produce this:
01403 ///
01404 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
01405 ///
01406 /// This form often exposes folding opportunities that are hidden in
01407 /// the original operand list.
01408 ///
01409 /// Return true iff it appears that any interesting folding opportunities
01410 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
01411 /// the common case where no interesting opportunities are present, and
01412 /// is also used as a check to avoid infinite recursion.
01413 ///
01414 static bool
01415 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
01416                              SmallVectorImpl<const SCEV *> &NewOps,
01417                              APInt &AccumulatedConstant,
01418                              const SCEV *const *Ops, size_t NumOperands,
01419                              const APInt &Scale,
01420                              ScalarEvolution &SE) {
01421   bool Interesting = false;
01422 
01423   // Iterate over the add operands. They are sorted, with constants first.
01424   unsigned i = 0;
01425   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
01426     ++i;
01427     // Pull a buried constant out to the outside.
01428     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
01429       Interesting = true;
01430     AccumulatedConstant += Scale * C->getValue()->getValue();
01431   }
01432 
01433   // Next comes everything else. We're especially interested in multiplies
01434   // here, but they're in the middle, so just visit the rest with one loop.
01435   for (; i != NumOperands; ++i) {
01436     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
01437     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
01438       APInt NewScale =
01439         Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
01440       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
01441         // A multiplication of a constant with another add; recurse.
01442         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
01443         Interesting |=
01444           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
01445                                        Add->op_begin(), Add->getNumOperands(),
01446                                        NewScale, SE);
01447       } else {
01448         // A multiplication of a constant with some other value. Update
01449         // the map.
01450         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
01451         const SCEV *Key = SE.getMulExpr(MulOps);
01452         std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
01453           M.insert(std::make_pair(Key, NewScale));
01454         if (Pair.second) {
01455           NewOps.push_back(Pair.first->first);
01456         } else {
01457           Pair.first->second += NewScale;
01458           // The map already had an entry for this value, which may indicate
01459           // a folding opportunity.
01460           Interesting = true;
01461         }
01462       }
01463     } else {
01464       // An ordinary operand. Update the map.
01465       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
01466         M.insert(std::make_pair(Ops[i], Scale));
01467       if (Pair.second) {
01468         NewOps.push_back(Pair.first->first);
01469       } else {
01470         Pair.first->second += Scale;
01471         // The map already had an entry for this value, which may indicate
01472         // a folding opportunity.
01473         Interesting = true;
01474       }
01475     }
01476   }
01477 
01478   return Interesting;
01479 }
01480 
01481 namespace {
01482   struct APIntCompare {
01483     bool operator()(const APInt &LHS, const APInt &RHS) const {
01484       return LHS.ult(RHS);
01485     }
01486   };
01487 }
01488 
01489 /// getAddExpr - Get a canonical add expression, or something simpler if
01490 /// possible.
01491 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
01492                                         SCEV::NoWrapFlags Flags) {
01493   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
01494          "only nuw or nsw allowed");
01495   assert(!Ops.empty() && "Cannot get empty add!");
01496   if (Ops.size() == 1) return Ops[0];
01497 #ifndef NDEBUG
01498   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
01499   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
01500     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
01501            "SCEVAddExpr operand types don't match!");
01502 #endif
01503 
01504   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
01505   // And vice-versa.
01506   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
01507   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
01508   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
01509     bool All = true;
01510     for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
01511          E = Ops.end(); I != E; ++I)
01512       if (!isKnownNonNegative(*I)) {
01513         All = false;
01514         break;
01515       }
01516     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
01517   }
01518 
01519   // Sort by complexity, this groups all similar expression types together.
01520   GroupByComplexity(Ops, LI);
01521 
01522   // If there are any constants, fold them together.
01523   unsigned Idx = 0;
01524   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
01525     ++Idx;
01526     assert(Idx < Ops.size());
01527     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
01528       // We found two constants, fold them together!
01529       Ops[0] = getConstant(LHSC->getValue()->getValue() +
01530                            RHSC->getValue()->getValue());
01531       if (Ops.size() == 2) return Ops[0];
01532       Ops.erase(Ops.begin()+1);  // Erase the folded element
01533       LHSC = cast<SCEVConstant>(Ops[0]);
01534     }
01535 
01536     // If we are left with a constant zero being added, strip it off.
01537     if (LHSC->getValue()->isZero()) {
01538       Ops.erase(Ops.begin());
01539       --Idx;
01540     }
01541 
01542     if (Ops.size() == 1) return Ops[0];
01543   }
01544 
01545   // Okay, check to see if the same value occurs in the operand list more than
01546   // once.  If so, merge them together into an multiply expression.  Since we
01547   // sorted the list, these values are required to be adjacent.
01548   Type *Ty = Ops[0]->getType();
01549   bool FoundMatch = false;
01550   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
01551     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
01552       // Scan ahead to count how many equal operands there are.
01553       unsigned Count = 2;
01554       while (i+Count != e && Ops[i+Count] == Ops[i])
01555         ++Count;
01556       // Merge the values into a multiply.
01557       const SCEV *Scale = getConstant(Ty, Count);
01558       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
01559       if (Ops.size() == Count)
01560         return Mul;
01561       Ops[i] = Mul;
01562       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
01563       --i; e -= Count - 1;
01564       FoundMatch = true;
01565     }
01566   if (FoundMatch)
01567     return getAddExpr(Ops, Flags);
01568 
01569   // Check for truncates. If all the operands are truncated from the same
01570   // type, see if factoring out the truncate would permit the result to be
01571   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
01572   // if the contents of the resulting outer trunc fold to something simple.
01573   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
01574     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
01575     Type *DstType = Trunc->getType();
01576     Type *SrcType = Trunc->getOperand()->getType();
01577     SmallVector<const SCEV *, 8> LargeOps;
01578     bool Ok = true;
01579     // Check all the operands to see if they can be represented in the
01580     // source type of the truncate.
01581     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01582       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
01583         if (T->getOperand()->getType() != SrcType) {
01584           Ok = false;
01585           break;
01586         }
01587         LargeOps.push_back(T->getOperand());
01588       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
01589         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
01590       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
01591         SmallVector<const SCEV *, 8> LargeMulOps;
01592         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
01593           if (const SCEVTruncateExpr *T =
01594                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
01595             if (T->getOperand()->getType() != SrcType) {
01596               Ok = false;
01597               break;
01598             }
01599             LargeMulOps.push_back(T->getOperand());
01600           } else if (const SCEVConstant *C =
01601                        dyn_cast<SCEVConstant>(M->getOperand(j))) {
01602             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
01603           } else {
01604             Ok = false;
01605             break;
01606           }
01607         }
01608         if (Ok)
01609           LargeOps.push_back(getMulExpr(LargeMulOps));
01610       } else {
01611         Ok = false;
01612         break;
01613       }
01614     }
01615     if (Ok) {
01616       // Evaluate the expression in the larger type.
01617       const SCEV *Fold = getAddExpr(LargeOps, Flags);
01618       // If it folds to something simple, use it. Otherwise, don't.
01619       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
01620         return getTruncateExpr(Fold, DstType);
01621     }
01622   }
01623 
01624   // Skip past any other cast SCEVs.
01625   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
01626     ++Idx;
01627 
01628   // If there are add operands they would be next.
01629   if (Idx < Ops.size()) {
01630     bool DeletedAdd = false;
01631     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
01632       // If we have an add, expand the add operands onto the end of the operands
01633       // list.
01634       Ops.erase(Ops.begin()+Idx);
01635       Ops.append(Add->op_begin(), Add->op_end());
01636       DeletedAdd = true;
01637     }
01638 
01639     // If we deleted at least one add, we added operands to the end of the list,
01640     // and they are not necessarily sorted.  Recurse to resort and resimplify
01641     // any operands we just acquired.
01642     if (DeletedAdd)
01643       return getAddExpr(Ops);
01644   }
01645 
01646   // Skip over the add expression until we get to a multiply.
01647   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
01648     ++Idx;
01649 
01650   // Check to see if there are any folding opportunities present with
01651   // operands multiplied by constant values.
01652   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
01653     uint64_t BitWidth = getTypeSizeInBits(Ty);
01654     DenseMap<const SCEV *, APInt> M;
01655     SmallVector<const SCEV *, 8> NewOps;
01656     APInt AccumulatedConstant(BitWidth, 0);
01657     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
01658                                      Ops.data(), Ops.size(),
01659                                      APInt(BitWidth, 1), *this)) {
01660       // Some interesting folding opportunity is present, so its worthwhile to
01661       // re-generate the operands list. Group the operands by constant scale,
01662       // to avoid multiplying by the same constant scale multiple times.
01663       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
01664       for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
01665            E = NewOps.end(); I != E; ++I)
01666         MulOpLists[M.find(*I)->second].push_back(*I);
01667       // Re-generate the operands list.
01668       Ops.clear();
01669       if (AccumulatedConstant != 0)
01670         Ops.push_back(getConstant(AccumulatedConstant));
01671       for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
01672            I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
01673         if (I->first != 0)
01674           Ops.push_back(getMulExpr(getConstant(I->first),
01675                                    getAddExpr(I->second)));
01676       if (Ops.empty())
01677         return getConstant(Ty, 0);
01678       if (Ops.size() == 1)
01679         return Ops[0];
01680       return getAddExpr(Ops);
01681     }
01682   }
01683 
01684   // If we are adding something to a multiply expression, make sure the
01685   // something is not already an operand of the multiply.  If so, merge it into
01686   // the multiply.
01687   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
01688     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
01689     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
01690       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
01691       if (isa<SCEVConstant>(MulOpSCEV))
01692         continue;
01693       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
01694         if (MulOpSCEV == Ops[AddOp]) {
01695           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
01696           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
01697           if (Mul->getNumOperands() != 2) {
01698             // If the multiply has more than two operands, we must get the
01699             // Y*Z term.
01700             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
01701                                                 Mul->op_begin()+MulOp);
01702             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
01703             InnerMul = getMulExpr(MulOps);
01704           }
01705           const SCEV *One = getConstant(Ty, 1);
01706           const SCEV *AddOne = getAddExpr(One, InnerMul);
01707           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
01708           if (Ops.size() == 2) return OuterMul;
01709           if (AddOp < Idx) {
01710             Ops.erase(Ops.begin()+AddOp);
01711             Ops.erase(Ops.begin()+Idx-1);
01712           } else {
01713             Ops.erase(Ops.begin()+Idx);
01714             Ops.erase(Ops.begin()+AddOp-1);
01715           }
01716           Ops.push_back(OuterMul);
01717           return getAddExpr(Ops);
01718         }
01719 
01720       // Check this multiply against other multiplies being added together.
01721       for (unsigned OtherMulIdx = Idx+1;
01722            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
01723            ++OtherMulIdx) {
01724         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
01725         // If MulOp occurs in OtherMul, we can fold the two multiplies
01726         // together.
01727         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
01728              OMulOp != e; ++OMulOp)
01729           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
01730             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
01731             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
01732             if (Mul->getNumOperands() != 2) {
01733               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
01734                                                   Mul->op_begin()+MulOp);
01735               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
01736               InnerMul1 = getMulExpr(MulOps);
01737             }
01738             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
01739             if (OtherMul->getNumOperands() != 2) {
01740               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
01741                                                   OtherMul->op_begin()+OMulOp);
01742               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
01743               InnerMul2 = getMulExpr(MulOps);
01744             }
01745             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
01746             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
01747             if (Ops.size() == 2) return OuterMul;
01748             Ops.erase(Ops.begin()+Idx);
01749             Ops.erase(Ops.begin()+OtherMulIdx-1);
01750             Ops.push_back(OuterMul);
01751             return getAddExpr(Ops);
01752           }
01753       }
01754     }
01755   }
01756 
01757   // If there are any add recurrences in the operands list, see if any other
01758   // added values are loop invariant.  If so, we can fold them into the
01759   // recurrence.
01760   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
01761     ++Idx;
01762 
01763   // Scan over all recurrences, trying to fold loop invariants into them.
01764   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
01765     // Scan all of the other operands to this add and add them to the vector if
01766     // they are loop invariant w.r.t. the recurrence.
01767     SmallVector<const SCEV *, 8> LIOps;
01768     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
01769     const Loop *AddRecLoop = AddRec->getLoop();
01770     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01771       if (isLoopInvariant(Ops[i], AddRecLoop)) {
01772         LIOps.push_back(Ops[i]);
01773         Ops.erase(Ops.begin()+i);
01774         --i; --e;
01775       }
01776 
01777     // If we found some loop invariants, fold them into the recurrence.
01778     if (!LIOps.empty()) {
01779       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
01780       LIOps.push_back(AddRec->getStart());
01781 
01782       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
01783                                              AddRec->op_end());
01784       AddRecOps[0] = getAddExpr(LIOps);
01785 
01786       // Build the new addrec. Propagate the NUW and NSW flags if both the
01787       // outer add and the inner addrec are guaranteed to have no overflow.
01788       // Always propagate NW.
01789       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
01790       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
01791 
01792       // If all of the other operands were loop invariant, we are done.
01793       if (Ops.size() == 1) return NewRec;
01794 
01795       // Otherwise, add the folded AddRec by the non-invariant parts.
01796       for (unsigned i = 0;; ++i)
01797         if (Ops[i] == AddRec) {
01798           Ops[i] = NewRec;
01799           break;
01800         }
01801       return getAddExpr(Ops);
01802     }
01803 
01804     // Okay, if there weren't any loop invariants to be folded, check to see if
01805     // there are multiple AddRec's with the same loop induction variable being
01806     // added together.  If so, we can fold them.
01807     for (unsigned OtherIdx = Idx+1;
01808          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
01809          ++OtherIdx)
01810       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
01811         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
01812         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
01813                                                AddRec->op_end());
01814         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
01815              ++OtherIdx)
01816           if (const SCEVAddRecExpr *OtherAddRec =
01817                 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
01818             if (OtherAddRec->getLoop() == AddRecLoop) {
01819               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
01820                    i != e; ++i) {
01821                 if (i >= AddRecOps.size()) {
01822                   AddRecOps.append(OtherAddRec->op_begin()+i,
01823                                    OtherAddRec->op_end());
01824                   break;
01825                 }
01826                 AddRecOps[i] = getAddExpr(AddRecOps[i],
01827                                           OtherAddRec->getOperand(i));
01828               }
01829               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
01830             }
01831         // Step size has changed, so we cannot guarantee no self-wraparound.
01832         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
01833         return getAddExpr(Ops);
01834       }
01835 
01836     // Otherwise couldn't fold anything into this recurrence.  Move onto the
01837     // next one.
01838   }
01839 
01840   // Okay, it looks like we really DO need an add expr.  Check to see if we
01841   // already have one, otherwise create a new one.
01842   FoldingSetNodeID ID;
01843   ID.AddInteger(scAddExpr);
01844   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01845     ID.AddPointer(Ops[i]);
01846   void *IP = nullptr;
01847   SCEVAddExpr *S =
01848     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
01849   if (!S) {
01850     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
01851     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
01852     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
01853                                         O, Ops.size());
01854     UniqueSCEVs.InsertNode(S, IP);
01855   }
01856   S->setNoWrapFlags(Flags);
01857   return S;
01858 }
01859 
01860 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
01861   uint64_t k = i*j;
01862   if (j > 1 && k / j != i) Overflow = true;
01863   return k;
01864 }
01865 
01866 /// Compute the result of "n choose k", the binomial coefficient.  If an
01867 /// intermediate computation overflows, Overflow will be set and the return will
01868 /// be garbage. Overflow is not cleared on absence of overflow.
01869 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
01870   // We use the multiplicative formula:
01871   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
01872   // At each iteration, we take the n-th term of the numeral and divide by the
01873   // (k-n)th term of the denominator.  This division will always produce an
01874   // integral result, and helps reduce the chance of overflow in the
01875   // intermediate computations. However, we can still overflow even when the
01876   // final result would fit.
01877 
01878   if (n == 0 || n == k) return 1;
01879   if (k > n) return 0;
01880 
01881   if (k > n/2)
01882     k = n-k;
01883 
01884   uint64_t r = 1;
01885   for (uint64_t i = 1; i <= k; ++i) {
01886     r = umul_ov(r, n-(i-1), Overflow);
01887     r /= i;
01888   }
01889   return r;
01890 }
01891 
01892 /// getMulExpr - Get a canonical multiply expression, or something simpler if
01893 /// possible.
01894 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
01895                                         SCEV::NoWrapFlags Flags) {
01896   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
01897          "only nuw or nsw allowed");
01898   assert(!Ops.empty() && "Cannot get empty mul!");
01899   if (Ops.size() == 1) return Ops[0];
01900 #ifndef NDEBUG
01901   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
01902   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
01903     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
01904            "SCEVMulExpr operand types don't match!");
01905 #endif
01906 
01907   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
01908   // And vice-versa.
01909   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
01910   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
01911   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
01912     bool All = true;
01913     for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
01914          E = Ops.end(); I != E; ++I)
01915       if (!isKnownNonNegative(*I)) {
01916         All = false;
01917         break;
01918       }
01919     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
01920   }
01921 
01922   // Sort by complexity, this groups all similar expression types together.
01923   GroupByComplexity(Ops, LI);
01924 
01925   // If there are any constants, fold them together.
01926   unsigned Idx = 0;
01927   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
01928 
01929     // C1*(C2+V) -> C1*C2 + C1*V
01930     if (Ops.size() == 2)
01931       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
01932         if (Add->getNumOperands() == 2 &&
01933             isa<SCEVConstant>(Add->getOperand(0)))
01934           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
01935                             getMulExpr(LHSC, Add->getOperand(1)));
01936 
01937     ++Idx;
01938     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
01939       // We found two constants, fold them together!
01940       ConstantInt *Fold = ConstantInt::get(getContext(),
01941                                            LHSC->getValue()->getValue() *
01942                                            RHSC->getValue()->getValue());
01943       Ops[0] = getConstant(Fold);
01944       Ops.erase(Ops.begin()+1);  // Erase the folded element
01945       if (Ops.size() == 1) return Ops[0];
01946       LHSC = cast<SCEVConstant>(Ops[0]);
01947     }
01948 
01949     // If we are left with a constant one being multiplied, strip it off.
01950     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
01951       Ops.erase(Ops.begin());
01952       --Idx;
01953     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
01954       // If we have a multiply of zero, it will always be zero.
01955       return Ops[0];
01956     } else if (Ops[0]->isAllOnesValue()) {
01957       // If we have a mul by -1 of an add, try distributing the -1 among the
01958       // add operands.
01959       if (Ops.size() == 2) {
01960         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
01961           SmallVector<const SCEV *, 4> NewOps;
01962           bool AnyFolded = false;
01963           for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
01964                  E = Add->op_end(); I != E; ++I) {
01965             const SCEV *Mul = getMulExpr(Ops[0], *I);
01966             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
01967             NewOps.push_back(Mul);
01968           }
01969           if (AnyFolded)
01970             return getAddExpr(NewOps);
01971         }
01972         else if (const SCEVAddRecExpr *
01973                  AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
01974           // Negation preserves a recurrence's no self-wrap property.
01975           SmallVector<const SCEV *, 4> Operands;
01976           for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
01977                  E = AddRec->op_end(); I != E; ++I) {
01978             Operands.push_back(getMulExpr(Ops[0], *I));
01979           }
01980           return getAddRecExpr(Operands, AddRec->getLoop(),
01981                                AddRec->getNoWrapFlags(SCEV::FlagNW));
01982         }
01983       }
01984     }
01985 
01986     if (Ops.size() == 1)
01987       return Ops[0];
01988   }
01989 
01990   // Skip over the add expression until we get to a multiply.
01991   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
01992     ++Idx;
01993 
01994   // If there are mul operands inline them all into this expression.
01995   if (Idx < Ops.size()) {
01996     bool DeletedMul = false;
01997     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
01998       // If we have an mul, expand the mul operands onto the end of the operands
01999       // list.
02000       Ops.erase(Ops.begin()+Idx);
02001       Ops.append(Mul->op_begin(), Mul->op_end());
02002       DeletedMul = true;
02003     }
02004 
02005     // If we deleted at least one mul, we added operands to the end of the list,
02006     // and they are not necessarily sorted.  Recurse to resort and resimplify
02007     // any operands we just acquired.
02008     if (DeletedMul)
02009       return getMulExpr(Ops);
02010   }
02011 
02012   // If there are any add recurrences in the operands list, see if any other
02013   // added values are loop invariant.  If so, we can fold them into the
02014   // recurrence.
02015   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
02016     ++Idx;
02017 
02018   // Scan over all recurrences, trying to fold loop invariants into them.
02019   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
02020     // Scan all of the other operands to this mul and add them to the vector if
02021     // they are loop invariant w.r.t. the recurrence.
02022     SmallVector<const SCEV *, 8> LIOps;
02023     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
02024     const Loop *AddRecLoop = AddRec->getLoop();
02025     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02026       if (isLoopInvariant(Ops[i], AddRecLoop)) {
02027         LIOps.push_back(Ops[i]);
02028         Ops.erase(Ops.begin()+i);
02029         --i; --e;
02030       }
02031 
02032     // If we found some loop invariants, fold them into the recurrence.
02033     if (!LIOps.empty()) {
02034       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
02035       SmallVector<const SCEV *, 4> NewOps;
02036       NewOps.reserve(AddRec->getNumOperands());
02037       const SCEV *Scale = getMulExpr(LIOps);
02038       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
02039         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
02040 
02041       // Build the new addrec. Propagate the NUW and NSW flags if both the
02042       // outer mul and the inner addrec are guaranteed to have no overflow.
02043       //
02044       // No self-wrap cannot be guaranteed after changing the step size, but
02045       // will be inferred if either NUW or NSW is true.
02046       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
02047       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
02048 
02049       // If all of the other operands were loop invariant, we are done.
02050       if (Ops.size() == 1) return NewRec;
02051 
02052       // Otherwise, multiply the folded AddRec by the non-invariant parts.
02053       for (unsigned i = 0;; ++i)
02054         if (Ops[i] == AddRec) {
02055           Ops[i] = NewRec;
02056           break;
02057         }
02058       return getMulExpr(Ops);
02059     }
02060 
02061     // Okay, if there weren't any loop invariants to be folded, check to see if
02062     // there are multiple AddRec's with the same loop induction variable being
02063     // multiplied together.  If so, we can fold them.
02064 
02065     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
02066     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
02067     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
02068     //   ]]],+,...up to x=2n}.
02069     // Note that the arguments to choose() are always integers with values
02070     // known at compile time, never SCEV objects.
02071     //
02072     // The implementation avoids pointless extra computations when the two
02073     // addrec's are of different length (mathematically, it's equivalent to
02074     // an infinite stream of zeros on the right).
02075     bool OpsModified = false;
02076     for (unsigned OtherIdx = Idx+1;
02077          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
02078          ++OtherIdx) {
02079       const SCEVAddRecExpr *OtherAddRec =
02080         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
02081       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
02082         continue;
02083 
02084       bool Overflow = false;
02085       Type *Ty = AddRec->getType();
02086       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
02087       SmallVector<const SCEV*, 7> AddRecOps;
02088       for (int x = 0, xe = AddRec->getNumOperands() +
02089              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
02090         const SCEV *Term = getConstant(Ty, 0);
02091         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
02092           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
02093           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
02094                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
02095                z < ze && !Overflow; ++z) {
02096             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
02097             uint64_t Coeff;
02098             if (LargerThan64Bits)
02099               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
02100             else
02101               Coeff = Coeff1*Coeff2;
02102             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
02103             const SCEV *Term1 = AddRec->getOperand(y-z);
02104             const SCEV *Term2 = OtherAddRec->getOperand(z);
02105             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
02106           }
02107         }
02108         AddRecOps.push_back(Term);
02109       }
02110       if (!Overflow) {
02111         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
02112                                               SCEV::FlagAnyWrap);
02113         if (Ops.size() == 2) return NewAddRec;
02114         Ops[Idx] = NewAddRec;
02115         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
02116         OpsModified = true;
02117         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
02118         if (!AddRec)
02119           break;
02120       }
02121     }
02122     if (OpsModified)
02123       return getMulExpr(Ops);
02124 
02125     // Otherwise couldn't fold anything into this recurrence.  Move onto the
02126     // next one.
02127   }
02128 
02129   // Okay, it looks like we really DO need an mul expr.  Check to see if we
02130   // already have one, otherwise create a new one.
02131   FoldingSetNodeID ID;
02132   ID.AddInteger(scMulExpr);
02133   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02134     ID.AddPointer(Ops[i]);
02135   void *IP = nullptr;
02136   SCEVMulExpr *S =
02137     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
02138   if (!S) {
02139     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
02140     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
02141     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
02142                                         O, Ops.size());
02143     UniqueSCEVs.InsertNode(S, IP);
02144   }
02145   S->setNoWrapFlags(Flags);
02146   return S;
02147 }
02148 
02149 /// getUDivExpr - Get a canonical unsigned division expression, or something
02150 /// simpler if possible.
02151 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
02152                                          const SCEV *RHS) {
02153   assert(getEffectiveSCEVType(LHS->getType()) ==
02154          getEffectiveSCEVType(RHS->getType()) &&
02155          "SCEVUDivExpr operand types don't match!");
02156 
02157   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
02158     if (RHSC->getValue()->equalsInt(1))
02159       return LHS;                               // X udiv 1 --> x
02160     // If the denominator is zero, the result of the udiv is undefined. Don't
02161     // try to analyze it, because the resolution chosen here may differ from
02162     // the resolution chosen in other parts of the compiler.
02163     if (!RHSC->getValue()->isZero()) {
02164       // Determine if the division can be folded into the operands of
02165       // its operands.
02166       // TODO: Generalize this to non-constants by using known-bits information.
02167       Type *Ty = LHS->getType();
02168       unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
02169       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
02170       // For non-power-of-two values, effectively round the value up to the
02171       // nearest power of two.
02172       if (!RHSC->getValue()->getValue().isPowerOf2())
02173         ++MaxShiftAmt;
02174       IntegerType *ExtTy =
02175         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
02176       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
02177         if (const SCEVConstant *Step =
02178             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
02179           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
02180           const APInt &StepInt = Step->getValue()->getValue();
02181           const APInt &DivInt = RHSC->getValue()->getValue();
02182           if (!StepInt.urem(DivInt) &&
02183               getZeroExtendExpr(AR, ExtTy) ==
02184               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
02185                             getZeroExtendExpr(Step, ExtTy),
02186                             AR->getLoop(), SCEV::FlagAnyWrap)) {
02187             SmallVector<const SCEV *, 4> Operands;
02188             for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
02189               Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
02190             return getAddRecExpr(Operands, AR->getLoop(),
02191                                  SCEV::FlagNW);
02192           }
02193           /// Get a canonical UDivExpr for a recurrence.
02194           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
02195           // We can currently only fold X%N if X is constant.
02196           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
02197           if (StartC && !DivInt.urem(StepInt) &&
02198               getZeroExtendExpr(AR, ExtTy) ==
02199               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
02200                             getZeroExtendExpr(Step, ExtTy),
02201                             AR->getLoop(), SCEV::FlagAnyWrap)) {
02202             const APInt &StartInt = StartC->getValue()->getValue();
02203             const APInt &StartRem = StartInt.urem(StepInt);
02204             if (StartRem != 0)
02205               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
02206                                   AR->getLoop(), SCEV::FlagNW);
02207           }
02208         }
02209       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
02210       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
02211         SmallVector<const SCEV *, 4> Operands;
02212         for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
02213           Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
02214         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
02215           // Find an operand that's safely divisible.
02216           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
02217             const SCEV *Op = M->getOperand(i);
02218             const SCEV *Div = getUDivExpr(Op, RHSC);
02219             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
02220               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
02221                                                       M->op_end());
02222               Operands[i] = Div;
02223               return getMulExpr(Operands);
02224             }
02225           }
02226       }
02227       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
02228       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
02229         SmallVector<const SCEV *, 4> Operands;
02230         for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
02231           Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
02232         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
02233           Operands.clear();
02234           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
02235             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
02236             if (isa<SCEVUDivExpr>(Op) ||
02237                 getMulExpr(Op, RHS) != A->getOperand(i))
02238               break;
02239             Operands.push_back(Op);
02240           }
02241           if (Operands.size() == A->getNumOperands())
02242             return getAddExpr(Operands);
02243         }
02244       }
02245 
02246       // Fold if both operands are constant.
02247       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
02248         Constant *LHSCV = LHSC->getValue();
02249         Constant *RHSCV = RHSC->getValue();
02250         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
02251                                                                    RHSCV)));
02252       }
02253     }
02254   }
02255 
02256   FoldingSetNodeID ID;
02257   ID.AddInteger(scUDivExpr);
02258   ID.AddPointer(LHS);
02259   ID.AddPointer(RHS);
02260   void *IP = nullptr;
02261   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
02262   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
02263                                              LHS, RHS);
02264   UniqueSCEVs.InsertNode(S, IP);
02265   return S;
02266 }
02267 
02268 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
02269   APInt A = C1->getValue()->getValue().abs();
02270   APInt B = C2->getValue()->getValue().abs();
02271   uint32_t ABW = A.getBitWidth();
02272   uint32_t BBW = B.getBitWidth();
02273 
02274   if (ABW > BBW)
02275     B = B.zext(ABW);
02276   else if (ABW < BBW)
02277     A = A.zext(BBW);
02278 
02279   return APIntOps::GreatestCommonDivisor(A, B);
02280 }
02281 
02282 /// getUDivExactExpr - Get a canonical unsigned division expression, or
02283 /// something simpler if possible. There is no representation for an exact udiv
02284 /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
02285 /// We can't do this when it's not exact because the udiv may be clearing bits.
02286 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
02287                                               const SCEV *RHS) {
02288   // TODO: we could try to find factors in all sorts of things, but for now we
02289   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
02290   // end of this file for inspiration.
02291 
02292   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
02293   if (!Mul)
02294     return getUDivExpr(LHS, RHS);
02295 
02296   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
02297     // If the mulexpr multiplies by a constant, then that constant must be the
02298     // first element of the mulexpr.
02299     if (const SCEVConstant *LHSCst =
02300             dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
02301       if (LHSCst == RHSCst) {
02302         SmallVector<const SCEV *, 2> Operands;
02303         Operands.append(Mul->op_begin() + 1, Mul->op_end());
02304         return getMulExpr(Operands);
02305       }
02306 
02307       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
02308       // that there's a factor provided by one of the other terms. We need to
02309       // check.
02310       APInt Factor = gcd(LHSCst, RHSCst);
02311       if (!Factor.isIntN(1)) {
02312         LHSCst = cast<SCEVConstant>(
02313             getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
02314         RHSCst = cast<SCEVConstant>(
02315             getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
02316         SmallVector<const SCEV *, 2> Operands;
02317         Operands.push_back(LHSCst);
02318         Operands.append(Mul->op_begin() + 1, Mul->op_end());
02319         LHS = getMulExpr(Operands);
02320         RHS = RHSCst;
02321         Mul = dyn_cast<SCEVMulExpr>(LHS);
02322         if (!Mul)
02323           return getUDivExactExpr(LHS, RHS);
02324       }
02325     }
02326   }
02327 
02328   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
02329     if (Mul->getOperand(i) == RHS) {
02330       SmallVector<const SCEV *, 2> Operands;
02331       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
02332       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
02333       return getMulExpr(Operands);
02334     }
02335   }
02336 
02337   return getUDivExpr(LHS, RHS);
02338 }
02339 
02340 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
02341 /// Simplify the expression as much as possible.
02342 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
02343                                            const Loop *L,
02344                                            SCEV::NoWrapFlags Flags) {
02345   SmallVector<const SCEV *, 4> Operands;
02346   Operands.push_back(Start);
02347   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
02348     if (StepChrec->getLoop() == L) {
02349       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
02350       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
02351     }
02352 
02353   Operands.push_back(Step);
02354   return getAddRecExpr(Operands, L, Flags);
02355 }
02356 
02357 /// getAddRecExpr - Get an add recurrence expression for the specified loop.
02358 /// Simplify the expression as much as possible.
02359 const SCEV *
02360 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
02361                                const Loop *L, SCEV::NoWrapFlags Flags) {
02362   if (Operands.size() == 1) return Operands[0];
02363 #ifndef NDEBUG
02364   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
02365   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
02366     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
02367            "SCEVAddRecExpr operand types don't match!");
02368   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
02369     assert(isLoopInvariant(Operands[i], L) &&
02370            "SCEVAddRecExpr operand is not loop-invariant!");
02371 #endif
02372 
02373   if (Operands.back()->isZero()) {
02374     Operands.pop_back();
02375     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
02376   }
02377 
02378   // It's tempting to want to call getMaxBackedgeTakenCount count here and
02379   // use that information to infer NUW and NSW flags. However, computing a
02380   // BE count requires calling getAddRecExpr, so we may not yet have a
02381   // meaningful BE count at this point (and if we don't, we'd be stuck
02382   // with a SCEVCouldNotCompute as the cached BE count).
02383 
02384   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
02385   // And vice-versa.
02386   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
02387   SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
02388   if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
02389     bool All = true;
02390     for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
02391          E = Operands.end(); I != E; ++I)
02392       if (!isKnownNonNegative(*I)) {
02393         All = false;
02394         break;
02395       }
02396     if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
02397   }
02398 
02399   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
02400   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
02401     const Loop *NestedLoop = NestedAR->getLoop();
02402     if (L->contains(NestedLoop) ?
02403         (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
02404         (!NestedLoop->contains(L) &&
02405          DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
02406       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
02407                                                   NestedAR->op_end());
02408       Operands[0] = NestedAR->getStart();
02409       // AddRecs require their operands be loop-invariant with respect to their
02410       // loops. Don't perform this transformation if it would break this
02411       // requirement.
02412       bool AllInvariant = true;
02413       for (unsigned i = 0, e = Operands.size(); i != e; ++i)
02414         if (!isLoopInvariant(Operands[i], L)) {
02415           AllInvariant = false;
02416           break;
02417         }
02418       if (AllInvariant) {
02419         // Create a recurrence for the outer loop with the same step size.
02420         //
02421         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
02422         // inner recurrence has the same property.
02423         SCEV::NoWrapFlags OuterFlags =
02424           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
02425 
02426         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
02427         AllInvariant = true;
02428         for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
02429           if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
02430             AllInvariant = false;
02431             break;
02432           }
02433         if (AllInvariant) {
02434           // Ok, both add recurrences are valid after the transformation.
02435           //
02436           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
02437           // the outer recurrence has the same property.
02438           SCEV::NoWrapFlags InnerFlags =
02439             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
02440           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
02441         }
02442       }
02443       // Reset Operands to its original state.
02444       Operands[0] = NestedAR;
02445     }
02446   }
02447 
02448   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
02449   // already have one, otherwise create a new one.
02450   FoldingSetNodeID ID;
02451   ID.AddInteger(scAddRecExpr);
02452   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
02453     ID.AddPointer(Operands[i]);
02454   ID.AddPointer(L);
02455   void *IP = nullptr;
02456   SCEVAddRecExpr *S =
02457     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
02458   if (!S) {
02459     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
02460     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
02461     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
02462                                            O, Operands.size(), L);
02463     UniqueSCEVs.InsertNode(S, IP);
02464   }
02465   S->setNoWrapFlags(Flags);
02466   return S;
02467 }
02468 
02469 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
02470                                          const SCEV *RHS) {
02471   SmallVector<const SCEV *, 2> Ops;
02472   Ops.push_back(LHS);
02473   Ops.push_back(RHS);
02474   return getSMaxExpr(Ops);
02475 }
02476 
02477 const SCEV *
02478 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
02479   assert(!Ops.empty() && "Cannot get empty smax!");
02480   if (Ops.size() == 1) return Ops[0];
02481 #ifndef NDEBUG
02482   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
02483   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
02484     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
02485            "SCEVSMaxExpr operand types don't match!");
02486 #endif
02487 
02488   // Sort by complexity, this groups all similar expression types together.
02489   GroupByComplexity(Ops, LI);
02490 
02491   // If there are any constants, fold them together.
02492   unsigned Idx = 0;
02493   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
02494     ++Idx;
02495     assert(Idx < Ops.size());
02496     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
02497       // We found two constants, fold them together!
02498       ConstantInt *Fold = ConstantInt::get(getContext(),
02499                               APIntOps::smax(LHSC->getValue()->getValue(),
02500                                              RHSC->getValue()->getValue()));
02501       Ops[0] = getConstant(Fold);
02502       Ops.erase(Ops.begin()+1);  // Erase the folded element
02503       if (Ops.size() == 1) return Ops[0];
02504       LHSC = cast<SCEVConstant>(Ops[0]);
02505     }
02506 
02507     // If we are left with a constant minimum-int, strip it off.
02508     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
02509       Ops.erase(Ops.begin());
02510       --Idx;
02511     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
02512       // If we have an smax with a constant maximum-int, it will always be
02513       // maximum-int.
02514       return Ops[0];
02515     }
02516 
02517     if (Ops.size() == 1) return Ops[0];
02518   }
02519 
02520   // Find the first SMax
02521   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
02522     ++Idx;
02523 
02524   // Check to see if one of the operands is an SMax. If so, expand its operands
02525   // onto our operand list, and recurse to simplify.
02526   if (Idx < Ops.size()) {
02527     bool DeletedSMax = false;
02528     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
02529       Ops.erase(Ops.begin()+Idx);
02530       Ops.append(SMax->op_begin(), SMax->op_end());
02531       DeletedSMax = true;
02532     }
02533 
02534     if (DeletedSMax)
02535       return getSMaxExpr(Ops);
02536   }
02537 
02538   // Okay, check to see if the same value occurs in the operand list twice.  If
02539   // so, delete one.  Since we sorted the list, these values are required to
02540   // be adjacent.
02541   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
02542     //  X smax Y smax Y  -->  X smax Y
02543     //  X smax Y         -->  X, if X is always greater than Y
02544     if (Ops[i] == Ops[i+1] ||
02545         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
02546       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
02547       --i; --e;
02548     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
02549       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
02550       --i; --e;
02551     }
02552 
02553   if (Ops.size() == 1) return Ops[0];
02554 
02555   assert(!Ops.empty() && "Reduced smax down to nothing!");
02556 
02557   // Okay, it looks like we really DO need an smax expr.  Check to see if we
02558   // already have one, otherwise create a new one.
02559   FoldingSetNodeID ID;
02560   ID.AddInteger(scSMaxExpr);
02561   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02562     ID.AddPointer(Ops[i]);
02563   void *IP = nullptr;
02564   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
02565   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
02566   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
02567   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
02568                                              O, Ops.size());
02569   UniqueSCEVs.InsertNode(S, IP);
02570   return S;
02571 }
02572 
02573 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
02574                                          const SCEV *RHS) {
02575   SmallVector<const SCEV *, 2> Ops;
02576   Ops.push_back(LHS);
02577   Ops.push_back(RHS);
02578   return getUMaxExpr(Ops);
02579 }
02580 
02581 const SCEV *
02582 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
02583   assert(!Ops.empty() && "Cannot get empty umax!");
02584   if (Ops.size() == 1) return Ops[0];
02585 #ifndef NDEBUG
02586   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
02587   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
02588     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
02589            "SCEVUMaxExpr operand types don't match!");
02590 #endif
02591 
02592   // Sort by complexity, this groups all similar expression types together.
02593   GroupByComplexity(Ops, LI);
02594 
02595   // If there are any constants, fold them together.
02596   unsigned Idx = 0;
02597   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
02598     ++Idx;
02599     assert(Idx < Ops.size());
02600     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
02601       // We found two constants, fold them together!
02602       ConstantInt *Fold = ConstantInt::get(getContext(),
02603                               APIntOps::umax(LHSC->getValue()->getValue(),
02604                                              RHSC->getValue()->getValue()));
02605       Ops[0] = getConstant(Fold);
02606       Ops.erase(Ops.begin()+1);  // Erase the folded element
02607       if (Ops.size() == 1) return Ops[0];
02608       LHSC = cast<SCEVConstant>(Ops[0]);
02609     }
02610 
02611     // If we are left with a constant minimum-int, strip it off.
02612     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
02613       Ops.erase(Ops.begin());
02614       --Idx;
02615     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
02616       // If we have an umax with a constant maximum-int, it will always be
02617       // maximum-int.
02618       return Ops[0];
02619     }
02620 
02621     if (Ops.size() == 1) return Ops[0];
02622   }
02623 
02624   // Find the first UMax
02625   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
02626     ++Idx;
02627 
02628   // Check to see if one of the operands is a UMax. If so, expand its operands
02629   // onto our operand list, and recurse to simplify.
02630   if (Idx < Ops.size()) {
02631     bool DeletedUMax = false;
02632     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
02633       Ops.erase(Ops.begin()+Idx);
02634       Ops.append(UMax->op_begin(), UMax->op_end());
02635       DeletedUMax = true;
02636     }
02637 
02638     if (DeletedUMax)
02639       return getUMaxExpr(Ops);
02640   }
02641 
02642   // Okay, check to see if the same value occurs in the operand list twice.  If
02643   // so, delete one.  Since we sorted the list, these values are required to
02644   // be adjacent.
02645   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
02646     //  X umax Y umax Y  -->  X umax Y
02647     //  X umax Y         -->  X, if X is always greater than Y
02648     if (Ops[i] == Ops[i+1] ||
02649         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
02650       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
02651       --i; --e;
02652     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
02653       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
02654       --i; --e;
02655     }
02656 
02657   if (Ops.size() == 1) return Ops[0];
02658 
02659   assert(!Ops.empty() && "Reduced umax down to nothing!");
02660 
02661   // Okay, it looks like we really DO need a umax expr.  Check to see if we
02662   // already have one, otherwise create a new one.
02663   FoldingSetNodeID ID;
02664   ID.AddInteger(scUMaxExpr);
02665   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
02666     ID.AddPointer(Ops[i]);
02667   void *IP = nullptr;
02668   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
02669   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
02670   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
02671   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
02672                                              O, Ops.size());
02673   UniqueSCEVs.InsertNode(S, IP);
02674   return S;
02675 }
02676 
02677 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
02678                                          const SCEV *RHS) {
02679   // ~smax(~x, ~y) == smin(x, y).
02680   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
02681 }
02682 
02683 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
02684                                          const SCEV *RHS) {
02685   // ~umax(~x, ~y) == umin(x, y)
02686   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
02687 }
02688 
02689 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
02690   // If we have DataLayout, we can bypass creating a target-independent
02691   // constant expression and then folding it back into a ConstantInt.
02692   // This is just a compile-time optimization.
02693   if (DL)
02694     return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
02695 
02696   Constant *C = ConstantExpr::getSizeOf(AllocTy);
02697   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
02698     if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
02699       C = Folded;
02700   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
02701   assert(Ty == IntTy && "Effective SCEV type doesn't match");
02702   return getTruncateOrZeroExtend(getSCEV(C), Ty);
02703 }
02704 
02705 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
02706                                              StructType *STy,
02707                                              unsigned FieldNo) {
02708   // If we have DataLayout, we can bypass creating a target-independent
02709   // constant expression and then folding it back into a ConstantInt.
02710   // This is just a compile-time optimization.
02711   if (DL) {
02712     return getConstant(IntTy,
02713                        DL->getStructLayout(STy)->getElementOffset(FieldNo));
02714   }
02715 
02716   Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
02717   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
02718     if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
02719       C = Folded;
02720 
02721   Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
02722   return getTruncateOrZeroExtend(getSCEV(C), Ty);
02723 }
02724 
02725 const SCEV *ScalarEvolution::getUnknown(Value *V) {
02726   // Don't attempt to do anything other than create a SCEVUnknown object
02727   // here.  createSCEV only calls getUnknown after checking for all other
02728   // interesting possibilities, and any other code that calls getUnknown
02729   // is doing so in order to hide a value from SCEV canonicalization.
02730 
02731   FoldingSetNodeID ID;
02732   ID.AddInteger(scUnknown);
02733   ID.AddPointer(V);
02734   void *IP = nullptr;
02735   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
02736     assert(cast<SCEVUnknown>(S)->getValue() == V &&
02737            "Stale SCEVUnknown in uniquing map!");
02738     return S;
02739   }
02740   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
02741                                             FirstUnknown);
02742   FirstUnknown = cast<SCEVUnknown>(S);
02743   UniqueSCEVs.InsertNode(S, IP);
02744   return S;
02745 }
02746 
02747 //===----------------------------------------------------------------------===//
02748 //            Basic SCEV Analysis and PHI Idiom Recognition Code
02749 //
02750 
02751 /// isSCEVable - Test if values of the given type are analyzable within
02752 /// the SCEV framework. This primarily includes integer types, and it
02753 /// can optionally include pointer types if the ScalarEvolution class
02754 /// has access to target-specific information.
02755 bool ScalarEvolution::isSCEVable(Type *Ty) const {
02756   // Integers and pointers are always SCEVable.
02757   return Ty->isIntegerTy() || Ty->isPointerTy();
02758 }
02759 
02760 /// getTypeSizeInBits - Return the size in bits of the specified type,
02761 /// for which isSCEVable must return true.
02762 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
02763   assert(isSCEVable(Ty) && "Type is not SCEVable!");
02764 
02765   // If we have a DataLayout, use it!
02766   if (DL)
02767     return DL->getTypeSizeInBits(Ty);
02768 
02769   // Integer types have fixed sizes.
02770   if (Ty->isIntegerTy())
02771     return Ty->getPrimitiveSizeInBits();
02772 
02773   // The only other support type is pointer. Without DataLayout, conservatively
02774   // assume pointers are 64-bit.
02775   assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
02776   return 64;
02777 }
02778 
02779 /// getEffectiveSCEVType - Return a type with the same bitwidth as
02780 /// the given type and which represents how SCEV will treat the given
02781 /// type, for which isSCEVable must return true. For pointer types,
02782 /// this is the pointer-sized integer type.
02783 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
02784   assert(isSCEVable(Ty) && "Type is not SCEVable!");
02785 
02786   if (Ty->isIntegerTy()) {
02787     return Ty;
02788   }
02789 
02790   // The only other support type is pointer.
02791   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
02792 
02793   if (DL)
02794     return DL->getIntPtrType(Ty);
02795 
02796   // Without DataLayout, conservatively assume pointers are 64-bit.
02797   return Type::getInt64Ty(getContext());
02798 }
02799 
02800 const SCEV *ScalarEvolution::getCouldNotCompute() {
02801   return &CouldNotCompute;
02802 }
02803 
02804 namespace {
02805   // Helper class working with SCEVTraversal to figure out if a SCEV contains
02806   // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
02807   // is set iff if find such SCEVUnknown.
02808   //
02809   struct FindInvalidSCEVUnknown {
02810     bool FindOne;
02811     FindInvalidSCEVUnknown() { FindOne = false; }
02812     bool follow(const SCEV *S) {
02813       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
02814       case scConstant:
02815         return false;
02816       case scUnknown:
02817         if (!cast<SCEVUnknown>(S)->getValue())
02818           FindOne = true;
02819         return false;
02820       default:
02821         return true;
02822       }
02823     }
02824     bool isDone() const { return FindOne; }
02825   };
02826 }
02827 
02828 bool ScalarEvolution::checkValidity(const SCEV *S) const {
02829   FindInvalidSCEVUnknown F;
02830   SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
02831   ST.visitAll(S);
02832 
02833   return !F.FindOne;
02834 }
02835 
02836 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
02837 /// expression and create a new one.
02838 const SCEV *ScalarEvolution::getSCEV(Value *V) {
02839   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
02840 
02841   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
02842   if (I != ValueExprMap.end()) {
02843     const SCEV *S = I->second;
02844     if (checkValidity(S))
02845       return S;
02846     else
02847       ValueExprMap.erase(I);
02848   }
02849   const SCEV *S = createSCEV(V);
02850 
02851   // The process of creating a SCEV for V may have caused other SCEVs
02852   // to have been created, so it's necessary to insert the new entry
02853   // from scratch, rather than trying to remember the insert position
02854   // above.
02855   ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
02856   return S;
02857 }
02858 
02859 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
02860 ///
02861 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
02862   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
02863     return getConstant(
02864                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
02865 
02866   Type *Ty = V->getType();
02867   Ty = getEffectiveSCEVType(Ty);
02868   return getMulExpr(V,
02869                   getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
02870 }
02871 
02872 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
02873 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
02874   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
02875     return getConstant(
02876                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
02877 
02878   Type *Ty = V->getType();
02879   Ty = getEffectiveSCEVType(Ty);
02880   const SCEV *AllOnes =
02881                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
02882   return getMinusSCEV(AllOnes, V);
02883 }
02884 
02885 /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
02886 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
02887                                           SCEV::NoWrapFlags Flags) {
02888   assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
02889 
02890   // Fast path: X - X --> 0.
02891   if (LHS == RHS)
02892     return getConstant(LHS->getType(), 0);
02893 
02894   // X - Y --> X + -Y
02895   return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
02896 }
02897 
02898 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
02899 /// input value to the specified type.  If the type must be extended, it is zero
02900 /// extended.
02901 const SCEV *
02902 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
02903   Type *SrcTy = V->getType();
02904   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02905          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02906          "Cannot truncate or zero extend with non-integer arguments!");
02907   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02908     return V;  // No conversion
02909   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
02910     return getTruncateExpr(V, Ty);
02911   return getZeroExtendExpr(V, Ty);
02912 }
02913 
02914 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
02915 /// input value to the specified type.  If the type must be extended, it is sign
02916 /// extended.
02917 const SCEV *
02918 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
02919                                          Type *Ty) {
02920   Type *SrcTy = V->getType();
02921   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02922          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02923          "Cannot truncate or zero extend with non-integer arguments!");
02924   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02925     return V;  // No conversion
02926   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
02927     return getTruncateExpr(V, Ty);
02928   return getSignExtendExpr(V, Ty);
02929 }
02930 
02931 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
02932 /// input value to the specified type.  If the type must be extended, it is zero
02933 /// extended.  The conversion must not be narrowing.
02934 const SCEV *
02935 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
02936   Type *SrcTy = V->getType();
02937   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02938          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02939          "Cannot noop or zero extend with non-integer arguments!");
02940   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
02941          "getNoopOrZeroExtend cannot truncate!");
02942   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02943     return V;  // No conversion
02944   return getZeroExtendExpr(V, Ty);
02945 }
02946 
02947 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
02948 /// input value to the specified type.  If the type must be extended, it is sign
02949 /// extended.  The conversion must not be narrowing.
02950 const SCEV *
02951 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
02952   Type *SrcTy = V->getType();
02953   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02954          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02955          "Cannot noop or sign extend with non-integer arguments!");
02956   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
02957          "getNoopOrSignExtend cannot truncate!");
02958   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02959     return V;  // No conversion
02960   return getSignExtendExpr(V, Ty);
02961 }
02962 
02963 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
02964 /// the input value to the specified type. If the type must be extended,
02965 /// it is extended with unspecified bits. The conversion must not be
02966 /// narrowing.
02967 const SCEV *
02968 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
02969   Type *SrcTy = V->getType();
02970   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02971          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02972          "Cannot noop or any extend with non-integer arguments!");
02973   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
02974          "getNoopOrAnyExtend cannot truncate!");
02975   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02976     return V;  // No conversion
02977   return getAnyExtendExpr(V, Ty);
02978 }
02979 
02980 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
02981 /// input value to the specified type.  The conversion must not be widening.
02982 const SCEV *
02983 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
02984   Type *SrcTy = V->getType();
02985   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
02986          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
02987          "Cannot truncate or noop with non-integer arguments!");
02988   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
02989          "getTruncateOrNoop cannot extend!");
02990   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
02991     return V;  // No conversion
02992   return getTruncateExpr(V, Ty);
02993 }
02994 
02995 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
02996 /// the types using zero-extension, and then perform a umax operation
02997 /// with them.
02998 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
02999                                                         const SCEV *RHS) {
03000   const SCEV *PromotedLHS = LHS;
03001   const SCEV *PromotedRHS = RHS;
03002 
03003   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
03004     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
03005   else
03006     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
03007 
03008   return getUMaxExpr(PromotedLHS, PromotedRHS);
03009 }
03010 
03011 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
03012 /// the types using zero-extension, and then perform a umin operation
03013 /// with them.
03014 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
03015                                                         const SCEV *RHS) {
03016   const SCEV *PromotedLHS = LHS;
03017   const SCEV *PromotedRHS = RHS;
03018 
03019   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
03020     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
03021   else
03022     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
03023 
03024   return getUMinExpr(PromotedLHS, PromotedRHS);
03025 }
03026 
03027 /// getPointerBase - Transitively follow the chain of pointer-type operands
03028 /// until reaching a SCEV that does not have a single pointer operand. This
03029 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
03030 /// but corner cases do exist.
03031 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
03032   // A pointer operand may evaluate to a nonpointer expression, such as null.
03033   if (!V->getType()->isPointerTy())
03034     return V;
03035 
03036   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
03037     return getPointerBase(Cast->getOperand());
03038   }
03039   else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
03040     const SCEV *PtrOp = nullptr;
03041     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
03042          I != E; ++I) {
03043       if ((*I)->getType()->isPointerTy()) {
03044         // Cannot find the base of an expression with multiple pointer operands.
03045         if (PtrOp)
03046           return V;
03047         PtrOp = *I;
03048       }
03049     }
03050     if (!PtrOp)
03051       return V;
03052     return getPointerBase(PtrOp);
03053   }
03054   return V;
03055 }
03056 
03057 /// PushDefUseChildren - Push users of the given Instruction
03058 /// onto the given Worklist.
03059 static void
03060 PushDefUseChildren(Instruction *I,
03061                    SmallVectorImpl<Instruction *> &Worklist) {
03062   // Push the def-use children onto the Worklist stack.
03063   for (User *U : I->users())
03064     Worklist.push_back(cast<Instruction>(U));
03065 }
03066 
03067 /// ForgetSymbolicValue - This looks up computed SCEV values for all
03068 /// instructions that depend on the given instruction and removes them from
03069 /// the ValueExprMapType map if they reference SymName. This is used during PHI
03070 /// resolution.
03071 void
03072 ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
03073   SmallVector<Instruction *, 16> Worklist;
03074   PushDefUseChildren(PN, Worklist);
03075 
03076   SmallPtrSet<Instruction *, 8> Visited;
03077   Visited.insert(PN);
03078   while (!Worklist.empty()) {
03079     Instruction *I = Worklist.pop_back_val();
03080     if (!Visited.insert(I)) continue;
03081 
03082     ValueExprMapType::iterator It =
03083       ValueExprMap.find_as(static_cast<Value *>(I));
03084     if (It != ValueExprMap.end()) {
03085       const SCEV *Old = It->second;
03086 
03087       // Short-circuit the def-use traversal if the symbolic name
03088       // ceases to appear in expressions.
03089       if (Old != SymName && !hasOperand(Old, SymName))
03090         continue;
03091 
03092       // SCEVUnknown for a PHI either means that it has an unrecognized
03093       // structure, it's a PHI that's in the progress of being computed
03094       // by createNodeForPHI, or it's a single-value PHI. In the first case,
03095       // additional loop trip count information isn't going to change anything.
03096       // In the second case, createNodeForPHI will perform the necessary
03097       // updates on its own when it gets to that point. In the third, we do
03098       // want to forget the SCEVUnknown.
03099       if (!isa<PHINode>(I) ||
03100           !isa<SCEVUnknown>(Old) ||
03101           (I != PN && Old == SymName)) {
03102         forgetMemoizedResults(Old);
03103         ValueExprMap.erase(It);
03104       }
03105     }
03106 
03107     PushDefUseChildren(I, Worklist);
03108   }
03109 }
03110 
03111 /// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
03112 /// a loop header, making it a potential recurrence, or it doesn't.
03113 ///
03114 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
03115   if (const Loop *L = LI->getLoopFor(PN->getParent()))
03116     if (L->getHeader() == PN->getParent()) {
03117       // The loop may have multiple entrances or multiple exits; we can analyze
03118       // this phi as an addrec if it has a unique entry value and a unique
03119       // backedge value.
03120       Value *BEValueV = nullptr, *StartValueV = nullptr;
03121       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
03122         Value *V = PN->getIncomingValue(i);
03123         if (L->contains(PN->getIncomingBlock(i))) {
03124           if (!BEValueV) {
03125             BEValueV = V;
03126           } else if (BEValueV != V) {
03127             BEValueV = nullptr;
03128             break;
03129           }
03130         } else if (!StartValueV) {
03131           StartValueV = V;
03132         } else if (StartValueV != V) {
03133           StartValueV = nullptr;
03134           break;
03135         }
03136       }
03137       if (BEValueV && StartValueV) {
03138         // While we are analyzing this PHI node, handle its value symbolically.
03139         const SCEV *SymbolicName = getUnknown(PN);
03140         assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
03141                "PHI node already processed?");
03142         ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
03143 
03144         // Using this symbolic name for the PHI, analyze the value coming around
03145         // the back-edge.
03146         const SCEV *BEValue = getSCEV(BEValueV);
03147 
03148         // NOTE: If BEValue is loop invariant, we know that the PHI node just
03149         // has a special value for the first iteration of the loop.
03150 
03151         // If the value coming around the backedge is an add with the symbolic
03152         // value we just inserted, then we found a simple induction variable!
03153         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
03154           // If there is a single occurrence of the symbolic value, replace it
03155           // with a recurrence.
03156           unsigned FoundIndex = Add->getNumOperands();
03157           for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
03158             if (Add->getOperand(i) == SymbolicName)
03159               if (FoundIndex == e) {
03160                 FoundIndex = i;
03161                 break;
03162               }
03163 
03164           if (FoundIndex != Add->getNumOperands()) {
03165             // Create an add with everything but the specified operand.
03166             SmallVector<const SCEV *, 8> Ops;
03167             for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
03168               if (i != FoundIndex)
03169                 Ops.push_back(Add->getOperand(i));
03170             const SCEV *Accum = getAddExpr(Ops);
03171 
03172             // This is not a valid addrec if the step amount is varying each
03173             // loop iteration, but is not itself an addrec in this loop.
03174             if (isLoopInvariant(Accum, L) ||
03175                 (isa<SCEVAddRecExpr>(Accum) &&
03176                  cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
03177               SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
03178 
03179               // If the increment doesn't overflow, then neither the addrec nor
03180               // the post-increment will overflow.
03181               if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
03182                 if (OBO->hasNoUnsignedWrap())
03183                   Flags = setFlags(Flags, SCEV::FlagNUW);
03184                 if (OBO->hasNoSignedWrap())
03185                   Flags = setFlags(Flags, SCEV::FlagNSW);
03186               } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
03187                 // If the increment is an inbounds GEP, then we know the address
03188                 // space cannot be wrapped around. We cannot make any guarantee
03189                 // about signed or unsigned overflow because pointers are
03190                 // unsigned but we may have a negative index from the base
03191                 // pointer. We can guarantee that no unsigned wrap occurs if the
03192                 // indices form a positive value.
03193                 if (GEP->isInBounds()) {
03194                   Flags = setFlags(Flags, SCEV::FlagNW);
03195 
03196                   const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
03197                   if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
03198                     Flags = setFlags(Flags, SCEV::FlagNUW);
03199                 }
03200               } else if (const SubOperator *OBO =
03201                            dyn_cast<SubOperator>(BEValueV)) {
03202                 if (OBO->hasNoUnsignedWrap())
03203                   Flags = setFlags(Flags, SCEV::FlagNUW);
03204                 if (OBO->hasNoSignedWrap())
03205                   Flags = setFlags(Flags, SCEV::FlagNSW);
03206               }
03207 
03208               const SCEV *StartVal = getSCEV(StartValueV);
03209               const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
03210 
03211               // Since the no-wrap flags are on the increment, they apply to the
03212               // post-incremented value as well.
03213               if (isLoopInvariant(Accum, L))
03214                 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
03215                                     Accum, L, Flags);
03216 
03217               // Okay, for the entire analysis of this edge we assumed the PHI
03218               // to be symbolic.  We now need to go back and purge all of the
03219               // entries for the scalars that use the symbolic expression.
03220               ForgetSymbolicName(PN, SymbolicName);
03221               ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
03222               return PHISCEV;
03223             }
03224           }
03225         } else if (const SCEVAddRecExpr *AddRec =
03226                      dyn_cast<SCEVAddRecExpr>(BEValue)) {
03227           // Otherwise, this could be a loop like this:
03228           //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
03229           // In this case, j = {1,+,1}  and BEValue is j.
03230           // Because the other in-value of i (0) fits the evolution of BEValue
03231           // i really is an addrec evolution.
03232           if (AddRec->getLoop() == L && AddRec->isAffine()) {
03233             const SCEV *StartVal = getSCEV(StartValueV);
03234 
03235             // If StartVal = j.start - j.stride, we can use StartVal as the
03236             // initial step of the addrec evolution.
03237             if (StartVal == getMinusSCEV(AddRec->getOperand(0),
03238                                          AddRec->getOperand(1))) {
03239               // FIXME: For constant StartVal, we should be able to infer
03240               // no-wrap flags.
03241               const SCEV *PHISCEV =
03242                 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
03243                               SCEV::FlagAnyWrap);
03244 
03245               // Okay, for the entire analysis of this edge we assumed the PHI
03246               // to be symbolic.  We now need to go back and purge all of the
03247               // entries for the scalars that use the symbolic expression.
03248               ForgetSymbolicName(PN, SymbolicName);
03249               ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
03250               return PHISCEV;
03251             }
03252           }
03253         }
03254       }
03255     }
03256 
03257   // If the PHI has a single incoming value, follow that value, unless the
03258   // PHI's incoming blocks are in a different loop, in which case doing so
03259   // risks breaking LCSSA form. Instcombine would normally zap these, but
03260   // it doesn't have DominatorTree information, so it may miss cases.
03261   if (Value *V = SimplifyInstruction(PN, DL, TLI, DT))
03262     if (LI->replacementPreservesLCSSAForm(PN, V))
03263       return getSCEV(V);
03264 
03265   // If it's not a loop phi, we can't handle it yet.
03266   return getUnknown(PN);
03267 }
03268 
03269 /// createNodeForGEP - Expand GEP instructions into add and multiply
03270 /// operations. This allows them to be analyzed by regular SCEV code.
03271 ///
03272 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
03273   Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
03274   Value *Base = GEP->getOperand(0);
03275   // Don't attempt to analyze GEPs over unsized objects.
03276   if (!Base->getType()->getPointerElementType()->isSized())
03277     return getUnknown(GEP);
03278 
03279   // Don't blindly transfer the inbounds flag from the GEP instruction to the
03280   // Add expression, because the Instruction may be guarded by control flow
03281   // and the no-overflow bits may not be valid for the expression in any
03282   // context.
03283   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
03284 
03285   const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
03286   gep_type_iterator GTI = gep_type_begin(GEP);
03287   for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
03288                                       E = GEP->op_end();
03289        I != E; ++I) {
03290     Value *Index = *I;
03291     // Compute the (potentially symbolic) offset in bytes for this index.
03292     if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
03293       // For a struct, add the member offset.
03294       unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
03295       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
03296 
03297       // Add the field offset to the running total offset.
03298       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
03299     } else {
03300       // For an array, add the element offset, explicitly scaled.
03301       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
03302       const SCEV *IndexS = getSCEV(Index);
03303       // Getelementptr indices are signed.
03304       IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
03305 
03306       // Multiply the index by the element size to compute the element offset.
03307       const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
03308 
03309       // Add the element offset to the running total offset.
03310       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
03311     }
03312   }
03313 
03314   // Get the SCEV for the GEP base.
03315   const SCEV *BaseS = getSCEV(Base);
03316 
03317   // Add the total offset from all the GEP indices to the base.
03318   return getAddExpr(BaseS, TotalOffset, Wrap);
03319 }
03320 
03321 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
03322 /// guaranteed to end in (at every loop iteration).  It is, at the same time,
03323 /// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
03324 /// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
03325 uint32_t
03326 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
03327   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
03328     return C->getValue()->getValue().countTrailingZeros();
03329 
03330   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
03331     return std::min(GetMinTrailingZeros(T->getOperand()),
03332                     (uint32_t)getTypeSizeInBits(T->getType()));
03333 
03334   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
03335     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
03336     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
03337              getTypeSizeInBits(E->getType()) : OpRes;
03338   }
03339 
03340   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
03341     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
03342     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
03343              getTypeSizeInBits(E->getType()) : OpRes;
03344   }
03345 
03346   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
03347     // The result is the min of all operands results.
03348     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
03349     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
03350       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
03351     return MinOpRes;
03352   }
03353 
03354   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
03355     // The result is the sum of all operands results.
03356     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
03357     uint32_t BitWidth = getTypeSizeInBits(M->getType());
03358     for (unsigned i = 1, e = M->getNumOperands();
03359          SumOpRes != BitWidth && i != e; ++i)
03360       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
03361                           BitWidth);
03362     return SumOpRes;
03363   }
03364 
03365   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
03366     // The result is the min of all operands results.
03367     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
03368     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
03369       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
03370     return MinOpRes;
03371   }
03372 
03373   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
03374     // The result is the min of all operands results.
03375     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
03376     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
03377       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
03378     return MinOpRes;
03379   }
03380 
03381   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
03382     // The result is the min of all operands results.
03383     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
03384     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
03385       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
03386     return MinOpRes;
03387   }
03388 
03389   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
03390     // For a SCEVUnknown, ask ValueTracking.
03391     unsigned BitWidth = getTypeSizeInBits(U->getType());
03392     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
03393     computeKnownBits(U->getValue(), Zeros, Ones);
03394     return Zeros.countTrailingOnes();
03395   }
03396 
03397   // SCEVUDivExpr
03398   return 0;
03399 }
03400 
03401 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
03402 ///
03403 ConstantRange
03404 ScalarEvolution::getUnsignedRange(const SCEV *S) {
03405   // See if we've computed this range already.
03406   DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
03407   if (I != UnsignedRanges.end())
03408     return I->second;
03409 
03410   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
03411     return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
03412 
03413   unsigned BitWidth = getTypeSizeInBits(S->getType());
03414   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
03415 
03416   // If the value has known zeros, the maximum unsigned value will have those
03417   // known zeros as well.
03418   uint32_t TZ = GetMinTrailingZeros(S);
03419   if (TZ != 0)
03420     ConservativeResult =
03421       ConstantRange(APInt::getMinValue(BitWidth),
03422                     APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
03423 
03424   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
03425     ConstantRange X = getUnsignedRange(Add->getOperand(0));
03426     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
03427       X = X.add(getUnsignedRange(Add->getOperand(i)));
03428     return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
03429   }
03430 
03431   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
03432     ConstantRange X = getUnsignedRange(Mul->getOperand(0));
03433     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
03434       X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
03435     return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
03436   }
03437 
03438   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
03439     ConstantRange X = getUnsignedRange(SMax->getOperand(0));
03440     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
03441       X = X.smax(getUnsignedRange(SMax->getOperand(i)));
03442     return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
03443   }
03444 
03445   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
03446     ConstantRange X = getUnsignedRange(UMax->getOperand(0));
03447     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
03448       X = X.umax(getUnsignedRange(UMax->getOperand(i)));
03449     return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
03450   }
03451 
03452   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
03453     ConstantRange X = getUnsignedRange(UDiv->getLHS());
03454     ConstantRange Y = getUnsignedRange(UDiv->getRHS());
03455     return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
03456   }
03457 
03458   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
03459     ConstantRange X = getUnsignedRange(ZExt->getOperand());
03460     return setUnsignedRange(ZExt,
03461       ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
03462   }
03463 
03464   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
03465     ConstantRange X = getUnsignedRange(SExt->getOperand());
03466     return setUnsignedRange(SExt,
03467       ConservativeResult.intersectWith(X.signExtend(BitWidth)));
03468   }
03469 
03470   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
03471     ConstantRange X = getUnsignedRange(Trunc->getOperand());
03472     return setUnsignedRange(Trunc,
03473       ConservativeResult.intersectWith(X.truncate(BitWidth)));
03474   }
03475 
03476   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
03477     // If there's no unsigned wrap, the value will never be less than its
03478     // initial value.
03479     if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
03480       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
03481         if (!C->getValue()->isZero())
03482           ConservativeResult =
03483             ConservativeResult.intersectWith(
03484               ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
03485 
03486     // TODO: non-affine addrec
03487     if (AddRec->isAffine()) {
03488       Type *Ty = AddRec->getType();
03489       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
03490       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
03491           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
03492         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
03493 
03494         const SCEV *Start = AddRec->getStart();
03495         const SCEV *Step = AddRec->getStepRecurrence(*this);
03496 
03497         ConstantRange StartRange = getUnsignedRange(Start);
03498         ConstantRange StepRange = getSignedRange(Step);
03499         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
03500         ConstantRange EndRange =
03501           StartRange.add(MaxBECountRange.multiply(StepRange));
03502 
03503         // Check for overflow. This must be done with ConstantRange arithmetic
03504         // because we could be called from within the ScalarEvolution overflow
03505         // checking code.
03506         ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
03507         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
03508         ConstantRange ExtMaxBECountRange =
03509           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
03510         ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
03511         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
03512             ExtEndRange)
03513           return setUnsignedRange(AddRec, ConservativeResult);
03514 
03515         APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
03516                                    EndRange.getUnsignedMin());
03517         APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
03518                                    EndRange.getUnsignedMax());
03519         if (Min.isMinValue() && Max.isMaxValue())
03520           return setUnsignedRange(AddRec, ConservativeResult);
03521         return setUnsignedRange(AddRec,
03522           ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
03523       }
03524     }
03525 
03526     return setUnsignedRange(AddRec, ConservativeResult);
03527   }
03528 
03529   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
03530     // For a SCEVUnknown, ask ValueTracking.
03531     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
03532     computeKnownBits(U->getValue(), Zeros, Ones, DL);
03533     if (Ones == ~Zeros + 1)
03534       return setUnsignedRange(U, ConservativeResult);
03535     return setUnsignedRange(U,
03536       ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
03537   }
03538 
03539   return setUnsignedRange(S, ConservativeResult);
03540 }
03541 
03542 /// getSignedRange - Determine the signed range for a particular SCEV.
03543 ///
03544 ConstantRange
03545 ScalarEvolution::getSignedRange(const SCEV *S) {
03546   // See if we've computed this range already.
03547   DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
03548   if (I != SignedRanges.end())
03549     return I->second;
03550 
03551   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
03552     return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
03553 
03554   unsigned BitWidth = getTypeSizeInBits(S->getType());
03555   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
03556 
03557   // If the value has known zeros, the maximum signed value will have those
03558   // known zeros as well.
03559   uint32_t TZ = GetMinTrailingZeros(S);
03560   if (TZ != 0)
03561     ConservativeResult =
03562       ConstantRange(APInt::getSignedMinValue(BitWidth),
03563                     APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
03564 
03565   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
03566     ConstantRange X = getSignedRange(Add->getOperand(0));
03567     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
03568       X = X.add(getSignedRange(Add->getOperand(i)));
03569     return setSignedRange(Add, ConservativeResult.intersectWith(X));
03570   }
03571 
03572   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
03573     ConstantRange X = getSignedRange(Mul->getOperand(0));
03574     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
03575       X = X.multiply(getSignedRange(Mul->getOperand(i)));
03576     return setSignedRange(Mul, ConservativeResult.intersectWith(X));
03577   }
03578 
03579   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
03580     ConstantRange X = getSignedRange(SMax->getOperand(0));
03581     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
03582       X = X.smax(getSignedRange(SMax->getOperand(i)));
03583     return setSignedRange(SMax, ConservativeResult.intersectWith(X));
03584   }
03585 
03586   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
03587     ConstantRange X = getSignedRange(UMax->getOperand(0));
03588     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
03589       X = X.umax(getSignedRange(UMax->getOperand(i)));
03590     return setSignedRange(UMax, ConservativeResult.intersectWith(X));
03591   }
03592 
03593   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
03594     ConstantRange X = getSignedRange(UDiv->getLHS());
03595     ConstantRange Y = getSignedRange(UDiv->getRHS());
03596     return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
03597   }
03598 
03599   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
03600     ConstantRange X = getSignedRange(ZExt->getOperand());
03601     return setSignedRange(ZExt,
03602       ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
03603   }
03604 
03605   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
03606     ConstantRange X = getSignedRange(SExt->getOperand());
03607     return setSignedRange(SExt,
03608       ConservativeResult.intersectWith(X.signExtend(BitWidth)));
03609   }
03610 
03611   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
03612     ConstantRange X = getSignedRange(Trunc->getOperand());
03613     return setSignedRange(Trunc,
03614       ConservativeResult.intersectWith(X.truncate(BitWidth)));
03615   }
03616 
03617   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
03618     // If there's no signed wrap, and all the operands have the same sign or
03619     // zero, the value won't ever change sign.
03620     if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
03621       bool AllNonNeg = true;
03622       bool AllNonPos = true;
03623       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
03624         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
03625         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
03626       }
03627       if (AllNonNeg)
03628         ConservativeResult = ConservativeResult.intersectWith(
03629           ConstantRange(APInt(BitWidth, 0),
03630                         APInt::getSignedMinValue(BitWidth)));
03631       else if (AllNonPos)
03632         ConservativeResult = ConservativeResult.intersectWith(
03633           ConstantRange(APInt::getSignedMinValue(BitWidth),
03634                         APInt(BitWidth, 1)));
03635     }
03636 
03637     // TODO: non-affine addrec
03638     if (AddRec->isAffine()) {
03639       Type *Ty = AddRec->getType();
03640       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
03641       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
03642           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
03643         MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
03644 
03645         const SCEV *Start = AddRec->getStart();
03646         const SCEV *Step = AddRec->getStepRecurrence(*this);
03647 
03648         ConstantRange StartRange = getSignedRange(Start);
03649         ConstantRange StepRange = getSignedRange(Step);
03650         ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
03651         ConstantRange EndRange =
03652           StartRange.add(MaxBECountRange.multiply(StepRange));
03653 
03654         // Check for overflow. This must be done with ConstantRange arithmetic
03655         // because we could be called from within the ScalarEvolution overflow
03656         // checking code.
03657         ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
03658         ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
03659         ConstantRange ExtMaxBECountRange =
03660           MaxBECountRange.zextOrTrunc(BitWidth*2+1);
03661         ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
03662         if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
03663             ExtEndRange)
03664           return setSignedRange(AddRec, ConservativeResult);
03665 
03666         APInt Min = APIntOps::smin(StartRange.getSignedMin(),
03667                                    EndRange.getSignedMin());
03668         APInt Max = APIntOps::smax(StartRange.getSignedMax(),
03669                                    EndRange.getSignedMax());
03670         if (Min.isMinSignedValue() && Max.isMaxSignedValue())
03671           return setSignedRange(AddRec, ConservativeResult);
03672         return setSignedRange(AddRec,
03673           ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
03674       }
03675     }
03676 
03677     return setSignedRange(AddRec, ConservativeResult);
03678   }
03679 
03680   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
03681     // For a SCEVUnknown, ask ValueTracking.
03682     if (!U->getValue()->getType()->isIntegerTy() && !DL)
03683       return setSignedRange(U, ConservativeResult);
03684     unsigned NS = ComputeNumSignBits(U->getValue(), DL);
03685     if (NS <= 1)
03686       return setSignedRange(U, ConservativeResult);
03687     return setSignedRange(U, ConservativeResult.intersectWith(
03688       ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
03689                     APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
03690   }
03691 
03692   return setSignedRange(S, ConservativeResult);
03693 }
03694 
03695 /// createSCEV - We know that there is no SCEV for the specified value.
03696 /// Analyze the expression.
03697 ///
03698 const SCEV *ScalarEvolution::createSCEV(Value *V) {
03699   if (!isSCEVable(V->getType()))
03700     return getUnknown(V);
03701 
03702   unsigned Opcode = Instruction::UserOp1;
03703   if (Instruction *I = dyn_cast<Instruction>(V)) {
03704     Opcode = I->getOpcode();
03705 
03706     // Don't attempt to analyze instructions in blocks that aren't
03707     // reachable. Such instructions don't matter, and they aren't required
03708     // to obey basic rules for definitions dominating uses which this
03709     // analysis depends on.
03710     if (!DT->isReachableFromEntry(I->getParent()))
03711       return getUnknown(V);
03712   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
03713     Opcode = CE->getOpcode();
03714   else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
03715     return getConstant(CI);
03716   else if (isa<ConstantPointerNull>(V))
03717     return getConstant(V->getType(), 0);
03718   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
03719     return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
03720   else
03721     return getUnknown(V);
03722 
03723   Operator *U = cast<Operator>(V);
03724   switch (Opcode) {
03725   case Instruction::Add: {
03726     // The simple thing to do would be to just call getSCEV on both operands
03727     // and call getAddExpr with the result. However if we're looking at a
03728     // bunch of things all added together, this can be quite inefficient,
03729     // because it leads to N-1 getAddExpr calls for N ultimate operands.
03730     // Instead, gather up all the operands and make a single getAddExpr call.
03731     // LLVM IR canonical form means we need only traverse the left operands.
03732     //
03733     // Don't apply this instruction's NSW or NUW flags to the new
03734     // expression. The instruction may be guarded by control flow that the
03735     // no-wrap behavior depends on. Non-control-equivalent instructions can be
03736     // mapped to the same SCEV expression, and it would be incorrect to transfer
03737     // NSW/NUW semantics to those operations.
03738     SmallVector<const SCEV *, 4> AddOps;
03739     AddOps.push_back(getSCEV(U->getOperand(1)));
03740     for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
03741       unsigned Opcode = Op->getValueID() - Value::InstructionVal;
03742       if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
03743         break;
03744       U = cast<Operator>(Op);
03745       const SCEV *Op1 = getSCEV(U->getOperand(1));
03746       if (Opcode == Instruction::Sub)
03747         AddOps.push_back(getNegativeSCEV(Op1));
03748       else
03749         AddOps.push_back(Op1);
03750     }
03751     AddOps.push_back(getSCEV(U->getOperand(0)));
03752     return getAddExpr(AddOps);
03753   }
03754   case Instruction::Mul: {
03755     // Don't transfer NSW/NUW for the same reason as AddExpr.
03756     SmallVector<const SCEV *, 4> MulOps;
03757     MulOps.push_back(getSCEV(U->getOperand(1)));
03758     for (Value *Op = U->getOperand(0);
03759          Op->getValueID() == Instruction::Mul + Value::InstructionVal;
03760          Op = U->getOperand(0)) {
03761       U = cast<Operator>(Op);
03762       MulOps.push_back(getSCEV(U->getOperand(1)));
03763     }
03764     MulOps.push_back(getSCEV(U->getOperand(0)));
03765     return getMulExpr(MulOps);
03766   }
03767   case Instruction::UDiv:
03768     return getUDivExpr(getSCEV(U->getOperand(0)),
03769                        getSCEV(U->getOperand(1)));
03770   case Instruction::Sub:
03771     return getMinusSCEV(getSCEV(U->getOperand(0)),
03772                         getSCEV(U->getOperand(1)));
03773   case Instruction::And:
03774     // For an expression like x&255 that merely masks off the high bits,
03775     // use zext(trunc(x)) as the SCEV expression.
03776     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
03777       if (CI->isNullValue())
03778         return getSCEV(U->getOperand(1));
03779       if (CI->isAllOnesValue())
03780         return getSCEV(U->getOperand(0));
03781       const APInt &A = CI->getValue();
03782 
03783       // Instcombine's ShrinkDemandedConstant may strip bits out of
03784       // constants, obscuring what would otherwise be a low-bits mask.
03785       // Use computeKnownBits to compute what ShrinkDemandedConstant
03786       // knew about to reconstruct a low-bits mask value.
03787       unsigned LZ = A.countLeadingZeros();
03788       unsigned TZ = A.countTrailingZeros();
03789       unsigned BitWidth = A.getBitWidth();
03790       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
03791       computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL);
03792 
03793       APInt EffectiveMask =
03794           APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
03795       if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
03796         const SCEV *MulCount = getConstant(
03797             ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
03798         return getMulExpr(
03799             getZeroExtendExpr(
03800                 getTruncateExpr(
03801                     getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
03802                     IntegerType::get(getContext(), BitWidth - LZ - TZ)),
03803                 U->getType()),
03804             MulCount);
03805       }
03806     }
03807     break;
03808 
03809   case Instruction::Or:
03810     // If the RHS of the Or is a constant, we may have something like:
03811     // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
03812     // optimizations will transparently handle this case.
03813     //
03814     // In order for this transformation to be safe, the LHS must be of the
03815     // form X*(2^n) and the Or constant must be less than 2^n.
03816     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
03817       const SCEV *LHS = getSCEV(U->getOperand(0));
03818       const APInt &CIVal = CI->getValue();
03819       if (GetMinTrailingZeros(LHS) >=
03820           (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
03821         // Build a plain add SCEV.
03822         const SCEV *S = getAddExpr(LHS, getSCEV(CI));
03823         // If the LHS of the add was an addrec and it has no-wrap flags,
03824         // transfer the no-wrap flags, since an or won't introduce a wrap.
03825         if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
03826           const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
03827           const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
03828             OldAR->getNoWrapFlags());
03829         }
03830         return S;
03831       }
03832     }
03833     break;
03834   case Instruction::Xor:
03835     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
03836       // If the RHS of the xor is a signbit, then this is just an add.
03837       // Instcombine turns add of signbit into xor as a strength reduction step.
03838       if (CI->getValue().isSignBit())
03839         return getAddExpr(getSCEV(U->getOperand(0)),
03840                           getSCEV(U->getOperand(1)));
03841 
03842       // If the RHS of xor is -1, then this is a not operation.
03843       if (CI->isAllOnesValue())
03844         return getNotSCEV(getSCEV(U->getOperand(0)));
03845 
03846       // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
03847       // This is a variant of the check for xor with -1, and it handles
03848       // the case where instcombine has trimmed non-demanded bits out
03849       // of an xor with -1.
03850       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
03851         if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
03852           if (BO->getOpcode() == Instruction::And &&
03853               LCI->getValue() == CI->getValue())
03854             if (const SCEVZeroExtendExpr *Z =
03855                   dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
03856               Type *UTy = U->getType();
03857               const SCEV *Z0 = Z->getOperand();
03858               Type *Z0Ty = Z0->getType();
03859               unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
03860 
03861               // If C is a low-bits mask, the zero extend is serving to
03862               // mask off the high bits. Complement the operand and
03863               // re-apply the zext.
03864               if (APIntOps::isMask(Z0TySize, CI->getValue()))
03865                 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
03866 
03867               // If C is a single bit, it may be in the sign-bit position
03868               // before the zero-extend. In this case, represent the xor
03869               // using an add, which is equivalent, and re-apply the zext.
03870               APInt Trunc = CI->getValue().trunc(Z0TySize);
03871               if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
03872                   Trunc.isSignBit())
03873                 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
03874                                          UTy);
03875             }
03876     }
03877     break;
03878 
03879   case Instruction::Shl:
03880     // Turn shift left of a constant amount into a multiply.
03881     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
03882       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
03883 
03884       // If the shift count is not less than the bitwidth, the result of
03885       // the shift is undefined. Don't try to analyze it, because the
03886       // resolution chosen here may differ from the resolution chosen in
03887       // other parts of the compiler.
03888       if (SA->getValue().uge(BitWidth))
03889         break;
03890 
03891       Constant *X = ConstantInt::get(getContext(),
03892         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
03893       return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
03894     }
03895     break;
03896 
03897   case Instruction::LShr:
03898     // Turn logical shift right of a constant into a unsigned divide.
03899     if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
03900       uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
03901 
03902       // If the shift count is not less than the bitwidth, the result of
03903       // the shift is undefined. Don't try to analyze it, because the
03904       // resolution chosen here may differ from the resolution chosen in
03905       // other parts of the compiler.
03906       if (SA->getValue().uge(BitWidth))
03907         break;
03908 
03909       Constant *X = ConstantInt::get(getContext(),
03910         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
03911       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
03912     }
03913     break;
03914 
03915   case Instruction::AShr:
03916     // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
03917     if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
03918       if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
03919         if (L->getOpcode() == Instruction::Shl &&
03920             L->getOperand(1) == U->getOperand(1)) {
03921           uint64_t BitWidth = getTypeSizeInBits(U->getType());
03922 
03923           // If the shift count is not less than the bitwidth, the result of
03924           // the shift is undefined. Don't try to analyze it, because the
03925           // resolution chosen here may differ from the resolution chosen in
03926           // other parts of the compiler.
03927           if (CI->getValue().uge(BitWidth))
03928             break;
03929 
03930           uint64_t Amt = BitWidth - CI->getZExtValue();
03931           if (Amt == BitWidth)
03932             return getSCEV(L->getOperand(0));       // shift by zero --> noop
03933           return
03934             getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
03935                                               IntegerType::get(getContext(),
03936                                                                Amt)),
03937                               U->getType());
03938         }
03939     break;
03940 
03941   case Instruction::Trunc:
03942     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
03943 
03944   case Instruction::ZExt:
03945     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
03946 
03947   case Instruction::SExt:
03948     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
03949 
03950   case Instruction::BitCast:
03951     // BitCasts are no-op casts so we just eliminate the cast.
03952     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
03953       return getSCEV(U->getOperand(0));
03954     break;
03955 
03956   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
03957   // lead to pointer expressions which cannot safely be expanded to GEPs,
03958   // because ScalarEvolution doesn't respect the GEP aliasing rules when
03959   // simplifying integer expressions.
03960 
03961   case Instruction::GetElementPtr:
03962     return createNodeForGEP(cast<GEPOperator>(U));
03963 
03964   case Instruction::PHI:
03965     return createNodeForPHI(cast<PHINode>(U));
03966 
03967   case Instruction::Select:
03968     // This could be a smax or umax that was lowered earlier.
03969     // Try to recover it.
03970     if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
03971       Value *LHS = ICI->getOperand(0);
03972       Value *RHS = ICI->getOperand(1);
03973       switch (ICI->getPredicate()) {
03974       case ICmpInst::ICMP_SLT:
03975       case ICmpInst::ICMP_SLE:
03976         std::swap(LHS, RHS);
03977         // fall through
03978       case ICmpInst::ICMP_SGT:
03979       case ICmpInst::ICMP_SGE:
03980         // a >s b ? a+x : b+x  ->  smax(a, b)+x
03981         // a >s b ? b+x : a+x  ->  smin(a, b)+x
03982         if (LHS->getType() == U->getType()) {
03983           const SCEV *LS = getSCEV(LHS);
03984           const SCEV *RS = getSCEV(RHS);
03985           const SCEV *LA = getSCEV(U->getOperand(1));
03986           const SCEV *RA = getSCEV(U->getOperand(2));
03987           const SCEV *LDiff = getMinusSCEV(LA, LS);
03988           const SCEV *RDiff = getMinusSCEV(RA, RS);
03989           if (LDiff == RDiff)
03990             return getAddExpr(getSMaxExpr(LS, RS), LDiff);
03991           LDiff = getMinusSCEV(LA, RS);
03992           RDiff = getMinusSCEV(RA, LS);
03993           if (LDiff == RDiff)
03994             return getAddExpr(getSMinExpr(LS, RS), LDiff);
03995         }
03996         break;
03997       case ICmpInst::ICMP_ULT:
03998       case ICmpInst::ICMP_ULE:
03999         std::swap(LHS, RHS);
04000         // fall through
04001       case ICmpInst::ICMP_UGT:
04002       case ICmpInst::ICMP_UGE:
04003         // a >u b ? a+x : b+x  ->  umax(a, b)+x
04004         // a >u b ? b+x : a+x  ->  umin(a, b)+x
04005         if (LHS->getType() == U->getType()) {
04006           const SCEV *LS = getSCEV(LHS);
04007           const SCEV *RS = getSCEV(RHS);
04008           const SCEV *LA = getSCEV(U->getOperand(1));
04009           const SCEV *RA = getSCEV(U->getOperand(2));
04010           const SCEV *LDiff = getMinusSCEV(LA, LS);
04011           const SCEV *RDiff = getMinusSCEV(RA, RS);
04012           if (LDiff == RDiff)
04013             return getAddExpr(getUMaxExpr(LS, RS), LDiff);
04014           LDiff = getMinusSCEV(LA, RS);
04015           RDiff = getMinusSCEV(RA, LS);
04016           if (LDiff == RDiff)
04017             return getAddExpr(getUMinExpr(LS, RS), LDiff);
04018         }
04019         break;
04020       case ICmpInst::ICMP_NE:
04021         // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
04022         if (LHS->getType() == U->getType() &&
04023             isa<ConstantInt>(RHS) &&
04024             cast<ConstantInt>(RHS)->isZero()) {
04025           const SCEV *One = getConstant(LHS->getType(), 1);
04026           const SCEV *LS = getSCEV(LHS);
04027           const SCEV *LA = getSCEV(U->getOperand(1));
04028           const SCEV *RA = getSCEV(U->getOperand(2));
04029           const SCEV *LDiff = getMinusSCEV(LA, LS);
04030           const SCEV *RDiff = getMinusSCEV(RA, One);
04031           if (LDiff == RDiff)
04032             return getAddExpr(getUMaxExpr(One, LS), LDiff);
04033         }
04034         break;
04035       case ICmpInst::ICMP_EQ:
04036         // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
04037         if (LHS->getType() == U->getType() &&
04038             isa<ConstantInt>(RHS) &&
04039             cast<ConstantInt>(RHS)->isZero()) {
04040           const SCEV *One = getConstant(LHS->getType(), 1);
04041           const SCEV *LS = getSCEV(LHS);
04042           const SCEV *LA = getSCEV(U->getOperand(1));
04043           const SCEV *RA = getSCEV(U->getOperand(2));
04044           const SCEV *LDiff = getMinusSCEV(LA, One);
04045           const SCEV *RDiff = getMinusSCEV(RA, LS);
04046           if (LDiff == RDiff)
04047             return getAddExpr(getUMaxExpr(One, LS), LDiff);
04048         }
04049         break;
04050       default:
04051         break;
04052       }
04053     }
04054 
04055   default: // We cannot analyze this expression.
04056     break;
04057   }
04058 
04059   return getUnknown(V);
04060 }
04061 
04062 
04063 
04064 //===----------------------------------------------------------------------===//
04065 //                   Iteration Count Computation Code
04066 //
04067 
04068 /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
04069 /// normal unsigned value. Returns 0 if the trip count is unknown or not
04070 /// constant. Will also return 0 if the maximum trip count is very large (>=
04071 /// 2^32).
04072 ///
04073 /// This "trip count" assumes that control exits via ExitingBlock. More
04074 /// precisely, it is the number of times that control may reach ExitingBlock
04075 /// before taking the branch. For loops with multiple exits, it may not be the
04076 /// number times that the loop header executes because the loop may exit
04077 /// prematurely via another branch.
04078 ///
04079 /// FIXME: We conservatively call getBackedgeTakenCount(L) instead of
04080 /// getExitCount(L, ExitingBlock) to compute a safe trip count considering all
04081 /// loop exits. getExitCount() may return an exact count for this branch
04082 /// assuming no-signed-wrap. The number of well-defined iterations may actually
04083 /// be higher than this trip count if this exit test is skipped and the loop
04084 /// exits via a different branch. Ideally, getExitCount() would know whether it
04085 /// depends on a NSW assumption, and we would only fall back to a conservative
04086 /// trip count in that case.
04087 unsigned ScalarEvolution::
04088 getSmallConstantTripCount(Loop *L, BasicBlock * /*ExitingBlock*/) {
04089   const SCEVConstant *ExitCount =
04090     dyn_cast<SCEVConstant>(getBackedgeTakenCount(L));
04091   if (!ExitCount)
04092     return 0;
04093 
04094   ConstantInt *ExitConst = ExitCount->getValue();
04095 
04096   // Guard against huge trip counts.
04097   if (ExitConst->getValue().getActiveBits() > 32)
04098     return 0;
04099 
04100   // In case of integer overflow, this returns 0, which is correct.
04101   return ((unsigned)ExitConst->getZExtValue()) + 1;
04102 }
04103 
04104 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
04105 /// trip count of this loop as a normal unsigned value, if possible. This
04106 /// means that the actual trip count is always a multiple of the returned
04107 /// value (don't forget the trip count could very well be zero as well!).
04108 ///
04109 /// Returns 1 if the trip count is unknown or not guaranteed to be the
04110 /// multiple of a constant (which is also the case if the trip count is simply
04111 /// constant, use getSmallConstantTripCount for that case), Will also return 1
04112 /// if the trip count is very large (>= 2^32).
04113 ///
04114 /// As explained in the comments for getSmallConstantTripCount, this assumes
04115 /// that control exits the loop via ExitingBlock.
04116 unsigned ScalarEvolution::
04117 getSmallConstantTripMultiple(Loop *L, BasicBlock * /*ExitingBlock*/) {
04118   const SCEV *ExitCount = getBackedgeTakenCount(L);
04119   if (ExitCount == getCouldNotCompute())
04120     return 1;
04121 
04122   // Get the trip count from the BE count by adding 1.
04123   const SCEV *TCMul = getAddExpr(ExitCount,
04124                                  getConstant(ExitCount->getType(), 1));
04125   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
04126   // to factor simple cases.
04127   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
04128     TCMul = Mul->getOperand(0);
04129 
04130   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
04131   if (!MulC)
04132     return 1;
04133 
04134   ConstantInt *Result = MulC->getValue();
04135 
04136   // Guard against huge trip counts (this requires checking
04137   // for zero to handle the case where the trip count == -1 and the
04138   // addition wraps).
04139   if (!Result || Result->getValue().getActiveBits() > 32 ||
04140       Result->getValue().getActiveBits() == 0)
04141     return 1;
04142 
04143   return (unsigned)Result->getZExtValue();
04144 }
04145 
04146 // getExitCount - Get the expression for the number of loop iterations for which
04147 // this loop is guaranteed not to exit via ExitingBlock. Otherwise return
04148 // SCEVCouldNotCompute.
04149 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
04150   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
04151 }
04152 
04153 /// getBackedgeTakenCount - If the specified loop has a predictable
04154 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
04155 /// object. The backedge-taken count is the number of times the loop header
04156 /// will be branched to from within the loop. This is one less than the
04157 /// trip count of the loop, since it doesn't count the first iteration,
04158 /// when the header is branched to from outside the loop.
04159 ///
04160 /// Note that it is not valid to call this method on a loop without a
04161 /// loop-invariant backedge-taken count (see
04162 /// hasLoopInvariantBackedgeTakenCount).
04163 ///
04164 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
04165   return getBackedgeTakenInfo(L).getExact(this);
04166 }
04167 
04168 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
04169 /// return the least SCEV value that is known never to be less than the
04170 /// actual backedge taken count.
04171 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
04172   return getBackedgeTakenInfo(L).getMax(this);
04173 }
04174 
04175 /// PushLoopPHIs - Push PHI nodes in the header of the given loop
04176 /// onto the given Worklist.
04177 static void
04178 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
04179   BasicBlock *Header = L->getHeader();
04180 
04181   // Push all Loop-header PHIs onto the Worklist stack.
04182   for (BasicBlock::iterator I = Header->begin();
04183        PHINode *PN = dyn_cast<PHINode>(I); ++I)
04184     Worklist.push_back(PN);
04185 }
04186 
04187 const ScalarEvolution::BackedgeTakenInfo &
04188 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
04189   // Initially insert an invalid entry for this loop. If the insertion
04190   // succeeds, proceed to actually compute a backedge-taken count and
04191   // update the value. The temporary CouldNotCompute value tells SCEV
04192   // code elsewhere that it shouldn't attempt to request a new
04193   // backedge-taken count, which could result in infinite recursion.
04194   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
04195     BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
04196   if (!Pair.second)
04197     return Pair.first->second;
04198 
04199   // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
04200   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
04201   // must be cleared in this scope.
04202   BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
04203 
04204   if (Result.getExact(this) != getCouldNotCompute()) {
04205     assert(isLoopInvariant(Result.getExact(this), L) &&
04206            isLoopInvariant(Result.getMax(this), L) &&
04207            "Computed backedge-taken count isn't loop invariant for loop!");
04208     ++NumTripCountsComputed;
04209   }
04210   else if (Result.getMax(this) == getCouldNotCompute() &&
04211            isa<PHINode>(L->getHeader()->begin())) {
04212     // Only count loops that have phi nodes as not being computable.
04213     ++NumTripCountsNotComputed;
04214   }
04215 
04216   // Now that we know more about the trip count for this loop, forget any
04217   // existing SCEV values for PHI nodes in this loop since they are only
04218   // conservative estimates made without the benefit of trip count
04219   // information. This is similar to the code in forgetLoop, except that
04220   // it handles SCEVUnknown PHI nodes specially.
04221   if (Result.hasAnyInfo()) {
04222     SmallVector<Instruction *, 16> Worklist;
04223     PushLoopPHIs(L, Worklist);
04224 
04225     SmallPtrSet<Instruction *, 8> Visited;
04226     while (!Worklist.empty()) {
04227       Instruction *I = Worklist.pop_back_val();
04228       if (!Visited.insert(I)) continue;
04229 
04230       ValueExprMapType::iterator It =
04231         ValueExprMap.find_as(static_cast<Value *>(I));
04232       if (It != ValueExprMap.end()) {
04233         const SCEV *Old = It->second;
04234 
04235         // SCEVUnknown for a PHI either means that it has an unrecognized
04236         // structure, or it's a PHI that's in the progress of being computed
04237         // by createNodeForPHI.  In the former case, additional loop trip
04238         // count information isn't going to change anything. In the later
04239         // case, createNodeForPHI will perform the necessary updates on its
04240         // own when it gets to that point.
04241         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
04242           forgetMemoizedResults(Old);
04243           ValueExprMap.erase(It);
04244         }
04245         if (PHINode *PN = dyn_cast<PHINode>(I))
04246           ConstantEvolutionLoopExitValue.erase(PN);
04247       }
04248 
04249       PushDefUseChildren(I, Worklist);
04250     }
04251   }
04252 
04253   // Re-lookup the insert position, since the call to
04254   // ComputeBackedgeTakenCount above could result in a
04255   // recusive call to getBackedgeTakenInfo (on a different
04256   // loop), which would invalidate the iterator computed
04257   // earlier.
04258   return BackedgeTakenCounts.find(L)->second = Result;
04259 }
04260 
04261 /// forgetLoop - This method should be called by the client when it has
04262 /// changed a loop in a way that may effect ScalarEvolution's ability to
04263 /// compute a trip count, or if the loop is deleted.
04264 void ScalarEvolution::forgetLoop(const Loop *L) {
04265   // Drop any stored trip count value.
04266   DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
04267     BackedgeTakenCounts.find(L);
04268   if (BTCPos != BackedgeTakenCounts.end()) {
04269     BTCPos->second.clear();
04270     BackedgeTakenCounts.erase(BTCPos);
04271   }
04272 
04273   // Drop information about expressions based on loop-header PHIs.
04274   SmallVector<Instruction *, 16> Worklist;
04275   PushLoopPHIs(L, Worklist);
04276 
04277   SmallPtrSet<Instruction *, 8> Visited;
04278   while (!Worklist.empty()) {
04279     Instruction *I = Worklist.pop_back_val();
04280     if (!Visited.insert(I)) continue;
04281 
04282     ValueExprMapType::iterator It =
04283       ValueExprMap.find_as(static_cast<Value *>(I));
04284     if (It != ValueExprMap.end()) {
04285       forgetMemoizedResults(It->second);
04286       ValueExprMap.erase(It);
04287       if (PHINode *PN = dyn_cast<PHINode>(I))
04288         ConstantEvolutionLoopExitValue.erase(PN);
04289     }
04290 
04291     PushDefUseChildren(I, Worklist);
04292   }
04293 
04294   // Forget all contained loops too, to avoid dangling entries in the
04295   // ValuesAtScopes map.
04296   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
04297     forgetLoop(*I);
04298 }
04299 
04300 /// forgetValue - This method should be called by the client when it has
04301 /// changed a value in a way that may effect its value, or which may
04302 /// disconnect it from a def-use chain linking it to a loop.
04303 void ScalarEvolution::forgetValue(Value *V) {
04304   Instruction *I = dyn_cast<Instruction>(V);
04305   if (!I) return;
04306 
04307   // Drop information about expressions based on loop-header PHIs.
04308   SmallVector<Instruction *, 16> Worklist;
04309   Worklist.push_back(I);
04310 
04311   SmallPtrSet<Instruction *, 8> Visited;
04312   while (!Worklist.empty()) {
04313     I = Worklist.pop_back_val();
04314     if (!Visited.insert(I)) continue;
04315 
04316     ValueExprMapType::iterator It =
04317       ValueExprMap.find_as(static_cast<Value *>(I));
04318     if (It != ValueExprMap.end()) {
04319       forgetMemoizedResults(It->second);
04320       ValueExprMap.erase(It);
04321       if (PHINode *PN = dyn_cast<PHINode>(I))
04322         ConstantEvolutionLoopExitValue.erase(PN);
04323     }
04324 
04325     PushDefUseChildren(I, Worklist);
04326   }
04327 }
04328 
04329 /// getExact - Get the exact loop backedge taken count considering all loop
04330 /// exits. A computable result can only be return for loops with a single exit.
04331 /// Returning the minimum taken count among all exits is incorrect because one
04332 /// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
04333 /// the limit of each loop test is never skipped. This is a valid assumption as
04334 /// long as the loop exits via that test. For precise results, it is the
04335 /// caller's responsibility to specify the relevant loop exit using
04336 /// getExact(ExitingBlock, SE).
04337 const SCEV *
04338 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
04339   // If any exits were not computable, the loop is not computable.
04340   if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
04341 
04342   // We need exactly one computable exit.
04343   if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
04344   assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
04345 
04346   const SCEV *BECount = nullptr;
04347   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
04348        ENT != nullptr; ENT = ENT->getNextExit()) {
04349 
04350     assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
04351 
04352     if (!BECount)
04353       BECount = ENT->ExactNotTaken;
04354     else if (BECount != ENT->ExactNotTaken)
04355       return SE->getCouldNotCompute();
04356   }
04357   assert(BECount && "Invalid not taken count for loop exit");
04358   return BECount;
04359 }
04360 
04361 /// getExact - Get the exact not taken count for this loop exit.
04362 const SCEV *
04363 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
04364                                              ScalarEvolution *SE) const {
04365   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
04366        ENT != nullptr; ENT = ENT->getNextExit()) {
04367 
04368     if (ENT->ExitingBlock == ExitingBlock)
04369       return ENT->ExactNotTaken;
04370   }
04371   return SE->getCouldNotCompute();
04372 }
04373 
04374 /// getMax - Get the max backedge taken count for the loop.
04375 const SCEV *
04376 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
04377   return Max ? Max : SE->getCouldNotCompute();
04378 }
04379 
04380 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
04381                                                     ScalarEvolution *SE) const {
04382   if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
04383     return true;
04384 
04385   if (!ExitNotTaken.ExitingBlock)
04386     return false;
04387 
04388   for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
04389        ENT != nullptr; ENT = ENT->getNextExit()) {
04390 
04391     if (ENT->ExactNotTaken != SE->getCouldNotCompute()
04392         && SE->hasOperand(ENT->ExactNotTaken, S)) {
04393       return true;
04394     }
04395   }
04396   return false;
04397 }
04398 
04399 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
04400 /// computable exit into a persistent ExitNotTakenInfo array.
04401 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
04402   SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
04403   bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
04404 
04405   if (!Complete)
04406     ExitNotTaken.setIncomplete();
04407 
04408   unsigned NumExits = ExitCounts.size();
04409   if (NumExits == 0) return;
04410 
04411   ExitNotTaken.ExitingBlock = ExitCounts[0].first;
04412   ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
04413   if (NumExits == 1) return;
04414 
04415   // Handle the rare case of multiple computable exits.
04416   ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
04417 
04418   ExitNotTakenInfo *PrevENT = &ExitNotTaken;
04419   for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
04420     PrevENT->setNextExit(ENT);
04421     ENT->ExitingBlock = ExitCounts[i].first;
04422     ENT->ExactNotTaken = ExitCounts[i].second;
04423   }
04424 }
04425 
04426 /// clear - Invalidate this result and free the ExitNotTakenInfo array.
04427 void ScalarEvolution::BackedgeTakenInfo::clear() {
04428   ExitNotTaken.ExitingBlock = nullptr;
04429   ExitNotTaken.ExactNotTaken = nullptr;
04430   delete[] ExitNotTaken.getNextExit();
04431 }
04432 
04433 /// ComputeBackedgeTakenCount - Compute the number of times the backedge
04434 /// of the specified loop will execute.
04435 ScalarEvolution::BackedgeTakenInfo
04436 ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
04437   SmallVector<BasicBlock *, 8> ExitingBlocks;
04438   L->getExitingBlocks(ExitingBlocks);
04439 
04440   SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
04441   bool CouldComputeBECount = true;
04442   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
04443   const SCEV *MustExitMaxBECount = nullptr;
04444   const SCEV *MayExitMaxBECount = nullptr;
04445 
04446   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
04447   // and compute maxBECount.
04448   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
04449     BasicBlock *ExitBB = ExitingBlocks[i];
04450     ExitLimit EL = ComputeExitLimit(L, ExitBB);
04451 
04452     // 1. For each exit that can be computed, add an entry to ExitCounts.
04453     // CouldComputeBECount is true only if all exits can be computed.
04454     if (EL.Exact == getCouldNotCompute())
04455       // We couldn't compute an exact value for this exit, so
04456       // we won't be able to compute an exact value for the loop.
04457       CouldComputeBECount = false;
04458     else
04459       ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
04460 
04461     // 2. Derive the loop's MaxBECount from each exit's max number of
04462     // non-exiting iterations. Partition the loop exits into two kinds:
04463     // LoopMustExits and LoopMayExits.
04464     //
04465     // A LoopMustExit meets two requirements:
04466     //
04467     // (a) Its ExitLimit.MustExit flag must be set which indicates that the exit
04468     // test condition cannot be skipped (the tested variable has unit stride or
04469     // the test is less-than or greater-than, rather than a strict inequality).
04470     //
04471     // (b) It must dominate the loop latch, hence must be tested on every loop
04472     // iteration.
04473     //
04474     // If any computable LoopMustExit is found, then MaxBECount is the minimum
04475     // EL.Max of computable LoopMustExits. Otherwise, MaxBECount is
04476     // conservatively the maximum EL.Max, where CouldNotCompute is considered
04477     // greater than any computable EL.Max.
04478     if (EL.MustExit && EL.Max != getCouldNotCompute() && Latch &&
04479         DT->dominates(ExitBB, Latch)) {
04480       if (!MustExitMaxBECount)
04481         MustExitMaxBECount = EL.Max;
04482       else {
04483         MustExitMaxBECount =
04484           getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
04485       }
04486     } else if (MayExitMaxBECount != getCouldNotCompute()) {
04487       if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
04488         MayExitMaxBECount = EL.Max;
04489       else {
04490         MayExitMaxBECount =
04491           getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
04492       }
04493     }
04494   }
04495   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
04496     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
04497   return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
04498 }
04499 
04500 /// ComputeExitLimit - Compute the number of times the backedge of the specified
04501 /// loop will execute if it exits via the specified block.
04502 ScalarEvolution::ExitLimit
04503 ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
04504 
04505   // Okay, we've chosen an exiting block.  See what condition causes us to
04506   // exit at this block and remember the exit block and whether all other targets
04507   // lead to the loop header.
04508   bool MustExecuteLoopHeader = true;
04509   BasicBlock *Exit = nullptr;
04510   for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
04511        SI != SE; ++SI)
04512     if (!L->contains(*SI)) {
04513       if (Exit) // Multiple exit successors.
04514         return getCouldNotCompute();
04515       Exit = *SI;
04516     } else if (*SI != L->getHeader()) {
04517       MustExecuteLoopHeader = false;
04518     }
04519 
04520   // At this point, we know we have a conditional branch that determines whether
04521   // the loop is exited.  However, we don't know if the branch is executed each
04522   // time through the loop.  If not, then the execution count of the branch will
04523   // not be equal to the trip count of the loop.
04524   //
04525   // Currently we check for this by checking to see if the Exit branch goes to
04526   // the loop header.  If so, we know it will always execute the same number of
04527   // times as the loop.  We also handle the case where the exit block *is* the
04528   // loop header.  This is common for un-rotated loops.
04529   //
04530   // If both of those tests fail, walk up the unique predecessor chain to the
04531   // header, stopping if there is an edge that doesn't exit the loop. If the
04532   // header is reached, the execution count of the branch will be equal to the
04533   // trip count of the loop.
04534   //
04535   //  More extensive analysis could be done to handle more cases here.
04536   //
04537   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
04538     // The simple checks failed, try climbing the unique predecessor chain
04539     // up to the header.
04540     bool Ok = false;
04541     for (BasicBlock *BB = ExitingBlock; BB; ) {
04542       BasicBlock *Pred = BB->getUniquePredecessor();
04543       if (!Pred)
04544         return getCouldNotCompute();
04545       TerminatorInst *PredTerm = Pred->getTerminator();
04546       for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
04547         BasicBlock *PredSucc = PredTerm->getSuccessor(i);
04548         if (PredSucc == BB)
04549           continue;
04550         // If the predecessor has a successor that isn't BB and isn't
04551         // outside the loop, assume the worst.
04552         if (L->contains(PredSucc))
04553           return getCouldNotCompute();
04554       }
04555       if (Pred == L->getHeader()) {
04556         Ok = true;
04557         break;
04558       }
04559       BB = Pred;
04560     }
04561     if (!Ok)
04562       return getCouldNotCompute();
04563   }
04564 
04565   TerminatorInst *Term = ExitingBlock->getTerminator();
04566   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
04567     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
04568     // Proceed to the next level to examine the exit condition expression.
04569     return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
04570                                     BI->getSuccessor(1),
04571                                     /*IsSubExpr=*/false);
04572   }
04573 
04574   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
04575     return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
04576                                                 /*IsSubExpr=*/false);
04577 
04578   return getCouldNotCompute();
04579 }
04580 
04581 /// ComputeExitLimitFromCond - Compute the number of times the
04582 /// backedge of the specified loop will execute if its exit condition
04583 /// were a conditional branch of ExitCond, TBB, and FBB.
04584 ///
04585 /// @param IsSubExpr is true if ExitCond does not directly control the exit
04586 /// branch. In this case, we cannot assume that the loop only exits when the
04587 /// condition is true and cannot infer that failing to meet the condition prior
04588 /// to integer wraparound results in undefined behavior.
04589 ScalarEvolution::ExitLimit
04590 ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
04591                                           Value *ExitCond,
04592                                           BasicBlock *TBB,
04593                                           BasicBlock *FBB,
04594                                           bool IsSubExpr) {
04595   // Check if the controlling expression for this loop is an And or Or.
04596   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
04597     if (BO->getOpcode() == Instruction::And) {
04598       // Recurse on the operands of the and.
04599       bool EitherMayExit = L->contains(TBB);
04600       ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
04601                                                IsSubExpr || EitherMayExit);
04602       ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
04603                                                IsSubExpr || EitherMayExit);
04604       const SCEV *BECount = getCouldNotCompute();
04605       const SCEV *MaxBECount = getCouldNotCompute();
04606       bool MustExit = false;
04607       if (EitherMayExit) {
04608         // Both conditions must be true for the loop to continue executing.
04609         // Choose the less conservative count.
04610         if (EL0.Exact == getCouldNotCompute() ||
04611             EL1.Exact == getCouldNotCompute())
04612           BECount = getCouldNotCompute();
04613         else
04614           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
04615         if (EL0.Max == getCouldNotCompute())
04616           MaxBECount = EL1.Max;
04617         else if (EL1.Max == getCouldNotCompute())
04618           MaxBECount = EL0.Max;
04619         else
04620           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
04621         MustExit = EL0.MustExit || EL1.MustExit;
04622       } else {
04623         // Both conditions must be true at the same time for the loop to exit.
04624         // For now, be conservative.
04625         assert(L->contains(FBB) && "Loop block has no successor in loop!");
04626         if (EL0.Max == EL1.Max)
04627           MaxBECount = EL0.Max;
04628         if (EL0.Exact == EL1.Exact)
04629           BECount = EL0.Exact;
04630         MustExit = EL0.MustExit && EL1.MustExit;
04631       }
04632 
04633       return ExitLimit(BECount, MaxBECount, MustExit);
04634     }
04635     if (BO->getOpcode() == Instruction::Or) {
04636       // Recurse on the operands of the or.
04637       bool EitherMayExit = L->contains(FBB);
04638       ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
04639                                                IsSubExpr || EitherMayExit);
04640       ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
04641                                                IsSubExpr || EitherMayExit);
04642       const SCEV *BECount = getCouldNotCompute();
04643       const SCEV *MaxBECount = getCouldNotCompute();
04644       bool MustExit = false;
04645       if (EitherMayExit) {
04646         // Both conditions must be false for the loop to continue executing.
04647         // Choose the less conservative count.
04648         if (EL0.Exact == getCouldNotCompute() ||
04649             EL1.Exact == getCouldNotCompute())
04650           BECount = getCouldNotCompute();
04651         else
04652           BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
04653         if (EL0.Max == getCouldNotCompute())
04654           MaxBECount = EL1.Max;
04655         else if (EL1.Max == getCouldNotCompute())
04656           MaxBECount = EL0.Max;
04657         else
04658           MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
04659         MustExit = EL0.MustExit || EL1.MustExit;
04660       } else {
04661         // Both conditions must be false at the same time for the loop to exit.
04662         // For now, be conservative.
04663         assert(L->contains(TBB) && "Loop block has no successor in loop!");
04664         if (EL0.Max == EL1.Max)
04665           MaxBECount = EL0.Max;
04666         if (EL0.Exact == EL1.Exact)
04667           BECount = EL0.Exact;
04668         MustExit = EL0.MustExit && EL1.MustExit;
04669       }
04670 
04671       return ExitLimit(BECount, MaxBECount, MustExit);
04672     }
04673   }
04674 
04675   // With an icmp, it may be feasible to compute an exact backedge-taken count.
04676   // Proceed to the next level to examine the icmp.
04677   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
04678     return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, IsSubExpr);
04679 
04680   // Check for a constant condition. These are normally stripped out by
04681   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
04682   // preserve the CFG and is temporarily leaving constant conditions
04683   // in place.
04684   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
04685     if (L->contains(FBB) == !CI->getZExtValue())
04686       // The backedge is always taken.
04687       return getCouldNotCompute();
04688     else
04689       // The backedge is never taken.
04690       return getConstant(CI->getType(), 0);
04691   }
04692 
04693   // If it's not an integer or pointer comparison then compute it the hard way.
04694   return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
04695 }
04696 
04697 /// ComputeExitLimitFromICmp - Compute the number of times the
04698 /// backedge of the specified loop will execute if its exit condition
04699 /// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
04700 ScalarEvolution::ExitLimit
04701 ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
04702                                           ICmpInst *ExitCond,
04703                                           BasicBlock *TBB,
04704                                           BasicBlock *FBB,
04705                                           bool IsSubExpr) {
04706 
04707   // If the condition was exit on true, convert the condition to exit on false
04708   ICmpInst::Predicate Cond;
04709   if (!L->contains(FBB))
04710     Cond = ExitCond->getPredicate();
04711   else
04712     Cond = ExitCond->getInversePredicate();
04713 
04714   // Handle common loops like: for (X = "string"; *X; ++X)
04715   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
04716     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
04717       ExitLimit ItCnt =
04718         ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
04719       if (ItCnt.hasAnyInfo())
04720         return ItCnt;
04721     }
04722 
04723   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
04724   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
04725 
04726   // Try to evaluate any dependencies out of the loop.
04727   LHS = getSCEVAtScope(LHS, L);
04728   RHS = getSCEVAtScope(RHS, L);
04729 
04730   // At this point, we would like to compute how many iterations of the
04731   // loop the predicate will return true for these inputs.
04732   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
04733     // If there is a loop-invariant, force it into the RHS.
04734     std::swap(LHS, RHS);
04735     Cond = ICmpInst::getSwappedPredicate(Cond);
04736   }
04737 
04738   // Simplify the operands before analyzing them.
04739   (void)SimplifyICmpOperands(Cond, LHS, RHS);
04740 
04741   // If we have a comparison of a chrec against a constant, try to use value
04742   // ranges to answer this query.
04743   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
04744     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
04745       if (AddRec->getLoop() == L) {
04746         // Form the constant range.
04747         ConstantRange CompRange(
04748             ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
04749 
04750         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
04751         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
04752       }
04753 
04754   switch (Cond) {
04755   case ICmpInst::ICMP_NE: {                     // while (X != Y)
04756     // Convert to: while (X-Y != 0)
04757     ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, IsSubExpr);
04758     if (EL.hasAnyInfo()) return EL;
04759     break;
04760   }
04761   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
04762     // Convert to: while (X-Y == 0)
04763     ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
04764     if (EL.hasAnyInfo()) return EL;
04765     break;
04766   }
04767   case ICmpInst::ICMP_SLT:
04768   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
04769     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
04770     ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, IsSubExpr);
04771     if (EL.hasAnyInfo()) return EL;
04772     break;
04773   }
04774   case ICmpInst::ICMP_SGT:
04775   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
04776     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
04777     ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, IsSubExpr);
04778     if (EL.hasAnyInfo()) return EL;
04779     break;
04780   }
04781   default:
04782 #if 0
04783     dbgs() << "ComputeBackedgeTakenCount ";
04784     if (ExitCond->getOperand(0)->getType()->isUnsigned())
04785       dbgs() << "[unsigned] ";
04786     dbgs() << *LHS << "   "
04787          << Instruction::getOpcodeName(Instruction::ICmp)
04788          << "   " << *RHS << "\n";
04789 #endif
04790     break;
04791   }
04792   return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
04793 }
04794 
04795 ScalarEvolution::ExitLimit
04796 ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
04797                                                       SwitchInst *Switch,
04798                                                       BasicBlock *ExitingBlock,
04799                                                       bool IsSubExpr) {
04800   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
04801 
04802   // Give up if the exit is the default dest of a switch.
04803   if (Switch->getDefaultDest() == ExitingBlock)
04804     return getCouldNotCompute();
04805 
04806   assert(L->contains(Switch->getDefaultDest()) &&
04807          "Default case must not exit the loop!");
04808   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
04809   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
04810 
04811   // while (X != Y) --> while (X-Y != 0)
04812   ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, IsSubExpr);
04813   if (EL.hasAnyInfo())
04814     return EL;
04815 
04816   return getCouldNotCompute();
04817 }
04818 
04819 static ConstantInt *
04820 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
04821                                 ScalarEvolution &SE) {
04822   const SCEV *InVal = SE.getConstant(C);
04823   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
04824   assert(isa<SCEVConstant>(Val) &&
04825          "Evaluation of SCEV at constant didn't fold correctly?");
04826   return cast<SCEVConstant>(Val)->getValue();
04827 }
04828 
04829 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
04830 /// 'icmp op load X, cst', try to see if we can compute the backedge
04831 /// execution count.
04832 ScalarEvolution::ExitLimit
04833 ScalarEvolution::ComputeLoadConstantCompareExitLimit(
04834   LoadInst *LI,
04835   Constant *RHS,
04836   const Loop *L,
04837   ICmpInst::Predicate predicate) {
04838 
04839   if (LI->isVolatile()) return getCouldNotCompute();
04840 
04841   // Check to see if the loaded pointer is a getelementptr of a global.
04842   // TODO: Use SCEV instead of manually grubbing with GEPs.
04843   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
04844   if (!GEP) return getCouldNotCompute();
04845 
04846   // Make sure that it is really a constant global we are gepping, with an
04847   // initializer, and make sure the first IDX is really 0.
04848   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
04849   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
04850       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
04851       !cast<Constant>(GEP->getOperand(1))->isNullValue())
04852     return getCouldNotCompute();
04853 
04854   // Okay, we allow one non-constant index into the GEP instruction.
04855   Value *VarIdx = nullptr;
04856   std::vector<Constant*> Indexes;
04857   unsigned VarIdxNum = 0;
04858   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
04859     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
04860       Indexes.push_back(CI);
04861     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
04862       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
04863       VarIdx = GEP->getOperand(i);
04864       VarIdxNum = i-2;
04865       Indexes.push_back(nullptr);
04866     }
04867 
04868   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
04869   if (!VarIdx)
04870     return getCouldNotCompute();
04871 
04872   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
04873   // Check to see if X is a loop variant variable value now.
04874   const SCEV *Idx = getSCEV(VarIdx);
04875   Idx = getSCEVAtScope(Idx, L);
04876 
04877   // We can only recognize very limited forms of loop index expressions, in
04878   // particular, only affine AddRec's like {C1,+,C2}.
04879   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
04880   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
04881       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
04882       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
04883     return getCouldNotCompute();
04884 
04885   unsigned MaxSteps = MaxBruteForceIterations;
04886   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
04887     ConstantInt *ItCst = ConstantInt::get(
04888                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
04889     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
04890 
04891     // Form the GEP offset.
04892     Indexes[VarIdxNum] = Val;
04893 
04894     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
04895                                                          Indexes);
04896     if (!Result) break;  // Cannot compute!
04897 
04898     // Evaluate the condition for this iteration.
04899     Result = ConstantExpr::getICmp(predicate, Result, RHS);
04900     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
04901     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
04902 #if 0
04903       dbgs() << "\n***\n*** Computed loop count " << *ItCst
04904              << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
04905              << "***\n";
04906 #endif
04907       ++NumArrayLenItCounts;
04908       return getConstant(ItCst);   // Found terminating iteration!
04909     }
04910   }
04911   return getCouldNotCompute();
04912 }
04913 
04914 
04915 /// CanConstantFold - Return true if we can constant fold an instruction of the
04916 /// specified type, assuming that all operands were constants.
04917 static bool CanConstantFold(const Instruction *I) {
04918   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
04919       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
04920       isa<LoadInst>(I))
04921     return true;
04922 
04923   if (const CallInst *CI = dyn_cast<CallInst>(I))
04924     if (const Function *F = CI->getCalledFunction())
04925       return canConstantFoldCallTo(F);
04926   return false;
04927 }
04928 
04929 /// Determine whether this instruction can constant evolve within this loop
04930 /// assuming its operands can all constant evolve.
04931 static bool canConstantEvolve(Instruction *I, const Loop *L) {
04932   // An instruction outside of the loop can't be derived from a loop PHI.
04933   if (!L->contains(I)) return false;
04934 
04935   if (isa<PHINode>(I)) {
04936     if (L->getHeader() == I->getParent())
04937       return true;
04938     else
04939       // We don't currently keep track of the control flow needed to evaluate
04940       // PHIs, so we cannot handle PHIs inside of loops.
04941       return false;
04942   }
04943 
04944   // If we won't be able to constant fold this expression even if the operands
04945   // are constants, bail early.
04946   return CanConstantFold(I);
04947 }
04948 
04949 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
04950 /// recursing through each instruction operand until reaching a loop header phi.
04951 static PHINode *
04952 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
04953                                DenseMap<Instruction *, PHINode *> &PHIMap) {
04954 
04955   // Otherwise, we can evaluate this instruction if all of its operands are
04956   // constant or derived from a PHI node themselves.
04957   PHINode *PHI = nullptr;
04958   for (Instruction::op_iterator OpI = UseInst->op_begin(),
04959          OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
04960 
04961     if (isa<Constant>(*OpI)) continue;
04962 
04963     Instruction *OpInst = dyn_cast<Instruction>(*OpI);
04964     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
04965 
04966     PHINode *P = dyn_cast<PHINode>(OpInst);
04967     if (!P)
04968       // If this operand is already visited, reuse the prior result.
04969       // We may have P != PHI if this is the deepest point at which the
04970       // inconsistent paths meet.
04971       P = PHIMap.lookup(OpInst);
04972     if (!P) {
04973       // Recurse and memoize the results, whether a phi is found or not.
04974       // This recursive call invalidates pointers into PHIMap.
04975       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
04976       PHIMap[OpInst] = P;
04977     }
04978     if (!P)
04979       return nullptr;  // Not evolving from PHI
04980     if (PHI && PHI != P)
04981       return nullptr;  // Evolving from multiple different PHIs.
04982     PHI = P;
04983   }
04984   // This is a expression evolving from a constant PHI!
04985   return PHI;
04986 }
04987 
04988 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
04989 /// in the loop that V is derived from.  We allow arbitrary operations along the
04990 /// way, but the operands of an operation must either be constants or a value
04991 /// derived from a constant PHI.  If this expression does not fit with these
04992 /// constraints, return null.
04993 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
04994   Instruction *I = dyn_cast<Instruction>(V);
04995   if (!I || !canConstantEvolve(I, L)) return nullptr;
04996 
04997   if (PHINode *PN = dyn_cast<PHINode>(I)) {
04998     return PN;
04999   }
05000 
05001   // Record non-constant instructions contained by the loop.
05002   DenseMap<Instruction *, PHINode *> PHIMap;
05003   return getConstantEvolvingPHIOperands(I, L, PHIMap);
05004 }
05005 
05006 /// EvaluateExpression - Given an expression that passes the
05007 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
05008 /// in the loop has the value PHIVal.  If we can't fold this expression for some
05009 /// reason, return null.
05010 static Constant *EvaluateExpression(Value *V, const Loop *L,
05011                                     DenseMap<Instruction *, Constant *> &Vals,
05012                                     const DataLayout *DL,
05013                                     const TargetLibraryInfo *TLI) {
05014   // Convenient constant check, but redundant for recursive calls.
05015   if (Constant *C = dyn_cast<Constant>(V)) return C;
05016   Instruction *I = dyn_cast<Instruction>(V);
05017   if (!I) return nullptr;
05018 
05019   if (Constant *C = Vals.lookup(I)) return C;
05020 
05021   // An instruction inside the loop depends on a value outside the loop that we
05022   // weren't given a mapping for, or a value such as a call inside the loop.
05023   if (!canConstantEvolve(I, L)) return nullptr;
05024 
05025   // An unmapped PHI can be due to a branch or another loop inside this loop,
05026   // or due to this not being the initial iteration through a loop where we
05027   // couldn't compute the evolution of this particular PHI last time.
05028   if (isa<PHINode>(I)) return nullptr;
05029 
05030   std::vector<Constant*> Operands(I->getNumOperands());
05031 
05032   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
05033     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
05034     if (!Operand) {
05035       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
05036       if (!Operands[i]) return nullptr;
05037       continue;
05038     }
05039     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
05040     Vals[Operand] = C;
05041     if (!C) return nullptr;
05042     Operands[i] = C;
05043   }
05044 
05045   if (CmpInst *CI = dyn_cast<CmpInst>(I))
05046     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
05047                                            Operands[1], DL, TLI);
05048   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
05049     if (!LI->isVolatile())
05050       return ConstantFoldLoadFromConstPtr(Operands[0], DL);
05051   }
05052   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
05053                                   TLI);
05054 }
05055 
05056 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
05057 /// in the header of its containing loop, we know the loop executes a
05058 /// constant number of times, and the PHI node is just a recurrence
05059 /// involving constants, fold it.
05060 Constant *
05061 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
05062                                                    const APInt &BEs,
05063                                                    const Loop *L) {
05064   DenseMap<PHINode*, Constant*>::const_iterator I =
05065     ConstantEvolutionLoopExitValue.find(PN);
05066   if (I != ConstantEvolutionLoopExitValue.end())
05067     return I->second;
05068 
05069   if (BEs.ugt(MaxBruteForceIterations))
05070     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
05071 
05072   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
05073 
05074   DenseMap<Instruction *, Constant *> CurrentIterVals;
05075   BasicBlock *Header = L->getHeader();
05076   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
05077 
05078   // Since the loop is canonicalized, the PHI node must have two entries.  One
05079   // entry must be a constant (coming in from outside of the loop), and the
05080   // second must be derived from the same PHI.
05081   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
05082   PHINode *PHI = nullptr;
05083   for (BasicBlock::iterator I = Header->begin();
05084        (PHI = dyn_cast<PHINode>(I)); ++I) {
05085     Constant *StartCST =
05086       dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
05087     if (!StartCST) continue;
05088     CurrentIterVals[PHI] = StartCST;
05089   }
05090   if (!CurrentIterVals.count(PN))
05091     return RetVal = nullptr;
05092 
05093   Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
05094 
05095   // Execute the loop symbolically to determine the exit value.
05096   if (BEs.getActiveBits() >= 32)
05097     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
05098 
05099   unsigned NumIterations = BEs.getZExtValue(); // must be in range
05100   unsigned IterationNum = 0;
05101   for (; ; ++IterationNum) {
05102     if (IterationNum == NumIterations)
05103       return RetVal = CurrentIterVals[PN];  // Got exit value!
05104 
05105     // Compute the value of the PHIs for the next iteration.
05106     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
05107     DenseMap<Instruction *, Constant *> NextIterVals;
05108     Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
05109                                            TLI);
05110     if (!NextPHI)
05111       return nullptr;        // Couldn't evaluate!
05112     NextIterVals[PN] = NextPHI;
05113 
05114     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
05115 
05116     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
05117     // cease to be able to evaluate one of them or if they stop evolving,
05118     // because that doesn't necessarily prevent us from computing PN.
05119     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
05120     for (DenseMap<Instruction *, Constant *>::const_iterator
05121            I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
05122       PHINode *PHI = dyn_cast<PHINode>(I->first);
05123       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
05124       PHIsToCompute.push_back(std::make_pair(PHI, I->second));
05125     }
05126     // We use two distinct loops because EvaluateExpression may invalidate any
05127     // iterators into CurrentIterVals.
05128     for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
05129              I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
05130       PHINode *PHI = I->first;
05131       Constant *&NextPHI = NextIterVals[PHI];
05132       if (!NextPHI) {   // Not already computed.
05133         Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
05134         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
05135       }
05136       if (NextPHI != I->second)
05137         StoppedEvolving = false;
05138     }
05139 
05140     // If all entries in CurrentIterVals == NextIterVals then we can stop
05141     // iterating, the loop can't continue to change.
05142     if (StoppedEvolving)
05143       return RetVal = CurrentIterVals[PN];
05144 
05145     CurrentIterVals.swap(NextIterVals);
05146   }
05147 }
05148 
05149 /// ComputeExitCountExhaustively - If the loop is known to execute a
05150 /// constant number of times (the condition evolves only from constants),
05151 /// try to evaluate a few iterations of the loop until we get the exit
05152 /// condition gets a value of ExitWhen (true or false).  If we cannot
05153 /// evaluate the trip count of the loop, return getCouldNotCompute().
05154 const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
05155                                                           Value *Cond,
05156                                                           bool ExitWhen) {
05157   PHINode *PN = getConstantEvolvingPHI(Cond, L);
05158   if (!PN) return getCouldNotCompute();
05159 
05160   // If the loop is canonicalized, the PHI will have exactly two entries.
05161   // That's the only form we support here.
05162   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
05163 
05164   DenseMap<Instruction *, Constant *> CurrentIterVals;
05165   BasicBlock *Header = L->getHeader();
05166   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
05167 
05168   // One entry must be a constant (coming in from outside of the loop), and the
05169   // second must be derived from the same PHI.
05170   bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
05171   PHINode *PHI = nullptr;
05172   for (BasicBlock::iterator I = Header->begin();
05173        (PHI = dyn_cast<PHINode>(I)); ++I) {
05174     Constant *StartCST =
05175       dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
05176     if (!StartCST) continue;
05177     CurrentIterVals[PHI] = StartCST;
05178   }
05179   if (!CurrentIterVals.count(PN))
05180     return getCouldNotCompute();
05181 
05182   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
05183   // the loop symbolically to determine when the condition gets a value of
05184   // "ExitWhen".
05185 
05186   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
05187   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
05188     ConstantInt *CondVal =
05189       dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
05190                                                        DL, TLI));
05191 
05192     // Couldn't symbolically evaluate.
05193     if (!CondVal) return getCouldNotCompute();
05194 
05195     if (CondVal->getValue() == uint64_t(ExitWhen)) {
05196       ++NumBruteForceTripCountsComputed;
05197       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
05198     }
05199 
05200     // Update all the PHI nodes for the next iteration.
05201     DenseMap<Instruction *, Constant *> NextIterVals;
05202 
05203     // Create a list of which PHIs we need to compute. We want to do this before
05204     // calling EvaluateExpression on them because that may invalidate iterators
05205     // into CurrentIterVals.
05206     SmallVector<PHINode *, 8> PHIsToCompute;
05207     for (DenseMap<Instruction *, Constant *>::const_iterator
05208            I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
05209       PHINode *PHI = dyn_cast<PHINode>(I->first);
05210       if (!PHI || PHI->getParent() != Header) continue;
05211       PHIsToCompute.push_back(PHI);
05212     }
05213     for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
05214              E = PHIsToCompute.end(); I != E; ++I) {
05215       PHINode *PHI = *I;
05216       Constant *&NextPHI = NextIterVals[PHI];
05217       if (NextPHI) continue;    // Already computed!
05218 
05219       Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
05220       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
05221     }
05222     CurrentIterVals.swap(NextIterVals);
05223   }
05224 
05225   // Too many iterations were needed to evaluate.
05226   return getCouldNotCompute();
05227 }
05228 
05229 /// getSCEVAtScope - Return a SCEV expression for the specified value
05230 /// at the specified scope in the program.  The L value specifies a loop
05231 /// nest to evaluate the expression at, where null is the top-level or a
05232 /// specified loop is immediately inside of the loop.
05233 ///
05234 /// This method can be used to compute the exit value for a variable defined
05235 /// in a loop by querying what the value will hold in the parent loop.
05236 ///
05237 /// In the case that a relevant loop exit value cannot be computed, the
05238 /// original value V is returned.
05239 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
05240   // Check to see if we've folded this expression at this loop before.
05241   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
05242   for (unsigned u = 0; u < Values.size(); u++) {
05243     if (Values[u].first == L)
05244       return Values[u].second ? Values[u].second : V;
05245   }
05246   Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
05247   // Otherwise compute it.
05248   const SCEV *C = computeSCEVAtScope(V, L);
05249   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
05250   for (unsigned u = Values2.size(); u > 0; u--) {
05251     if (Values2[u - 1].first == L) {
05252       Values2[u - 1].second = C;
05253       break;
05254     }
05255   }
05256   return C;
05257 }
05258 
05259 /// This builds up a Constant using the ConstantExpr interface.  That way, we
05260 /// will return Constants for objects which aren't represented by a
05261 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
05262 /// Returns NULL if the SCEV isn't representable as a Constant.
05263 static Constant *BuildConstantFromSCEV(const SCEV *V) {
05264   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
05265     case scCouldNotCompute:
05266     case scAddRecExpr:
05267       break;
05268     case scConstant:
05269       return cast<SCEVConstant>(V)->getValue();
05270     case scUnknown:
05271       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
05272     case scSignExtend: {
05273       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
05274       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
05275         return ConstantExpr::getSExt(CastOp, SS->getType());
05276       break;
05277     }
05278     case scZeroExtend: {
05279       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
05280       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
05281         return ConstantExpr::getZExt(CastOp, SZ->getType());
05282       break;
05283     }
05284     case scTruncate: {
05285       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
05286       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
05287         return ConstantExpr::getTrunc(CastOp, ST->getType());
05288       break;
05289     }
05290     case scAddExpr: {
05291       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
05292       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
05293         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
05294           unsigned AS = PTy->getAddressSpace();
05295           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
05296           C = ConstantExpr::getBitCast(C, DestPtrTy);
05297         }
05298         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
05299           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
05300           if (!C2) return nullptr;
05301 
05302           // First pointer!
05303           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
05304             unsigned AS = C2->getType()->getPointerAddressSpace();
05305             std::swap(C, C2);
05306             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
05307             // The offsets have been converted to bytes.  We can add bytes to an
05308             // i8* by GEP with the byte count in the first index.
05309             C = ConstantExpr::getBitCast(C, DestPtrTy);
05310           }
05311 
05312           // Don't bother trying to sum two pointers. We probably can't
05313           // statically compute a load that results from it anyway.
05314           if (C2->getType()->isPointerTy())
05315             return nullptr;
05316 
05317           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
05318             if (PTy->getElementType()->isStructTy())
05319               C2 = ConstantExpr::getIntegerCast(
05320                   C2, Type::getInt32Ty(C->getContext()), true);
05321             C = ConstantExpr::getGetElementPtr(C, C2);
05322           } else
05323             C = ConstantExpr::getAdd(C, C2);
05324         }
05325         return C;
05326       }
05327       break;
05328     }
05329     case scMulExpr: {
05330       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
05331       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
05332         // Don't bother with pointers at all.
05333         if (C->getType()->isPointerTy()) return nullptr;
05334         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
05335           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
05336           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
05337           C = ConstantExpr::getMul(C, C2);
05338         }
05339         return C;
05340       }
05341       break;
05342     }
05343     case scUDivExpr: {
05344       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
05345       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
05346         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
05347           if (LHS->getType() == RHS->getType())
05348             return ConstantExpr::getUDiv(LHS, RHS);
05349       break;
05350     }
05351     case scSMaxExpr:
05352     case scUMaxExpr:
05353       break; // TODO: smax, umax.
05354   }
05355   return nullptr;
05356 }
05357 
05358 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
05359   if (isa<SCEVConstant>(V)) return V;
05360 
05361   // If this instruction is evolved from a constant-evolving PHI, compute the
05362   // exit value from the loop without using SCEVs.
05363   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
05364     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
05365       const Loop *LI = (*this->LI)[I->getParent()];
05366       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
05367         if (PHINode *PN = dyn_cast<PHINode>(I))
05368           if (PN->getParent() == LI->getHeader()) {
05369             // Okay, there is no closed form solution for the PHI node.  Check
05370             // to see if the loop that contains it has a known backedge-taken
05371             // count.  If so, we may be able to force computation of the exit
05372             // value.
05373             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
05374             if (const SCEVConstant *BTCC =
05375                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
05376               // Okay, we know how many times the containing loop executes.  If
05377               // this is a constant evolving PHI node, get the final value at
05378               // the specified iteration number.
05379               Constant *RV = getConstantEvolutionLoopExitValue(PN,
05380                                                    BTCC->getValue()->getValue(),
05381                                                                LI);
05382               if (RV) return getSCEV(RV);
05383             }
05384           }
05385 
05386       // Okay, this is an expression that we cannot symbolically evaluate
05387       // into a SCEV.  Check to see if it's possible to symbolically evaluate
05388       // the arguments into constants, and if so, try to constant propagate the
05389       // result.  This is particularly useful for computing loop exit values.
05390       if (CanConstantFold(I)) {
05391         SmallVector<Constant *, 4> Operands;
05392         bool MadeImprovement = false;
05393         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
05394           Value *Op = I->getOperand(i);
05395           if (Constant *C = dyn_cast<Constant>(Op)) {
05396             Operands.push_back(C);
05397             continue;
05398           }
05399 
05400           // If any of the operands is non-constant and if they are
05401           // non-integer and non-pointer, don't even try to analyze them
05402           // with scev techniques.
05403           if (!isSCEVable(Op->getType()))
05404             return V;
05405 
05406           const SCEV *OrigV = getSCEV(Op);
05407           const SCEV *OpV = getSCEVAtScope(OrigV, L);
05408           MadeImprovement |= OrigV != OpV;
05409 
05410           Constant *C = BuildConstantFromSCEV(OpV);
05411           if (!C) return V;
05412           if (C->getType() != Op->getType())
05413             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
05414                                                               Op->getType(),
05415                                                               false),
05416                                       C, Op->getType());
05417           Operands.push_back(C);
05418         }
05419 
05420         // Check to see if getSCEVAtScope actually made an improvement.
05421         if (MadeImprovement) {
05422           Constant *C = nullptr;
05423           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
05424             C = ConstantFoldCompareInstOperands(CI->getPredicate(),
05425                                                 Operands[0], Operands[1], DL,
05426                                                 TLI);
05427           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
05428             if (!LI->isVolatile())
05429               C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
05430           } else
05431             C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
05432                                          Operands, DL, TLI);
05433           if (!C) return V;
05434           return getSCEV(C);
05435         }
05436       }
05437     }
05438 
05439     // This is some other type of SCEVUnknown, just return it.
05440     return V;
05441   }
05442 
05443   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
05444     // Avoid performing the look-up in the common case where the specified
05445     // expression has no loop-variant portions.
05446     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
05447       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
05448       if (OpAtScope != Comm->getOperand(i)) {
05449         // Okay, at least one of these operands is loop variant but might be
05450         // foldable.  Build a new instance of the folded commutative expression.
05451         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
05452                                             Comm->op_begin()+i);
05453         NewOps.push_back(OpAtScope);
05454 
05455         for (++i; i != e; ++i) {
05456           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
05457           NewOps.push_back(OpAtScope);
05458         }
05459         if (isa<SCEVAddExpr>(Comm))
05460           return getAddExpr(NewOps);
05461         if (isa<SCEVMulExpr>(Comm))
05462           return getMulExpr(NewOps);
05463         if (isa<SCEVSMaxExpr>(Comm))
05464           return getSMaxExpr(NewOps);
05465         if (isa<SCEVUMaxExpr>(Comm))
05466           return getUMaxExpr(NewOps);
05467         llvm_unreachable("Unknown commutative SCEV type!");
05468       }
05469     }
05470     // If we got here, all operands are loop invariant.
05471     return Comm;
05472   }
05473 
05474   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
05475     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
05476     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
05477     if (LHS == Div->getLHS() && RHS == Div->getRHS())
05478       return Div;   // must be loop invariant
05479     return getUDivExpr(LHS, RHS);
05480   }
05481 
05482   // If this is a loop recurrence for a loop that does not contain L, then we
05483   // are dealing with the final value computed by the loop.
05484   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
05485     // First, attempt to evaluate each operand.
05486     // Avoid performing the look-up in the common case where the specified
05487     // expression has no loop-variant portions.
05488     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
05489       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
05490       if (OpAtScope == AddRec->getOperand(i))
05491         continue;
05492 
05493       // Okay, at least one of these operands is loop variant but might be
05494       // foldable.  Build a new instance of the folded commutative expression.
05495       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
05496                                           AddRec->op_begin()+i);
05497       NewOps.push_back(OpAtScope);
05498       for (++i; i != e; ++i)
05499         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
05500 
05501       const SCEV *FoldedRec =
05502         getAddRecExpr(NewOps, AddRec->getLoop(),
05503                       AddRec->getNoWrapFlags(SCEV::FlagNW));
05504       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
05505       // The addrec may be folded to a nonrecurrence, for example, if the
05506       // induction variable is multiplied by zero after constant folding. Go
05507       // ahead and return the folded value.
05508       if (!AddRec)
05509         return FoldedRec;
05510       break;
05511     }
05512 
05513     // If the scope is outside the addrec's loop, evaluate it by using the
05514     // loop exit value of the addrec.
05515     if (!AddRec->getLoop()->contains(L)) {
05516       // To evaluate this recurrence, we need to know how many times the AddRec
05517       // loop iterates.  Compute this now.
05518       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
05519       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
05520 
05521       // Then, evaluate the AddRec.
05522       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
05523     }
05524 
05525     return AddRec;
05526   }
05527 
05528   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
05529     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
05530     if (Op == Cast->getOperand())
05531       return Cast;  // must be loop invariant
05532     return getZeroExtendExpr(Op, Cast->getType());
05533   }
05534 
05535   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
05536     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
05537     if (Op == Cast->getOperand())
05538       return Cast;  // must be loop invariant
05539     return getSignExtendExpr(Op, Cast->getType());
05540   }
05541 
05542   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
05543     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
05544     if (Op == Cast->getOperand())
05545       return Cast;  // must be loop invariant
05546     return getTruncateExpr(Op, Cast->getType());
05547   }
05548 
05549   llvm_unreachable("Unknown SCEV type!");
05550 }
05551 
05552 /// getSCEVAtScope - This is a convenience function which does
05553 /// getSCEVAtScope(getSCEV(V), L).
05554 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
05555   return getSCEVAtScope(getSCEV(V), L);
05556 }
05557 
05558 /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
05559 /// following equation:
05560 ///
05561 ///     A * X = B (mod N)
05562 ///
05563 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
05564 /// A and B isn't important.
05565 ///
05566 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
05567 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
05568                                                ScalarEvolution &SE) {
05569   uint32_t BW = A.getBitWidth();
05570   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
05571   assert(A != 0 && "A must be non-zero.");
05572 
05573   // 1. D = gcd(A, N)
05574   //
05575   // The gcd of A and N may have only one prime factor: 2. The number of
05576   // trailing zeros in A is its multiplicity
05577   uint32_t Mult2 = A.countTrailingZeros();
05578   // D = 2^Mult2
05579 
05580   // 2. Check if B is divisible by D.
05581   //
05582   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
05583   // is not less than multiplicity of this prime factor for D.
05584   if (B.countTrailingZeros() < Mult2)
05585     return SE.getCouldNotCompute();
05586 
05587   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
05588   // modulo (N / D).
05589   //
05590   // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
05591   // bit width during computations.
05592   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
05593   APInt Mod(BW + 1, 0);
05594   Mod.setBit(BW - Mult2);  // Mod = N / D
05595   APInt I = AD.multiplicativeInverse(Mod);
05596 
05597   // 4. Compute the minimum unsigned root of the equation:
05598   // I * (B / D) mod (N / D)
05599   APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
05600 
05601   // The result is guaranteed to be less than 2^BW so we may truncate it to BW
05602   // bits.
05603   return SE.getConstant(Result.trunc(BW));
05604 }
05605 
05606 /// SolveQuadraticEquation - Find the roots of the quadratic equation for the
05607 /// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
05608 /// might be the same) or two SCEVCouldNotCompute objects.
05609 ///
05610 static std::pair<const SCEV *,const SCEV *>
05611 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
05612   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
05613   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
05614   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
05615   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
05616 
05617   // We currently can only solve this if the coefficients are constants.
05618   if (!LC || !MC || !NC) {
05619     const SCEV *CNC = SE.getCouldNotCompute();
05620     return std::make_pair(CNC, CNC);
05621   }
05622 
05623   uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
05624   const APInt &L = LC->getValue()->getValue();
05625   const APInt &M = MC->getValue()->getValue();
05626   const APInt &N = NC->getValue()->getValue();
05627   APInt Two(BitWidth, 2);
05628   APInt Four(BitWidth, 4);
05629 
05630   {
05631     using namespace APIntOps;
05632     const APInt& C = L;
05633     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
05634     // The B coefficient is M-N/2
05635     APInt B(M);
05636     B -= sdiv(N,Two);
05637 
05638     // The A coefficient is N/2
05639     APInt A(N.sdiv(Two));
05640 
05641     // Compute the B^2-4ac term.
05642     APInt SqrtTerm(B);
05643     SqrtTerm *= B;
05644     SqrtTerm -= Four * (A * C);
05645 
05646     if (SqrtTerm.isNegative()) {
05647       // The loop is provably infinite.
05648       const SCEV *CNC = SE.getCouldNotCompute();
05649       return std::make_pair(CNC, CNC);
05650     }
05651 
05652     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
05653     // integer value or else APInt::sqrt() will assert.
05654     APInt SqrtVal(SqrtTerm.sqrt());
05655 
05656     // Compute the two solutions for the quadratic formula.
05657     // The divisions must be performed as signed divisions.
05658     APInt NegB(-B);
05659     APInt TwoA(A << 1);
05660     if (TwoA.isMinValue()) {
05661       const SCEV *CNC = SE.getCouldNotCompute();
05662       return std::make_pair(CNC, CNC);
05663     }
05664 
05665     LLVMContext &Context = SE.getContext();
05666 
05667     ConstantInt *Solution1 =
05668       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
05669     ConstantInt *Solution2 =
05670       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
05671 
05672     return std::make_pair(SE.getConstant(Solution1),
05673                           SE.getConstant(Solution2));
05674   } // end APIntOps namespace
05675 }
05676 
05677 /// HowFarToZero - Return the number of times a backedge comparing the specified
05678 /// value to zero will execute.  If not computable, return CouldNotCompute.
05679 ///
05680 /// This is only used for loops with a "x != y" exit test. The exit condition is
05681 /// now expressed as a single expression, V = x-y. So the exit test is
05682 /// effectively V != 0.  We know and take advantage of the fact that this
05683 /// expression only being used in a comparison by zero context.
05684 ScalarEvolution::ExitLimit
05685 ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr) {
05686   // If the value is a constant
05687   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
05688     // If the value is already zero, the branch will execute zero times.
05689     if (C->getValue()->isZero()) return C;
05690     return getCouldNotCompute();  // Otherwise it will loop infinitely.
05691   }
05692 
05693   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
05694   if (!AddRec || AddRec->getLoop() != L)
05695     return getCouldNotCompute();
05696 
05697   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
05698   // the quadratic equation to solve it.
05699   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
05700     std::pair<const SCEV *,const SCEV *> Roots =
05701       SolveQuadraticEquation(AddRec, *this);
05702     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
05703     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
05704     if (R1 && R2) {
05705 #if 0
05706       dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
05707              << "  sol#2: " << *R2 << "\n";
05708 #endif
05709       // Pick the smallest positive root value.
05710       if (ConstantInt *CB =
05711           dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
05712                                                       R1->getValue(),
05713                                                       R2->getValue()))) {
05714         if (CB->getZExtValue() == false)
05715           std::swap(R1, R2);   // R1 is the minimum root now.
05716 
05717         // We can only use this value if the chrec ends up with an exact zero
05718         // value at this index.  When solving for "X*X != 5", for example, we
05719         // should not accept a root of 2.
05720         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
05721         if (Val->isZero())
05722           return R1;  // We found a quadratic root!
05723       }
05724     }
05725     return getCouldNotCompute();
05726   }
05727 
05728   // Otherwise we can only handle this if it is affine.
05729   if (!AddRec->isAffine())
05730     return getCouldNotCompute();
05731 
05732   // If this is an affine expression, the execution count of this branch is
05733   // the minimum unsigned root of the following equation:
05734   //
05735   //     Start + Step*N = 0 (mod 2^BW)
05736   //
05737   // equivalent to:
05738   //
05739   //             Step*N = -Start (mod 2^BW)
05740   //
05741   // where BW is the common bit width of Start and Step.
05742 
05743   // Get the initial value for the loop.
05744   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
05745   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
05746 
05747   // For now we handle only constant steps.
05748   //
05749   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
05750   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
05751   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
05752   // We have not yet seen any such cases.
05753   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
05754   if (!StepC || StepC->getValue()->equalsInt(0))
05755     return getCouldNotCompute();
05756 
05757   // For positive steps (counting up until unsigned overflow):
05758   //   N = -Start/Step (as unsigned)
05759   // For negative steps (counting down to zero):
05760   //   N = Start/-Step
05761   // First compute the unsigned distance from zero in the direction of Step.
05762   bool CountDown = StepC->getValue()->getValue().isNegative();
05763   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
05764 
05765   // Handle unitary steps, which cannot wraparound.
05766   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
05767   //   N = Distance (as unsigned)
05768   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
05769     ConstantRange CR = getUnsignedRange(Start);
05770     const SCEV *MaxBECount;
05771     if (!CountDown && CR.getUnsignedMin().isMinValue())
05772       // When counting up, the worst starting value is 1, not 0.
05773       MaxBECount = CR.getUnsignedMax().isMinValue()
05774         ? getConstant(APInt::getMinValue(CR.getBitWidth()))
05775         : getConstant(APInt::getMaxValue(CR.getBitWidth()));
05776     else
05777       MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
05778                                          : -CR.getUnsignedMin());
05779     return ExitLimit(Distance, MaxBECount, /*MustExit=*/true);
05780   }
05781 
05782   // If the recurrence is known not to wraparound, unsigned divide computes the
05783   // back edge count. (Ideally we would have an "isexact" bit for udiv). We know
05784   // that the value will either become zero (and thus the loop terminates), that
05785   // the loop will terminate through some other exit condition first, or that
05786   // the loop has undefined behavior.  This means we can't "miss" the exit
05787   // value, even with nonunit stride, and exit later via the same branch. Note
05788   // that we can skip this exit if loop later exits via a different
05789   // branch. Hence MustExit=false.
05790   //
05791   // This is only valid for expressions that directly compute the loop exit. It
05792   // is invalid for subexpressions in which the loop may exit through this
05793   // branch even if this subexpression is false. In that case, the trip count
05794   // computed by this udiv could be smaller than the number of well-defined
05795   // iterations.
05796   if (!IsSubExpr && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
05797     const SCEV *Exact =
05798       getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
05799     return ExitLimit(Exact, Exact, /*MustExit=*/false);
05800   }
05801 
05802   // If Step is a power of two that evenly divides Start we know that the loop
05803   // will always terminate.  Start may not be a constant so we just have the
05804   // number of trailing zeros available.  This is safe even in presence of
05805   // overflow as the recurrence will overflow to exactly 0.
05806   const APInt &StepV = StepC->getValue()->getValue();
05807   if (StepV.isPowerOf2() &&
05808       GetMinTrailingZeros(getNegativeSCEV(Start)) >= StepV.countTrailingZeros())
05809     return getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
05810 
05811   // Then, try to solve the above equation provided that Start is constant.
05812   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
05813     return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
05814                                         -StartC->getValue()->getValue(),
05815                                         *this);
05816   return getCouldNotCompute();
05817 }
05818 
05819 /// HowFarToNonZero - Return the number of times a backedge checking the
05820 /// specified value for nonzero will execute.  If not computable, return
05821 /// CouldNotCompute
05822 ScalarEvolution::ExitLimit
05823 ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
05824   // Loops that look like: while (X == 0) are very strange indeed.  We don't
05825   // handle them yet except for the trivial case.  This could be expanded in the
05826   // future as needed.
05827 
05828   // If the value is a constant, check to see if it is known to be non-zero
05829   // already.  If so, the backedge will execute zero times.
05830   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
05831     if (!C->getValue()->isNullValue())
05832       return getConstant(C->getType(), 0);
05833     return getCouldNotCompute();  // Otherwise it will loop infinitely.
05834   }
05835 
05836   // We could implement others, but I really doubt anyone writes loops like
05837   // this, and if they did, they would already be constant folded.
05838   return getCouldNotCompute();
05839 }
05840 
05841 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
05842 /// (which may not be an immediate predecessor) which has exactly one
05843 /// successor from which BB is reachable, or null if no such block is
05844 /// found.
05845 ///
05846 std::pair<BasicBlock *, BasicBlock *>
05847 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
05848   // If the block has a unique predecessor, then there is no path from the
05849   // predecessor to the block that does not go through the direct edge
05850   // from the predecessor to the block.
05851   if (BasicBlock *Pred = BB->getSinglePredecessor())
05852     return std::make_pair(Pred, BB);
05853 
05854   // A loop's header is defined to be a block that dominates the loop.
05855   // If the header has a unique predecessor outside the loop, it must be
05856   // a block that has exactly one successor that can reach the loop.
05857   if (Loop *L = LI->getLoopFor(BB))
05858     return std::make_pair(L->getLoopPredecessor(), L->getHeader());
05859 
05860   return std::pair<BasicBlock *, BasicBlock *>();
05861 }
05862 
05863 /// HasSameValue - SCEV structural equivalence is usually sufficient for
05864 /// testing whether two expressions are equal, however for the purposes of
05865 /// looking for a condition guarding a loop, it can be useful to be a little
05866 /// more general, since a front-end may have replicated the controlling
05867 /// expression.
05868 ///
05869 static bool HasSameValue(const SCEV *A, const SCEV *B) {
05870   // Quick check to see if they are the same SCEV.
05871   if (A == B) return true;
05872 
05873   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
05874   // two different instructions with the same value. Check for this case.
05875   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
05876     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
05877       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
05878         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
05879           if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
05880             return true;
05881 
05882   // Otherwise assume they may have a different value.
05883   return false;
05884 }
05885 
05886 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
05887 /// predicate Pred. Return true iff any changes were made.
05888 ///
05889 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
05890                                            const SCEV *&LHS, const SCEV *&RHS,
05891                                            unsigned Depth) {
05892   bool Changed = false;
05893 
05894   // If we hit the max recursion limit bail out.
05895   if (Depth >= 3)
05896     return false;
05897 
05898   // Canonicalize a constant to the right side.
05899   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
05900     // Check for both operands constant.
05901     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
05902       if (ConstantExpr::getICmp(Pred,
05903                                 LHSC->getValue(),
05904                                 RHSC->getValue())->isNullValue())
05905         goto trivially_false;
05906       else
05907         goto trivially_true;
05908     }
05909     // Otherwise swap the operands to put the constant on the right.
05910     std::swap(LHS, RHS);
05911     Pred = ICmpInst::getSwappedPredicate(Pred);
05912     Changed = true;
05913   }
05914 
05915   // If we're comparing an addrec with a value which is loop-invariant in the
05916   // addrec's loop, put the addrec on the left. Also make a dominance check,
05917   // as both operands could be addrecs loop-invariant in each other's loop.
05918   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
05919     const Loop *L = AR->getLoop();
05920     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
05921       std::swap(LHS, RHS);
05922       Pred = ICmpInst::getSwappedPredicate(Pred);
05923       Changed = true;
05924     }
05925   }
05926 
05927   // If there's a constant operand, canonicalize comparisons with boundary
05928   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
05929   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
05930     const APInt &RA = RC->getValue()->getValue();
05931     switch (Pred) {
05932     default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
05933     case ICmpInst::ICMP_EQ:
05934     case ICmpInst::ICMP_NE:
05935       // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
05936       if (!RA)
05937         if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
05938           if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
05939             if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
05940                 ME->getOperand(0)->isAllOnesValue()) {
05941               RHS = AE->getOperand(1);
05942               LHS = ME->getOperand(1);
05943               Changed = true;
05944             }
05945       break;
05946     case ICmpInst::ICMP_UGE:
05947       if ((RA - 1).isMinValue()) {
05948         Pred = ICmpInst::ICMP_NE;
05949         RHS = getConstant(RA - 1);
05950         Changed = true;
05951         break;
05952       }
05953       if (RA.isMaxValue()) {
05954         Pred = ICmpInst::ICMP_EQ;
05955         Changed = true;
05956         break;
05957       }
05958       if (RA.isMinValue()) goto trivially_true;
05959 
05960       Pred = ICmpInst::ICMP_UGT;
05961       RHS = getConstant(RA - 1);
05962       Changed = true;
05963       break;
05964     case ICmpInst::ICMP_ULE:
05965       if ((RA + 1).isMaxValue()) {
05966         Pred = ICmpInst::ICMP_NE;
05967         RHS = getConstant(RA + 1);
05968         Changed = true;
05969         break;
05970       }
05971       if (RA.isMinValue()) {
05972         Pred = ICmpInst::ICMP_EQ;
05973         Changed = true;
05974         break;
05975       }
05976       if (RA.isMaxValue()) goto trivially_true;
05977 
05978       Pred = ICmpInst::ICMP_ULT;
05979       RHS = getConstant(RA + 1);
05980       Changed = true;
05981       break;
05982     case ICmpInst::ICMP_SGE:
05983       if ((RA - 1).isMinSignedValue()) {
05984         Pred = ICmpInst::ICMP_NE;
05985         RHS = getConstant(RA - 1);
05986         Changed = true;
05987         break;
05988       }
05989       if (RA.isMaxSignedValue()) {
05990         Pred = ICmpInst::ICMP_EQ;
05991         Changed = true;
05992         break;
05993       }
05994       if (RA.isMinSignedValue()) goto trivially_true;
05995 
05996       Pred = ICmpInst::ICMP_SGT;
05997       RHS = getConstant(RA - 1);
05998       Changed = true;
05999       break;
06000     case ICmpInst::ICMP_SLE:
06001       if ((RA + 1).isMaxSignedValue()) {
06002         Pred = ICmpInst::ICMP_NE;
06003         RHS = getConstant(RA + 1);
06004         Changed = true;
06005         break;
06006       }
06007       if (RA.isMinSignedValue()) {
06008         Pred = ICmpInst::ICMP_EQ;
06009         Changed = true;
06010         break;
06011       }
06012       if (RA.isMaxSignedValue()) goto trivially_true;
06013 
06014       Pred = ICmpInst::ICMP_SLT;
06015       RHS = getConstant(RA + 1);
06016       Changed = true;
06017       break;
06018     case ICmpInst::ICMP_UGT:
06019       if (RA.isMinValue()) {
06020         Pred = ICmpInst::ICMP_NE;
06021         Changed = true;
06022         break;
06023       }
06024       if ((RA + 1).isMaxValue()) {
06025         Pred = ICmpInst::ICMP_EQ;
06026         RHS = getConstant(RA + 1);
06027         Changed = true;
06028         break;
06029       }
06030       if (RA.isMaxValue()) goto trivially_false;
06031       break;
06032     case ICmpInst::ICMP_ULT:
06033       if (RA.isMaxValue()) {
06034         Pred = ICmpInst::ICMP_NE;
06035         Changed = true;
06036         break;
06037       }
06038       if ((RA - 1).isMinValue()) {
06039         Pred = ICmpInst::ICMP_EQ;
06040         RHS = getConstant(RA - 1);
06041         Changed = true;
06042         break;
06043       }
06044       if (RA.isMinValue()) goto trivially_false;
06045       break;
06046     case ICmpInst::ICMP_SGT:
06047       if (RA.isMinSignedValue()) {
06048         Pred = ICmpInst::ICMP_NE;
06049         Changed = true;
06050         break;
06051       }
06052       if ((RA + 1).isMaxSignedValue()) {
06053         Pred = ICmpInst::ICMP_EQ;
06054         RHS = getConstant(RA + 1);
06055         Changed = true;
06056         break;
06057       }
06058       if (RA.isMaxSignedValue()) goto trivially_false;
06059       break;
06060     case ICmpInst::ICMP_SLT:
06061       if (RA.isMaxSignedValue()) {
06062         Pred = ICmpInst::ICMP_NE;
06063         Changed = true;
06064         break;
06065       }
06066       if ((RA - 1).isMinSignedValue()) {
06067        Pred = ICmpInst::ICMP_EQ;
06068        RHS = getConstant(RA - 1);
06069         Changed = true;
06070        break;
06071       }
06072       if (RA.isMinSignedValue()) goto trivially_false;
06073       break;
06074     }
06075   }
06076 
06077   // Check for obvious equality.
06078   if (HasSameValue(LHS, RHS)) {
06079     if (ICmpInst::isTrueWhenEqual(Pred))
06080       goto trivially_true;
06081     if (ICmpInst::isFalseWhenEqual(Pred))
06082       goto trivially_false;
06083   }
06084 
06085   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
06086   // adding or subtracting 1 from one of the operands.
06087   switch (Pred) {
06088   case ICmpInst::ICMP_SLE:
06089     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
06090       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
06091                        SCEV::FlagNSW);
06092       Pred = ICmpInst::ICMP_SLT;
06093       Changed = true;
06094     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
06095       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
06096                        SCEV::FlagNSW);
06097       Pred = ICmpInst::ICMP_SLT;
06098       Changed = true;
06099     }
06100     break;
06101   case ICmpInst::ICMP_SGE:
06102     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
06103       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
06104                        SCEV::FlagNSW);
06105       Pred = ICmpInst::ICMP_SGT;
06106       Changed = true;
06107     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
06108       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
06109                        SCEV::FlagNSW);
06110       Pred = ICmpInst::ICMP_SGT;
06111       Changed = true;
06112     }
06113     break;
06114   case ICmpInst::ICMP_ULE:
06115     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
06116       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
06117                        SCEV::FlagNUW);
06118       Pred = ICmpInst::ICMP_ULT;
06119       Changed = true;
06120     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
06121       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
06122                        SCEV::FlagNUW);
06123       Pred = ICmpInst::ICMP_ULT;
06124       Changed = true;
06125     }
06126     break;
06127   case ICmpInst::ICMP_UGE:
06128     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
06129       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
06130                        SCEV::FlagNUW);
06131       Pred = ICmpInst::ICMP_UGT;
06132       Changed = true;
06133     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
06134       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
06135                        SCEV::FlagNUW);
06136       Pred = ICmpInst::ICMP_UGT;
06137       Changed = true;
06138     }
06139     break;
06140   default:
06141     break;
06142   }
06143 
06144   // TODO: More simplifications are possible here.
06145 
06146   // Recursively simplify until we either hit a recursion limit or nothing
06147   // changes.
06148   if (Changed)
06149     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
06150 
06151   return Changed;
06152 
06153 trivially_true:
06154   // Return 0 == 0.
06155   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
06156   Pred = ICmpInst::ICMP_EQ;
06157   return true;
06158 
06159 trivially_false:
06160   // Return 0 != 0.
06161   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
06162   Pred = ICmpInst::ICMP_NE;
06163   return true;
06164 }
06165 
06166 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
06167   return getSignedRange(S).getSignedMax().isNegative();
06168 }
06169 
06170 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
06171   return getSignedRange(S).getSignedMin().isStrictlyPositive();
06172 }
06173 
06174 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
06175   return !getSignedRange(S).getSignedMin().isNegative();
06176 }
06177 
06178 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
06179   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
06180 }
06181 
06182 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
06183   return isKnownNegative(S) || isKnownPositive(S);
06184 }
06185 
06186 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
06187                                        const SCEV *LHS, const SCEV *RHS) {
06188   // Canonicalize the inputs first.
06189   (void)SimplifyICmpOperands(Pred, LHS, RHS);
06190 
06191   // If LHS or RHS is an addrec, check to see if the condition is true in
06192   // every iteration of the loop.
06193   // If LHS and RHS are both addrec, both conditions must be true in
06194   // every iteration of the loop.
06195   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
06196   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
06197   bool LeftGuarded = false;
06198   bool RightGuarded = false;
06199   if (LAR) {
06200     const Loop *L = LAR->getLoop();
06201     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
06202         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
06203       if (!RAR) return true;
06204       LeftGuarded = true;
06205     }
06206   }
06207   if (RAR) {
06208     const Loop *L = RAR->getLoop();
06209     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
06210         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
06211       if (!LAR) return true;
06212       RightGuarded = true;
06213     }
06214   }
06215   if (LeftGuarded && RightGuarded)
06216     return true;
06217 
06218   // Otherwise see what can be done with known constant ranges.
06219   return isKnownPredicateWithRanges(Pred, LHS, RHS);
06220 }
06221 
06222 bool
06223 ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
06224                                             const SCEV *LHS, const SCEV *RHS) {
06225   if (HasSameValue(LHS, RHS))
06226     return ICmpInst::isTrueWhenEqual(Pred);
06227 
06228   // This code is split out from isKnownPredicate because it is called from
06229   // within isLoopEntryGuardedByCond.
06230   switch (Pred) {
06231   default:
06232     llvm_unreachable("Unexpected ICmpInst::Predicate value!");
06233   case ICmpInst::ICMP_SGT:
06234     std::swap(LHS, RHS);
06235   case ICmpInst::ICMP_SLT: {
06236     ConstantRange LHSRange = getSignedRange(LHS);
06237     ConstantRange RHSRange = getSignedRange(RHS);
06238     if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
06239       return true;
06240     if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
06241       return false;
06242     break;
06243   }
06244   case ICmpInst::ICMP_SGE:
06245     std::swap(LHS, RHS);
06246   case ICmpInst::ICMP_SLE: {
06247     ConstantRange LHSRange = getSignedRange(LHS);
06248     ConstantRange RHSRange = getSignedRange(RHS);
06249     if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
06250       return true;
06251     if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
06252       return false;
06253     break;
06254   }
06255   case ICmpInst::ICMP_UGT:
06256     std::swap(LHS, RHS);
06257   case ICmpInst::ICMP_ULT: {
06258     ConstantRange LHSRange = getUnsignedRange(LHS);
06259     ConstantRange RHSRange = getUnsignedRange(RHS);
06260     if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
06261       return true;
06262     if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
06263       return false;
06264     break;
06265   }
06266   case ICmpInst::ICMP_UGE:
06267     std::swap(LHS, RHS);
06268   case ICmpInst::ICMP_ULE: {
06269     ConstantRange LHSRange = getUnsignedRange(LHS);
06270     ConstantRange RHSRange = getUnsignedRange(RHS);
06271     if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
06272       return true;
06273     if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
06274       return false;
06275     break;
06276   }
06277   case ICmpInst::ICMP_NE: {
06278     if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
06279       return true;
06280     if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
06281       return true;
06282 
06283     const SCEV *Diff = getMinusSCEV(LHS, RHS);
06284     if (isKnownNonZero(Diff))
06285       return true;
06286     break;
06287   }
06288   case ICmpInst::ICMP_EQ:
06289     // The check at the top of the function catches the case where
06290     // the values are known to be equal.
06291     break;
06292   }
06293   return false;
06294 }
06295 
06296 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
06297 /// protected by a conditional between LHS and RHS.  This is used to
06298 /// to eliminate casts.
06299 bool
06300 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
06301                                              ICmpInst::Predicate Pred,
06302                                              const SCEV *LHS, const SCEV *RHS) {
06303   // Interpret a null as meaning no loop, where there is obviously no guard
06304   // (interprocedural conditions notwithstanding).
06305   if (!L) return true;
06306 
06307   BasicBlock *Latch = L->getLoopLatch();
06308   if (!Latch)
06309     return false;
06310 
06311   BranchInst *LoopContinuePredicate =
06312     dyn_cast<BranchInst>(Latch->getTerminator());
06313   if (!LoopContinuePredicate ||
06314       LoopContinuePredicate->isUnconditional())
06315     return false;
06316 
06317   return isImpliedCond(Pred, LHS, RHS,
06318                        LoopContinuePredicate->getCondition(),
06319                        LoopContinuePredicate->getSuccessor(0) != L->getHeader());
06320 }
06321 
06322 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
06323 /// by a conditional between LHS and RHS.  This is used to help avoid max
06324 /// expressions in loop trip counts, and to eliminate casts.
06325 bool
06326 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
06327                                           ICmpInst::Predicate Pred,
06328                                           const SCEV *LHS, const SCEV *RHS) {
06329   // Interpret a null as meaning no loop, where there is obviously no guard
06330   // (interprocedural conditions notwithstanding).
06331   if (!L) return false;
06332 
06333   // Starting at the loop predecessor, climb up the predecessor chain, as long
06334   // as there are predecessors that can be found that have unique successors
06335   // leading to the original header.
06336   for (std::pair<BasicBlock *, BasicBlock *>
06337          Pair(L->getLoopPredecessor(), L->getHeader());
06338        Pair.first;
06339        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
06340 
06341     BranchInst *LoopEntryPredicate =
06342       dyn_cast<BranchInst>(Pair.first->getTerminator());
06343     if (!LoopEntryPredicate ||
06344         LoopEntryPredicate->isUnconditional())
06345       continue;
06346 
06347     if (isImpliedCond(Pred, LHS, RHS,
06348                       LoopEntryPredicate->getCondition(),
06349                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
06350       return true;
06351   }
06352 
06353   return false;
06354 }
06355 
06356 /// RAII wrapper to prevent recursive application of isImpliedCond.
06357 /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
06358 /// currently evaluating isImpliedCond.
06359 struct MarkPendingLoopPredicate {
06360   Value *Cond;
06361   DenseSet<Value*> &LoopPreds;
06362   bool Pending;
06363 
06364   MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
06365     : Cond(C), LoopPreds(LP) {
06366     Pending = !LoopPreds.insert(Cond).second;
06367   }
06368   ~MarkPendingLoopPredicate() {
06369     if (!Pending)
06370       LoopPreds.erase(Cond);
06371   }
06372 };
06373 
06374 /// isImpliedCond - Test whether the condition described by Pred, LHS,
06375 /// and RHS is true whenever the given Cond value evaluates to true.
06376 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
06377                                     const SCEV *LHS, const SCEV *RHS,
06378                                     Value *FoundCondValue,
06379                                     bool Inverse) {
06380   MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
06381   if (Mark.Pending)
06382     return false;
06383 
06384   // Recursively handle And and Or conditions.
06385   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
06386     if (BO->getOpcode() == Instruction::And) {
06387       if (!Inverse)
06388         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
06389                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
06390     } else if (BO->getOpcode() == Instruction::Or) {
06391       if (Inverse)
06392         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
06393                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
06394     }
06395   }
06396 
06397   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
06398   if (!ICI) return false;
06399 
06400   // Bail if the ICmp's operands' types are wider than the needed type
06401   // before attempting to call getSCEV on them. This avoids infinite
06402   // recursion, since the analysis of widening casts can require loop
06403   // exit condition information for overflow checking, which would
06404   // lead back here.
06405   if (getTypeSizeInBits(LHS->getType()) <
06406       getTypeSizeInBits(ICI->getOperand(0)->getType()))
06407     return false;
06408 
06409   // Now that we found a conditional branch that dominates the loop or controls
06410   // the loop latch. Check to see if it is the comparison we are looking for.
06411   ICmpInst::Predicate FoundPred;
06412   if (Inverse)
06413     FoundPred = ICI->getInversePredicate();
06414   else
06415     FoundPred = ICI->getPredicate();
06416 
06417   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
06418   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
06419 
06420   // Balance the types. The case where FoundLHS' type is wider than
06421   // LHS' type is checked for above.
06422   if (getTypeSizeInBits(LHS->getType()) >
06423       getTypeSizeInBits(FoundLHS->getType())) {
06424     if (CmpInst::isSigned(FoundPred)) {
06425       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
06426       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
06427     } else {
06428       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
06429       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
06430     }
06431   }
06432 
06433   // Canonicalize the query to match the way instcombine will have
06434   // canonicalized the comparison.
06435   if (SimplifyICmpOperands(Pred, LHS, RHS))
06436     if (LHS == RHS)
06437       return CmpInst::isTrueWhenEqual(Pred);
06438   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
06439     if (FoundLHS == FoundRHS)
06440       return CmpInst::isFalseWhenEqual(FoundPred);
06441 
06442   // Check to see if we can make the LHS or RHS match.
06443   if (LHS == FoundRHS || RHS == FoundLHS) {
06444     if (isa<SCEVConstant>(RHS)) {
06445       std::swap(FoundLHS, FoundRHS);
06446       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
06447     } else {
06448       std::swap(LHS, RHS);
06449       Pred = ICmpInst::getSwappedPredicate(Pred);
06450     }
06451   }
06452 
06453   // Check whether the found predicate is the same as the desired predicate.
06454   if (FoundPred == Pred)
06455     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
06456 
06457   // Check whether swapping the found predicate makes it the same as the
06458   // desired predicate.
06459   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
06460     if (isa<SCEVConstant>(RHS))
06461       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
06462     else
06463       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
06464                                    RHS, LHS, FoundLHS, FoundRHS);
06465   }
06466 
06467   // Check whether the actual condition is beyond sufficient.
06468   if (FoundPred == ICmpInst::ICMP_EQ)
06469     if (ICmpInst::isTrueWhenEqual(Pred))
06470       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
06471         return true;
06472   if (Pred == ICmpInst::ICMP_NE)
06473     if (!ICmpInst::isTrueWhenEqual(FoundPred))
06474       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
06475         return true;
06476 
06477   // Otherwise assume the worst.
06478   return false;
06479 }
06480 
06481 /// isImpliedCondOperands - Test whether the condition described by Pred,
06482 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
06483 /// and FoundRHS is true.
06484 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
06485                                             const SCEV *LHS, const SCEV *RHS,
06486                                             const SCEV *FoundLHS,
06487                                             const SCEV *FoundRHS) {
06488   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
06489                                      FoundLHS, FoundRHS) ||
06490          // ~x < ~y --> x > y
06491          isImpliedCondOperandsHelper(Pred, LHS, RHS,
06492                                      getNotSCEV(FoundRHS),
06493                                      getNotSCEV(FoundLHS));
06494 }
06495 
06496 /// isImpliedCondOperandsHelper - Test whether the condition described by
06497 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
06498 /// FoundLHS, and FoundRHS is true.
06499 bool
06500 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
06501                                              const SCEV *LHS, const SCEV *RHS,
06502                                              const SCEV *FoundLHS,
06503                                              const SCEV *FoundRHS) {
06504   switch (Pred) {
06505   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
06506   case ICmpInst::ICMP_EQ:
06507   case ICmpInst::ICMP_NE:
06508     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
06509       return true;
06510     break;
06511   case ICmpInst::ICMP_SLT:
06512   case ICmpInst::ICMP_SLE:
06513     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
06514         isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
06515       return true;
06516     break;
06517   case ICmpInst::ICMP_SGT:
06518   case ICmpInst::ICMP_SGE:
06519     if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
06520         isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
06521       return true;
06522     break;
06523   case ICmpInst::ICMP_ULT:
06524   case ICmpInst::ICMP_ULE:
06525     if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
06526         isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
06527       return true;
06528     break;
06529   case ICmpInst::ICMP_UGT:
06530   case ICmpInst::ICMP_UGE:
06531     if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
06532         isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
06533       return true;
06534     break;
06535   }
06536 
06537   return false;
06538 }
06539 
06540 // Verify if an linear IV with positive stride can overflow when in a 
06541 // less-than comparison, knowing the invariant term of the comparison, the 
06542 // stride and the knowledge of NSW/NUW flags on the recurrence.
06543 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
06544                                          bool IsSigned, bool NoWrap) {
06545   if (NoWrap) return false;
06546 
06547   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
06548   const SCEV *One = getConstant(Stride->getType(), 1);
06549 
06550   if (IsSigned) {
06551     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
06552     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
06553     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
06554                                 .getSignedMax();
06555 
06556     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
06557     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
06558   }
06559 
06560   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
06561   APInt MaxValue = APInt::getMaxValue(BitWidth);
06562   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
06563                               .getUnsignedMax();
06564 
06565   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
06566   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
06567 }
06568 
06569 // Verify if an linear IV with negative stride can overflow when in a 
06570 // greater-than comparison, knowing the invariant term of the comparison,
06571 // the stride and the knowledge of NSW/NUW flags on the recurrence.
06572 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
06573                                          bool IsSigned, bool NoWrap) {
06574   if (NoWrap) return false;
06575 
06576   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
06577   const SCEV *One = getConstant(Stride->getType(), 1);
06578 
06579   if (IsSigned) {
06580     APInt MinRHS = getSignedRange(RHS).getSignedMin();
06581     APInt MinValue = APInt::getSignedMinValue(BitWidth);
06582     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
06583                                .getSignedMax();
06584 
06585     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
06586     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
06587   }
06588 
06589   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
06590   APInt MinValue = APInt::getMinValue(BitWidth);
06591   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
06592                             .getUnsignedMax();
06593 
06594   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
06595   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
06596 }
06597 
06598 // Compute the backedge taken count knowing the interval difference, the
06599 // stride and presence of the equality in the comparison.
06600 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 
06601                                             bool Equality) {
06602   const SCEV *One = getConstant(Step->getType(), 1);
06603   Delta = Equality ? getAddExpr(Delta, Step)
06604                    : getAddExpr(Delta, getMinusSCEV(Step, One));
06605   return getUDivExpr(Delta, Step);
06606 }
06607 
06608 /// HowManyLessThans - Return the number of times a backedge containing the
06609 /// specified less-than comparison will execute.  If not computable, return
06610 /// CouldNotCompute.
06611 ///
06612 /// @param IsSubExpr is true when the LHS < RHS condition does not directly
06613 /// control the branch. In this case, we can only compute an iteration count for
06614 /// a subexpression that cannot overflow before evaluating true.
06615 ScalarEvolution::ExitLimit
06616 ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
06617                                   const Loop *L, bool IsSigned,
06618                                   bool IsSubExpr) {
06619   // We handle only IV < Invariant
06620   if (!isLoopInvariant(RHS, L))
06621     return getCouldNotCompute();
06622 
06623   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
06624 
06625   // Avoid weird loops
06626   if (!IV || IV->getLoop() != L || !IV->isAffine())
06627     return getCouldNotCompute();
06628 
06629   bool NoWrap = !IsSubExpr &&
06630                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
06631 
06632   const SCEV *Stride = IV->getStepRecurrence(*this);
06633 
06634   // Avoid negative or zero stride values
06635   if (!isKnownPositive(Stride))
06636     return getCouldNotCompute();
06637 
06638   // Avoid proven overflow cases: this will ensure that the backedge taken count
06639   // will not generate any unsigned overflow. Relaxed no-overflow conditions
06640   // exploit NoWrapFlags, allowing to optimize in presence of undefined 
06641   // behaviors like the case of C language.
06642   if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
06643     return getCouldNotCompute();
06644 
06645   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
06646                                       : ICmpInst::ICMP_ULT;
06647   const SCEV *Start = IV->getStart();
06648   const SCEV *End = RHS;
06649   if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
06650     End = IsSigned ? getSMaxExpr(RHS, Start)
06651                    : getUMaxExpr(RHS, Start);
06652 
06653   const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
06654 
06655   APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
06656                             : getUnsignedRange(Start).getUnsignedMin();
06657 
06658   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
06659                              : getUnsignedRange(Stride).getUnsignedMin();
06660 
06661   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
06662   APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
06663                          : APInt::getMaxValue(BitWidth) - (MinStride - 1);
06664 
06665   // Although End can be a MAX expression we estimate MaxEnd considering only
06666   // the case End = RHS. This is safe because in the other case (End - Start)
06667   // is zero, leading to a zero maximum backedge taken count.
06668   APInt MaxEnd =
06669     IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
06670              : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
06671 
06672   const SCEV *MaxBECount;
06673   if (isa<SCEVConstant>(BECount))
06674     MaxBECount = BECount;
06675   else
06676     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
06677                                 getConstant(MinStride), false);
06678 
06679   if (isa<SCEVCouldNotCompute>(MaxBECount))
06680     MaxBECount = BECount;
06681 
06682   return ExitLimit(BECount, MaxBECount, /*MustExit=*/true);
06683 }
06684 
06685 ScalarEvolution::ExitLimit
06686 ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
06687                                      const Loop *L, bool IsSigned,
06688                                      bool IsSubExpr) {
06689   // We handle only IV > Invariant
06690   if (!isLoopInvariant(RHS, L))
06691     return getCouldNotCompute();
06692 
06693   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
06694 
06695   // Avoid weird loops
06696   if (!IV || IV->getLoop() != L || !IV->isAffine())
06697     return getCouldNotCompute();
06698 
06699   bool NoWrap = !IsSubExpr &&
06700                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
06701 
06702   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
06703 
06704   // Avoid negative or zero stride values
06705   if (!isKnownPositive(Stride))
06706     return getCouldNotCompute();
06707 
06708   // Avoid proven overflow cases: this will ensure that the backedge taken count
06709   // will not generate any unsigned overflow. Relaxed no-overflow conditions
06710   // exploit NoWrapFlags, allowing to optimize in presence of undefined 
06711   // behaviors like the case of C language.
06712   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
06713     return getCouldNotCompute();
06714 
06715   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
06716                                       : ICmpInst::ICMP_UGT;
06717 
06718   const SCEV *Start = IV->getStart();
06719   const SCEV *End = RHS;
06720   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
06721     End = IsSigned ? getSMinExpr(RHS, Start)
06722                    : getUMinExpr(RHS, Start);
06723 
06724   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
06725 
06726   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
06727                             : getUnsignedRange(Start).getUnsignedMax();
06728 
06729   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
06730                              : getUnsignedRange(Stride).getUnsignedMin();
06731 
06732   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
06733   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
06734                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
06735 
06736   // Although End can be a MIN expression we estimate MinEnd considering only
06737   // the case End = RHS. This is safe because in the other case (Start - End)
06738   // is zero, leading to a zero maximum backedge taken count.
06739   APInt MinEnd =
06740     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
06741              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
06742 
06743 
06744   const SCEV *MaxBECount = getCouldNotCompute();
06745   if (isa<SCEVConstant>(BECount))
06746     MaxBECount = BECount;
06747   else
06748     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), 
06749                                 getConstant(MinStride), false);
06750 
06751   if (isa<SCEVCouldNotCompute>(MaxBECount))
06752     MaxBECount = BECount;
06753 
06754   return ExitLimit(BECount, MaxBECount, /*MustExit=*/true);
06755 }
06756 
06757 /// getNumIterationsInRange - Return the number of iterations of this loop that
06758 /// produce values in the specified constant range.  Another way of looking at
06759 /// this is that it returns the first iteration number where the value is not in
06760 /// the condition, thus computing the exit count. If the iteration count can't
06761 /// be computed, an instance of SCEVCouldNotCompute is returned.
06762 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
06763                                                     ScalarEvolution &SE) const {
06764   if (Range.isFullSet())  // Infinite loop.
06765     return SE.getCouldNotCompute();
06766 
06767   // If the start is a non-zero constant, shift the range to simplify things.
06768   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
06769     if (!SC->getValue()->isZero()) {
06770       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
06771       Operands[0] = SE.getConstant(SC->getType(), 0);
06772       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
06773                                              getNoWrapFlags(FlagNW));
06774       if (const SCEVAddRecExpr *ShiftedAddRec =
06775             dyn_cast<SCEVAddRecExpr>(Shifted))
06776         return ShiftedAddRec->getNumIterationsInRange(
06777                            Range.subtract(SC->getValue()->getValue()), SE);
06778       // This is strange and shouldn't happen.
06779       return SE.getCouldNotCompute();
06780     }
06781 
06782   // The only time we can solve this is when we have all constant indices.
06783   // Otherwise, we cannot determine the overflow conditions.
06784   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
06785     if (!isa<SCEVConstant>(getOperand(i)))
06786       return SE.getCouldNotCompute();
06787 
06788 
06789   // Okay at this point we know that all elements of the chrec are constants and
06790   // that the start element is zero.
06791 
06792   // First check to see if the range contains zero.  If not, the first
06793   // iteration exits.
06794   unsigned BitWidth = SE.getTypeSizeInBits(getType());
06795   if (!Range.contains(APInt(BitWidth, 0)))
06796     return SE.getConstant(getType(), 0);
06797 
06798   if (isAffine()) {
06799     // If this is an affine expression then we have this situation:
06800     //   Solve {0,+,A} in Range  ===  Ax in Range
06801 
06802     // We know that zero is in the range.  If A is positive then we know that
06803     // the upper value of the range must be the first possible exit value.
06804     // If A is negative then the lower of the range is the last possible loop
06805     // value.  Also note that we already checked for a full range.
06806     APInt One(BitWidth,1);
06807     APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
06808     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
06809 
06810     // The exit value should be (End+A)/A.
06811     APInt ExitVal = (End + A).udiv(A);
06812     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
06813 
06814     // Evaluate at the exit value.  If we really did fall out of the valid
06815     // range, then we computed our trip count, otherwise wrap around or other
06816     // things must have happened.
06817     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
06818     if (Range.contains(Val->getValue()))
06819       return SE.getCouldNotCompute();  // Something strange happened
06820 
06821     // Ensure that the previous value is in the range.  This is a sanity check.
06822     assert(Range.contains(
06823            EvaluateConstantChrecAtConstant(this,
06824            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
06825            "Linear scev computation is off in a bad way!");
06826     return SE.getConstant(ExitValue);
06827   } else if (isQuadratic()) {
06828     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
06829     // quadratic equation to solve it.  To do this, we must frame our problem in
06830     // terms of figuring out when zero is crossed, instead of when
06831     // Range.getUpper() is crossed.
06832     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
06833     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
06834     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
06835                                              // getNoWrapFlags(FlagNW)
06836                                              FlagAnyWrap);
06837 
06838     // Next, solve the constructed addrec
06839     std::pair<const SCEV *,const SCEV *> Roots =
06840       SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
06841     const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
06842     const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
06843     if (R1) {
06844       // Pick the smallest positive root value.
06845       if (ConstantInt *CB =
06846           dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
06847                          R1->getValue(), R2->getValue()))) {
06848         if (CB->getZExtValue() == false)
06849           std::swap(R1, R2);   // R1 is the minimum root now.
06850 
06851         // Make sure the root is not off by one.  The returned iteration should
06852         // not be in the range, but the previous one should be.  When solving
06853         // for "X*X < 5", for example, we should not return a root of 2.
06854         ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
06855                                                              R1->getValue(),
06856                                                              SE);
06857         if (Range.contains(R1Val->getValue())) {
06858           // The next iteration must be out of the range...
06859           ConstantInt *NextVal =
06860                 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
06861 
06862           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
06863           if (!Range.contains(R1Val->getValue()))
06864             return SE.getConstant(NextVal);
06865           return SE.getCouldNotCompute();  // Something strange happened
06866         }
06867 
06868         // If R1 was not in the range, then it is a good return value.  Make
06869         // sure that R1-1 WAS in the range though, just in case.
06870         ConstantInt *NextVal =
06871                ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
06872         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
06873         if (Range.contains(R1Val->getValue()))
06874           return R1;
06875         return SE.getCouldNotCompute();  // Something strange happened
06876       }
06877     }
06878   }
06879 
06880   return SE.getCouldNotCompute();
06881 }
06882 
06883 namespace {
06884 struct FindUndefs {
06885   bool Found;
06886   FindUndefs() : Found(false) {}
06887 
06888   bool follow(const SCEV *S) {
06889     if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
06890       if (isa<UndefValue>(C->getValue()))
06891         Found = true;
06892     } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
06893       if (isa<UndefValue>(C->getValue()))
06894         Found = true;
06895     }
06896 
06897     // Keep looking if we haven't found it yet.
06898     return !Found;
06899   }
06900   bool isDone() const {
06901     // Stop recursion if we have found an undef.
06902     return Found;
06903   }
06904 };
06905 }
06906 
06907 // Return true when S contains at least an undef value.
06908 static inline bool
06909 containsUndefs(const SCEV *S) {
06910   FindUndefs F;
06911   SCEVTraversal<FindUndefs> ST(F);
06912   ST.visitAll(S);
06913 
06914   return F.Found;
06915 }
06916 
06917 namespace {
06918 // Collect all steps of SCEV expressions.
06919 struct SCEVCollectStrides {
06920   ScalarEvolution &SE;
06921   SmallVectorImpl<const SCEV *> &Strides;
06922 
06923   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
06924       : SE(SE), Strides(S) {}
06925 
06926   bool follow(const SCEV *S) {
06927     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
06928       Strides.push_back(AR->getStepRecurrence(SE));
06929     return true;
06930   }
06931   bool isDone() const { return false; }
06932 };
06933 
06934 // Collect all SCEVUnknown and SCEVMulExpr expressions.
06935 struct SCEVCollectTerms {
06936   SmallVectorImpl<const SCEV *> &Terms;
06937 
06938   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
06939       : Terms(T) {}
06940 
06941   bool follow(const SCEV *S) {
06942     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
06943       if (!containsUndefs(S))
06944         Terms.push_back(S);
06945 
06946       // Stop recursion: once we collected a term, do not walk its operands.
06947       return false;
06948     }
06949 
06950     // Keep looking.
06951     return true;
06952   }
06953   bool isDone() const { return false; }
06954 };
06955 }
06956 
06957 /// Find parametric terms in this SCEVAddRecExpr.
06958 void SCEVAddRecExpr::collectParametricTerms(
06959     ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
06960   SmallVector<const SCEV *, 4> Strides;
06961   SCEVCollectStrides S