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