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