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