LLVM API Documentation

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