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