LCOV - code coverage report
Current view: top level - lib/Analysis - ScalarEvolution.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 4208 4428 95.0 %
Date: 2018-06-17 00:07:59 Functions: 346 354 97.7 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file contains the implementation of the scalar evolution analysis
      11             : // engine, which is used primarily to analyze expressions involving induction
      12             : // variables in loops.
      13             : //
      14             : // There are several aspects to this library.  First is the representation of
      15             : // scalar expressions, which are represented as subclasses of the SCEV class.
      16             : // These classes are used to represent certain types of subexpressions that we
      17             : // can handle. We only create one SCEV of a particular shape, so
      18             : // pointer-comparisons for equality are legal.
      19             : //
      20             : // One important aspect of the SCEV objects is that they are never cyclic, even
      21             : // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
      22             : // the PHI node is one of the idioms that we can represent (e.g., a polynomial
      23             : // recurrence) then we represent it directly as a recurrence node, otherwise we
      24             : // represent it as a SCEVUnknown node.
      25             : //
      26             : // In addition to being able to represent expressions of various types, we also
      27             : // have folders that are used to build the *canonical* representation for a
      28             : // particular expression.  These folders are capable of using a variety of
      29             : // rewrite rules to simplify the expressions.
      30             : //
      31             : // Once the folders are defined, we can implement the more interesting
      32             : // higher-level code, such as the code that recognizes PHI nodes of various
      33             : // types, computes the execution count of a loop, etc.
      34             : //
      35             : // TODO: We should use these routines and value representations to implement
      36             : // dependence analysis!
      37             : //
      38             : //===----------------------------------------------------------------------===//
      39             : //
      40             : // There are several good references for the techniques used in this analysis.
      41             : //
      42             : //  Chains of recurrences -- a method to expedite the evaluation
      43             : //  of closed-form functions
      44             : //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
      45             : //
      46             : //  On computational properties of chains of recurrences
      47             : //  Eugene V. Zima
      48             : //
      49             : //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
      50             : //  Robert A. van Engelen
      51             : //
      52             : //  Efficient Symbolic Analysis for Optimizing Compilers
      53             : //  Robert A. van Engelen
      54             : //
      55             : //  Using the chains of recurrences algebra for data dependence testing and
      56             : //  induction variable substitution
      57             : //  MS Thesis, Johnie Birch
      58             : //
      59             : //===----------------------------------------------------------------------===//
      60             : 
      61             : #include "llvm/Analysis/ScalarEvolution.h"
      62             : #include "llvm/ADT/APInt.h"
      63             : #include "llvm/ADT/ArrayRef.h"
      64             : #include "llvm/ADT/DenseMap.h"
      65             : #include "llvm/ADT/DepthFirstIterator.h"
      66             : #include "llvm/ADT/EquivalenceClasses.h"
      67             : #include "llvm/ADT/FoldingSet.h"
      68             : #include "llvm/ADT/None.h"
      69             : #include "llvm/ADT/Optional.h"
      70             : #include "llvm/ADT/STLExtras.h"
      71             : #include "llvm/ADT/ScopeExit.h"
      72             : #include "llvm/ADT/Sequence.h"
      73             : #include "llvm/ADT/SetVector.h"
      74             : #include "llvm/ADT/SmallPtrSet.h"
      75             : #include "llvm/ADT/SmallSet.h"
      76             : #include "llvm/ADT/SmallVector.h"
      77             : #include "llvm/ADT/Statistic.h"
      78             : #include "llvm/ADT/StringRef.h"
      79             : #include "llvm/Analysis/AssumptionCache.h"
      80             : #include "llvm/Analysis/ConstantFolding.h"
      81             : #include "llvm/Analysis/InstructionSimplify.h"
      82             : #include "llvm/Analysis/LoopInfo.h"
      83             : #include "llvm/Analysis/ScalarEvolutionExpressions.h"
      84             : #include "llvm/Analysis/TargetLibraryInfo.h"
      85             : #include "llvm/Analysis/ValueTracking.h"
      86             : #include "llvm/Config/llvm-config.h"
      87             : #include "llvm/IR/Argument.h"
      88             : #include "llvm/IR/BasicBlock.h"
      89             : #include "llvm/IR/CFG.h"
      90             : #include "llvm/IR/CallSite.h"
      91             : #include "llvm/IR/Constant.h"
      92             : #include "llvm/IR/ConstantRange.h"
      93             : #include "llvm/IR/Constants.h"
      94             : #include "llvm/IR/DataLayout.h"
      95             : #include "llvm/IR/DerivedTypes.h"
      96             : #include "llvm/IR/Dominators.h"
      97             : #include "llvm/IR/Function.h"
      98             : #include "llvm/IR/GlobalAlias.h"
      99             : #include "llvm/IR/GlobalValue.h"
     100             : #include "llvm/IR/GlobalVariable.h"
     101             : #include "llvm/IR/InstIterator.h"
     102             : #include "llvm/IR/InstrTypes.h"
     103             : #include "llvm/IR/Instruction.h"
     104             : #include "llvm/IR/Instructions.h"
     105             : #include "llvm/IR/IntrinsicInst.h"
     106             : #include "llvm/IR/Intrinsics.h"
     107             : #include "llvm/IR/LLVMContext.h"
     108             : #include "llvm/IR/Metadata.h"
     109             : #include "llvm/IR/Operator.h"
     110             : #include "llvm/IR/PatternMatch.h"
     111             : #include "llvm/IR/Type.h"
     112             : #include "llvm/IR/Use.h"
     113             : #include "llvm/IR/User.h"
     114             : #include "llvm/IR/Value.h"
     115             : #include "llvm/Pass.h"
     116             : #include "llvm/Support/Casting.h"
     117             : #include "llvm/Support/CommandLine.h"
     118             : #include "llvm/Support/Compiler.h"
     119             : #include "llvm/Support/Debug.h"
     120             : #include "llvm/Support/ErrorHandling.h"
     121             : #include "llvm/Support/KnownBits.h"
     122             : #include "llvm/Support/SaveAndRestore.h"
     123             : #include "llvm/Support/raw_ostream.h"
     124             : #include <algorithm>
     125             : #include <cassert>
     126             : #include <climits>
     127             : #include <cstddef>
     128             : #include <cstdint>
     129             : #include <cstdlib>
     130             : #include <map>
     131             : #include <memory>
     132             : #include <tuple>
     133             : #include <utility>
     134             : #include <vector>
     135             : 
     136             : using namespace llvm;
     137             : 
     138             : #define DEBUG_TYPE "scalar-evolution"
     139             : 
     140             : STATISTIC(NumArrayLenItCounts,
     141             :           "Number of trip counts computed with array length");
     142             : STATISTIC(NumTripCountsComputed,
     143             :           "Number of loops with predictable loop counts");
     144             : STATISTIC(NumTripCountsNotComputed,
     145             :           "Number of loops without predictable loop counts");
     146             : STATISTIC(NumBruteForceTripCountsComputed,
     147             :           "Number of loops with trip counts computed by force");
     148             : 
     149             : static cl::opt<unsigned>
     150      101169 : MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
     151      101169 :                         cl::desc("Maximum number of iterations SCEV will "
     152             :                                  "symbolically execute a constant "
     153             :                                  "derived loop"),
     154      303507 :                         cl::init(100));
     155             : 
     156             : // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
     157      101169 : static cl::opt<bool> VerifySCEV(
     158             :     "verify-scev", cl::Hidden,
     159      101169 :     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
     160             : static cl::opt<bool>
     161      101169 :     VerifySCEVMap("verify-scev-maps", cl::Hidden,
     162      101169 :                   cl::desc("Verify no dangling value in ScalarEvolution's "
     163      101169 :                            "ExprValueMap (slow)"));
     164             : 
     165      101169 : static cl::opt<unsigned> MulOpsInlineThreshold(
     166             :     "scev-mulops-inline-threshold", cl::Hidden,
     167      101169 :     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
     168      303507 :     cl::init(32));
     169             : 
     170      101169 : static cl::opt<unsigned> AddOpsInlineThreshold(
     171             :     "scev-addops-inline-threshold", cl::Hidden,
     172      101169 :     cl::desc("Threshold for inlining addition operands into a SCEV"),
     173      303507 :     cl::init(500));
     174             : 
     175      101169 : static cl::opt<unsigned> MaxSCEVCompareDepth(
     176             :     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
     177      101169 :     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
     178      303507 :     cl::init(32));
     179             : 
     180      101169 : static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
     181             :     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
     182      101169 :     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
     183      303507 :     cl::init(2));
     184             : 
     185      101169 : static cl::opt<unsigned> MaxValueCompareDepth(
     186             :     "scalar-evolution-max-value-compare-depth", cl::Hidden,
     187      101169 :     cl::desc("Maximum depth of recursive value complexity comparisons"),
     188      303507 :     cl::init(2));
     189             : 
     190             : static cl::opt<unsigned>
     191      101169 :     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
     192      101169 :                   cl::desc("Maximum depth of recursive arithmetics"),
     193      303507 :                   cl::init(32));
     194             : 
     195      101169 : static cl::opt<unsigned> MaxConstantEvolvingDepth(
     196             :     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
     197      202338 :     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
     198             : 
     199             : static cl::opt<unsigned>
     200      101169 :     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
     201      101169 :                 cl::desc("Maximum depth of recursive SExt/ZExt"),
     202      303507 :                 cl::init(8));
     203             : 
     204             : static cl::opt<unsigned>
     205      101169 :     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
     206      101169 :                   cl::desc("Max coefficients in AddRec during evolving"),
     207      303507 :                   cl::init(16));
     208             : 
     209             : //===----------------------------------------------------------------------===//
     210             : //                           SCEV class definitions
     211             : //===----------------------------------------------------------------------===//
     212             : 
     213             : //===----------------------------------------------------------------------===//
     214             : // Implementation of the SCEV class.
     215             : //
     216             : 
     217             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     218             : LLVM_DUMP_METHOD void SCEV::dump() const {
     219             :   print(dbgs());
     220             :   dbgs() << '\n';
     221             : }
     222             : #endif
     223             : 
     224       50782 : void SCEV::print(raw_ostream &OS) const {
     225      101564 :   switch (static_cast<SCEVTypes>(getSCEVType())) {
     226             :   case scConstant:
     227       17842 :     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
     228       17842 :     return;
     229             :   case scTruncate: {
     230             :     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
     231        1245 :     const SCEV *Op = Trunc->getOperand();
     232        2490 :     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
     233        2490 :        << *Trunc->getType() << ")";
     234        1245 :     return;
     235             :   }
     236             :   case scZeroExtend: {
     237             :     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
     238        2516 :     const SCEV *Op = ZExt->getOperand();
     239        5032 :     OS << "(zext " << *Op->getType() << " " << *Op << " to "
     240        5032 :        << *ZExt->getType() << ")";
     241        2516 :     return;
     242             :   }
     243             :   case scSignExtend: {
     244             :     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
     245         452 :     const SCEV *Op = SExt->getOperand();
     246         904 :     OS << "(sext " << *Op->getType() << " " << *Op << " to "
     247         904 :        << *SExt->getType() << ")";
     248         452 :     return;
     249             :   }
     250             :   case scAddRecExpr: {
     251             :     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
     252        6888 :     OS << "{" << *AR->getOperand(0);
     253        7216 :     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
     254        7544 :       OS << ",+," << *AR->getOperand(i);
     255        3444 :     OS << "}<";
     256        3444 :     if (AR->hasNoUnsignedWrap())
     257         458 :       OS << "nuw><";
     258        3444 :     if (AR->hasNoSignedWrap())
     259         621 :       OS << "nsw><";
     260        4351 :     if (AR->hasNoSelfWrap() &&
     261             :         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
     262         163 :       OS << "nw><";
     263        6888 :     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
     264        3444 :     OS << ">";
     265        3444 :     return;
     266             :   }
     267             :   case scAddExpr:
     268             :   case scMulExpr:
     269             :   case scUMaxExpr:
     270             :   case scSMaxExpr: {
     271             :     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
     272             :     const char *OpStr = nullptr;
     273       14605 :     switch (NAry->getSCEVType()) {
     274        5824 :     case scAddExpr: OpStr = " + "; break;
     275        5772 :     case scMulExpr: OpStr = " * "; break;
     276        2727 :     case scUMaxExpr: OpStr = " umax "; break;
     277         282 :     case scSMaxExpr: OpStr = " smax "; break;
     278             :     }
     279       14605 :     OS << "(";
     280       14605 :     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
     281       46233 :          I != E; ++I) {
     282       31628 :       OS << **I;
     283       31628 :       if (std::next(I) != E)
     284       17023 :         OS << OpStr;
     285             :     }
     286       14605 :     OS << ")";
     287       29210 :     switch (NAry->getSCEVType()) {
     288             :     case scAddExpr:
     289             :     case scMulExpr:
     290       11596 :       if (NAry->hasNoUnsignedWrap())
     291         402 :         OS << "<nuw>";
     292       11596 :       if (NAry->hasNoSignedWrap())
     293        2662 :         OS << "<nsw>";
     294             :     }
     295             :     return;
     296             :   }
     297             :   case scUDivExpr: {
     298             :     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
     299         403 :     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
     300         403 :     return;
     301             :   }
     302             :   case scUnknown: {
     303             :     const SCEVUnknown *U = cast<SCEVUnknown>(this);
     304             :     Type *AllocTy;
     305       10275 :     if (U->isSizeOf(AllocTy)) {
     306           8 :       OS << "sizeof(" << *AllocTy << ")";
     307           4 :       return;
     308             :     }
     309       10271 :     if (U->isAlignOf(AllocTy)) {
     310           6 :       OS << "alignof(" << *AllocTy << ")";
     311           3 :       return;
     312             :     }
     313             : 
     314             :     Type *CTy;
     315             :     Constant *FieldNo;
     316       10268 :     if (U->isOffsetOf(CTy, FieldNo)) {
     317           2 :       OS << "offsetof(" << *CTy << ", ";
     318           1 :       FieldNo->printAsOperand(OS, false);
     319           1 :       OS << ")";
     320           1 :       return;
     321             :     }
     322             : 
     323             :     // Otherwise just print it normally.
     324       10267 :     U->getValue()->printAsOperand(OS, false);
     325       10267 :     return;
     326             :   }
     327           0 :   case scCouldNotCompute:
     328           0 :     OS << "***COULDNOTCOMPUTE***";
     329           0 :     return;
     330             :   }
     331           0 :   llvm_unreachable("Unknown SCEV kind!");
     332             : }
     333             : 
     334     7588826 : Type *SCEV::getType() const {
     335     7635461 :   switch (static_cast<SCEVTypes>(getSCEVType())) {
     336             :   case scConstant:
     337     6322460 :     return cast<SCEVConstant>(this)->getType();
     338             :   case scTruncate:
     339             :   case scZeroExtend:
     340             :   case scSignExtend:
     341      150528 :     return cast<SCEVCastExpr>(this)->getType();
     342             :   case scAddRecExpr:
     343             :   case scMulExpr:
     344             :   case scUMaxExpr:
     345             :   case scSMaxExpr:
     346     1586851 :     return cast<SCEVNAryExpr>(this)->getType();
     347             :   case scAddExpr:
     348      793951 :     return cast<SCEVAddExpr>(this)->getType();
     349             :   case scUDivExpr:
     350       46635 :     return cast<SCEVUDivExpr>(this)->getType();
     351             :   case scUnknown:
     352     1896266 :     return cast<SCEVUnknown>(this)->getType();
     353           0 :   case scCouldNotCompute:
     354           0 :     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
     355             :   }
     356           0 :   llvm_unreachable("Unknown SCEV kind!");
     357             : }
     358             : 
     359     1241245 : bool SCEV::isZero() const {
     360             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
     361      829188 :     return SC->getValue()->isZero();
     362             :   return false;
     363             : }
     364             : 
     365       42471 : bool SCEV::isOne() const {
     366             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
     367       27283 :     return SC->getValue()->isOne();
     368             :   return false;
     369             : }
     370             : 
     371      536956 : bool SCEV::isAllOnesValue() const {
     372             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
     373      533655 :     return SC->getValue()->isMinusOne();
     374             :   return false;
     375             : }
     376             : 
     377       20416 : bool SCEV::isNonConstantNegative() const {
     378             :   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
     379             :   if (!Mul) return false;
     380             : 
     381             :   // If there is a constant factor, it will be first.
     382        3818 :   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
     383             :   if (!SC) return false;
     384             : 
     385             :   // Return true if the value is negative, this matches things like (-42 * V).
     386        6182 :   return SC->getAPInt().isNegative();
     387             : }
     388             : 
     389      475625 : SCEVCouldNotCompute::SCEVCouldNotCompute() :
     390      475625 :   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
     391             : 
     392      570265 : bool SCEVCouldNotCompute::classof(const SCEV *S) {
     393      570265 :   return S->getSCEVType() == scCouldNotCompute;
     394             : }
     395             : 
     396     4977537 : const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
     397             :   FoldingSetNodeID ID;
     398     4977537 :   ID.AddInteger(scConstant);
     399     4977537 :   ID.AddPointer(V);
     400     4977537 :   void *IP = nullptr;
     401     4977537 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
     402      725840 :   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
     403      362920 :   UniqueSCEVs.InsertNode(S, IP);
     404      362920 :   return S;
     405             : }
     406             : 
     407     1919977 : const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
     408     3839954 :   return getConstant(ConstantInt::get(getContext(), Val));
     409             : }
     410             : 
     411             : const SCEV *
     412     1208429 : ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
     413     1208429 :   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
     414     1208429 :   return getConstant(ConstantInt::get(ITy, V, isSigned));
     415             : }
     416             : 
     417       50098 : SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
     418       50098 :                            unsigned SCEVTy, const SCEV *op, Type *ty)
     419       50098 :   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
     420             : 
     421        2895 : SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
     422        2895 :                                    const SCEV *op, Type *ty)
     423        2895 :   : SCEVCastExpr(ID, scTruncate, op, ty) {
     424             :   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
     425             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
     426             :          "Cannot truncate non-integer value!");
     427        2895 : }
     428             : 
     429       29177 : SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
     430       29177 :                                        const SCEV *op, Type *ty)
     431       29177 :   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
     432             :   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
     433             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
     434             :          "Cannot zero extend non-integer value!");
     435       29177 : }
     436             : 
     437       18026 : SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
     438       18026 :                                        const SCEV *op, Type *ty)
     439       18026 :   : SCEVCastExpr(ID, scSignExtend, op, ty) {
     440             :   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
     441             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
     442             :          "Cannot sign extend non-integer value!");
     443       18026 : }
     444             : 
     445         895 : void SCEVUnknown::deleted() {
     446             :   // Clear this SCEVUnknown from various maps.
     447         895 :   SE->forgetMemoizedResults(this);
     448             : 
     449             :   // Remove this SCEVUnknown from the uniquing map.
     450         895 :   SE->UniqueSCEVs.RemoveNode(this);
     451             : 
     452             :   // Release the value.
     453             :   setValPtr(nullptr);
     454         895 : }
     455             : 
     456        1302 : void SCEVUnknown::allUsesReplacedWith(Value *New) {
     457             :   // Remove this SCEVUnknown from the uniquing map.
     458        1302 :   SE->UniqueSCEVs.RemoveNode(this);
     459             : 
     460             :   // Update this SCEVUnknown to point to the new value. This is needed
     461             :   // because there may still be outstanding SCEVs which still point to
     462             :   // this SCEVUnknown.
     463             :   setValPtr(New);
     464        1302 : }
     465             : 
     466       10275 : bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
     467             :   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
     468          13 :     if (VCE->getOpcode() == Instruction::PtrToInt)
     469             :       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
     470           8 :         if (CE->getOpcode() == Instruction::GetElementPtr &&
     471          24 :             CE->getOperand(0)->isNullValue() &&
     472             :             CE->getNumOperands() == 2)
     473             :           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
     474           4 :             if (CI->isOne()) {
     475           4 :               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
     476           4 :                                  ->getElementType();
     477           4 :               return true;
     478             :             }
     479             : 
     480             :   return false;
     481             : }
     482             : 
     483       10271 : bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
     484             :   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
     485           9 :     if (VCE->getOpcode() == Instruction::PtrToInt)
     486             :       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
     487           8 :         if (CE->getOpcode() == Instruction::GetElementPtr &&
     488           4 :             CE->getOperand(0)->isNullValue()) {
     489             :           Type *Ty =
     490           4 :             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
     491             :           if (StructType *STy = dyn_cast<StructType>(Ty))
     492           4 :             if (!STy->isPacked() &&
     493           8 :                 CE->getNumOperands() == 3 &&
     494           4 :                 CE->getOperand(1)->isNullValue()) {
     495             :               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
     496           3 :                 if (CI->isOne() &&
     497           7 :                     STy->getNumElements() == 2 &&
     498           6 :                     STy->getElementType(0)->isIntegerTy(1)) {
     499           6 :                   AllocTy = STy->getElementType(1);
     500           3 :                   return true;
     501             :                 }
     502             :             }
     503             :         }
     504             : 
     505             :   return false;
     506             : }
     507             : 
     508       10268 : bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
     509             :   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
     510           6 :     if (VCE->getOpcode() == Instruction::PtrToInt)
     511             :       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
     512           1 :         if (CE->getOpcode() == Instruction::GetElementPtr &&
     513           1 :             CE->getNumOperands() == 3 &&
     514           3 :             CE->getOperand(0)->isNullValue() &&
     515           1 :             CE->getOperand(1)->isNullValue()) {
     516             :           Type *Ty =
     517           1 :             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
     518             :           // Ignore vector types here so that ScalarEvolutionExpander doesn't
     519             :           // emit getelementptrs that index into vectors.
     520           1 :           if (Ty->isStructTy() || Ty->isArrayTy()) {
     521           1 :             CTy = Ty;
     522           1 :             FieldNo = CE->getOperand(2);
     523           1 :             return true;
     524             :           }
     525             :         }
     526             : 
     527             :   return false;
     528             : }
     529             : 
     530             : //===----------------------------------------------------------------------===//
     531             : //                               SCEV Utilities
     532             : //===----------------------------------------------------------------------===//
     533             : 
     534             : /// Compare the two values \p LV and \p RV in terms of their "complexity" where
     535             : /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
     536             : /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
     537             : /// have been previously deemed to be "equally complex" by this routine.  It is
     538             : /// intended to avoid exponential time complexity in cases like:
     539             : ///
     540             : ///   %a = f(%x, %y)
     541             : ///   %b = f(%a, %a)
     542             : ///   %c = f(%b, %b)
     543             : ///
     544             : ///   %d = f(%x, %y)
     545             : ///   %e = f(%d, %d)
     546             : ///   %f = f(%e, %e)
     547             : ///
     548             : ///   CompareValueComplexity(%f, %c)
     549             : ///
     550             : /// Since we do not continue running this routine on expression trees once we
     551             : /// have seen unequal values, there is no need to track them in the cache.
     552             : static int
     553     4091301 : CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
     554             :                        const LoopInfo *const LI, Value *LV, Value *RV,
     555             :                        unsigned Depth) {
     556     4091301 :   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
     557             :     return 0;
     558             : 
     559             :   // Order pointer values after integer values. This helps SCEVExpander form
     560             :   // GEPs.
     561     2076175 :   bool LIsPointer = LV->getType()->isPointerTy(),
     562     2076175 :        RIsPointer = RV->getType()->isPointerTy();
     563     2076175 :   if (LIsPointer != RIsPointer)
     564       10028 :     return (int)LIsPointer - (int)RIsPointer;
     565             : 
     566             :   // Compare getValueID values.
     567     4132294 :   unsigned LID = LV->getValueID(), RID = RV->getValueID();
     568     2066147 :   if (LID != RID)
     569      694771 :     return (int)LID - (int)RID;
     570             : 
     571             :   // Sort arguments by their position.
     572             :   if (const auto *LA = dyn_cast<Argument>(LV)) {
     573             :     const auto *RA = cast<Argument>(RV);
     574        9265 :     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
     575        9265 :     return (int)LArgNo - (int)RArgNo;
     576             :   }
     577             : 
     578             :   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
     579             :     const auto *RGV = cast<GlobalValue>(RV);
     580             : 
     581             :     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
     582             :       auto LT = GV->getLinkage();
     583       11364 :       return !(GlobalValue::isPrivateLinkage(LT) ||
     584             :                GlobalValue::isInternalLinkage(LT));
     585             :     };
     586             : 
     587             :     // Use the names to distinguish the two values, but only if the
     588             :     // names are semantically important.
     589             :     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
     590       11364 :       return LGV->getName().compare(RGV->getName());
     591             :   }
     592             : 
     593             :   // For instructions, compare their loop depth, and their operand count.  This
     594             :   // is pretty loose.
     595             :   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
     596             :     const auto *RInst = cast<Instruction>(RV);
     597             : 
     598             :     // Compare loop depths.
     599     1354821 :     const BasicBlock *LParent = LInst->getParent(),
     600     1354821 :                      *RParent = RInst->getParent();
     601     1354821 :     if (LParent != RParent) {
     602      936462 :       unsigned LDepth = LI->getLoopDepth(LParent),
     603      936462 :                RDepth = LI->getLoopDepth(RParent);
     604      936462 :       if (LDepth != RDepth)
     605         354 :         return (int)LDepth - (int)RDepth;
     606             :     }
     607             : 
     608             :     // Compare the number of operands.
     609             :     unsigned LNumOps = LInst->getNumOperands(),
     610             :              RNumOps = RInst->getNumOperands();
     611     1354467 :     if (LNumOps != RNumOps)
     612         113 :       return (int)LNumOps - (int)RNumOps;
     613             : 
     614     4119834 :     for (unsigned Idx : seq(0u, LNumOps)) {
     615             :       int Result =
     616     5663700 :           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
     617     2831850 :                                  RInst->getOperand(Idx), Depth + 1);
     618     2831850 :       if (Result != 0)
     619             :         return Result;
     620             :     }
     621             :   }
     622             : 
     623     1289592 :   EqCacheValue.unionSets(LV, RV);
     624     1289592 :   return 0;
     625             : }
     626             : 
     627             : // Return negative, zero, or positive, if LHS is less than, equal to, or greater
     628             : // than RHS, respectively. A three-way result allows recursive comparisons to be
     629             : // more efficient.
     630     7834247 : static int CompareSCEVComplexity(
     631             :     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
     632             :     EquivalenceClasses<const Value *> &EqCacheValue,
     633             :     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
     634             :     DominatorTree &DT, unsigned Depth = 0) {
     635             :   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
     636     7834247 :   if (LHS == RHS)
     637             :     return 0;
     638             : 
     639             :   // Primarily, sort the SCEVs by their getSCEVType().
     640    13854682 :   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
     641     6927341 :   if (LType != RType)
     642     2657474 :     return (int)LType - (int)RType;
     643             : 
     644     4269867 :   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
     645             :     return 0;
     646             :   // Aside from the getSCEVType() ordering, the particular ordering
     647             :   // isn't very important except that it's beneficial to be consistent,
     648             :   // so that (a + b) and (b + a) don't end up as different expressions.
     649     3322437 :   switch (static_cast<SCEVTypes>(LType)) {
     650     1259451 :   case scUnknown: {
     651     1259451 :     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
     652     1259451 :     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
     653             : 
     654     1259451 :     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
     655     1259451 :                                    RU->getValue(), Depth + 1);
     656     1259451 :     if (X == 0)
     657      539238 :       EqCacheSCEV.unionSets(LHS, RHS);
     658             :     return X;
     659             :   }
     660             : 
     661     1303580 :   case scConstant: {
     662     1303580 :     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
     663     1303580 :     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
     664             : 
     665             :     // Compare constant values.
     666             :     const APInt &LA = LC->getAPInt();
     667             :     const APInt &RA = RC->getAPInt();
     668     1303580 :     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
     669     1303580 :     if (LBitWidth != RBitWidth)
     670           1 :       return (int)LBitWidth - (int)RBitWidth;
     671     1303579 :     return LA.ult(RA) ? -1 : 1;
     672             :   }
     673             : 
     674       16856 :   case scAddRecExpr: {
     675       16856 :     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
     676       16856 :     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
     677             : 
     678             :     // There is always a dominance between two recs that are used by one SCEV,
     679             :     // so we can safely sort recs by loop header dominance. We require such
     680             :     // order in getAddExpr.
     681       16856 :     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
     682       16856 :     if (LLoop != RLoop) {
     683             :       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
     684             :       assert(LHead != RHead && "Two loops share the same header?");
     685        3880 :       if (DT.dominates(LHead, RHead))
     686             :         return 1;
     687             :       else
     688             :         assert(DT.dominates(RHead, LHead) &&
     689             :                "No dominance between recurrences used by one SCEV?");
     690        1815 :       return -1;
     691             :     }
     692             : 
     693             :     // Addrec complexity grows with operand count.
     694       12976 :     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
     695       12976 :     if (LNumOps != RNumOps)
     696        2524 :       return (int)LNumOps - (int)RNumOps;
     697             : 
     698             :     // Compare NoWrap flags.
     699       31356 :     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
     700        2314 :       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
     701             : 
     702             :     // Lexicographically compare.
     703        8296 :     for (unsigned i = 0; i != LNumOps; ++i) {
     704       16434 :       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     705             :                                     LA->getOperand(i), RA->getOperand(i), DT,
     706        8217 :                                     Depth + 1);
     707        8217 :       if (X != 0)
     708             :         return X;
     709             :     }
     710           0 :     EqCacheSCEV.unionSets(LHS, RHS);
     711           0 :     return 0;
     712             :   }
     713             : 
     714      725721 :   case scAddExpr:
     715             :   case scMulExpr:
     716             :   case scSMaxExpr:
     717             :   case scUMaxExpr: {
     718      725721 :     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
     719      725721 :     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
     720             : 
     721             :     // Lexicographically compare n-ary expressions.
     722      725721 :     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
     723      725721 :     if (LNumOps != RNumOps)
     724       86090 :       return (int)LNumOps - (int)RNumOps;
     725             : 
     726             :     // Compare NoWrap flags.
     727     1918893 :     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
     728       31336 :       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
     729             : 
     730     2166591 :     for (unsigned i = 0; i != LNumOps; ++i) {
     731     2257460 :       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     732             :                                     LC->getOperand(i), RC->getOperand(i), DT,
     733     1128730 :                                     Depth + 1);
     734     1128730 :       if (X != 0)
     735             :         return X;
     736             :     }
     737      258713 :     EqCacheSCEV.unionSets(LHS, RHS);
     738      258713 :     return 0;
     739             :   }
     740             : 
     741        3514 :   case scUDivExpr: {
     742        3514 :     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
     743        3514 :     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
     744             : 
     745             :     // Lexicographically compare udiv expressions.
     746        3514 :     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
     747        3514 :                                   RC->getLHS(), DT, Depth + 1);
     748        3514 :     if (X != 0)
     749             :       return X;
     750          95 :     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
     751             :                               RC->getRHS(), DT, Depth + 1);
     752          95 :     if (X == 0)
     753          92 :       EqCacheSCEV.unionSets(LHS, RHS);
     754             :     return X;
     755             :   }
     756             : 
     757       13315 :   case scTruncate:
     758             :   case scZeroExtend:
     759             :   case scSignExtend: {
     760       13315 :     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
     761       13315 :     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
     762             : 
     763             :     // Compare cast expressions by operand.
     764       13315 :     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     765             :                                   LC->getOperand(), RC->getOperand(), DT,
     766       13315 :                                   Depth + 1);
     767       13315 :     if (X == 0)
     768        1753 :       EqCacheSCEV.unionSets(LHS, RHS);
     769             :     return X;
     770             :   }
     771             : 
     772           0 :   case scCouldNotCompute:
     773           0 :     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
     774             :   }
     775           0 :   llvm_unreachable("Unknown SCEV kind!");
     776             : }
     777             : 
     778             : /// Given a list of SCEV objects, order them by their complexity, and group
     779             : /// objects of the same complexity together by value.  When this routine is
     780             : /// finished, we know that any duplicates in the vector are consecutive and that
     781             : /// complexity is monotonically increasing.
     782             : ///
     783             : /// Note that we go take special precautions to ensure that we get deterministic
     784             : /// results from this routine.  In other words, we don't want the results of
     785             : /// this to depend on where the addresses of various SCEV objects happened to
     786             : /// land in memory.
     787     3593822 : static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
     788             :                               LoopInfo *LI, DominatorTree &DT) {
     789     6827998 :   if (Ops.size() < 2) return;  // Noop
     790             : 
     791             :   EquivalenceClasses<const SCEV *> EqCacheSCEV;
     792             :   EquivalenceClasses<const Value *> EqCacheValue;
     793     3593822 :   if (Ops.size() == 2) {
     794             :     // This is the common case, which also happens to be trivially simple.
     795             :     // Special case it.
     796             :     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
     797     3199640 :     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
     798             :       std::swap(LHS, RHS);
     799             :     return;
     800             :   }
     801             : 
     802             :   // Do the rough sort by complexity.
     803             :   std::stable_sort(Ops.begin(), Ops.end(),
     804     3480736 :                    [&](const SCEV *LHS, const SCEV *RHS) {
     805     3480736 :                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     806     3480736 :                                                   LHS, RHS, DT) < 0;
     807     3480736 :                    });
     808             : 
     809             :   // Now that we are sorted by complexity, group elements of the same
     810             :   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
     811             :   // be extremely short in practice.  Note that we take this approach because we
     812             :   // do not want to depend on the addresses of the objects we are grouping.
     813     1396302 :   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
     814     2073312 :     const SCEV *S = Ops[i];
     815     1036656 :     unsigned Complexity = S->getSCEVType();
     816             : 
     817             :     // If there are any objects of the same complexity and same value as this
     818             :     // one, group them.
     819    26377825 :     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
     820    12347636 :       if (Ops[j] == S) { // Found a duplicate.
     821             :         // Move it to immediately after i'th element.
     822       61634 :         std::swap(Ops[i+1], Ops[j]);
     823             :         ++i;   // no need to rescan it.
     824       61634 :         if (i == e-2) return;  // Done!
     825             :       }
     826             :     }
     827             :   }
     828             : }
     829             : 
     830             : // Returns the size of the SCEV S.
     831          72 : static inline int sizeOfSCEV(const SCEV *S) {
     832             :   struct FindSCEVSize {
     833             :     int Size = 0;
     834             : 
     835             :     FindSCEVSize() = default;
     836             : 
     837             :     bool follow(const SCEV *S) {
     838         209 :       ++Size;
     839             :       // Keep looking at all operands of S.
     840             :       return true;
     841             :     }
     842             : 
     843             :     bool isDone() const {
     844             :       return false;
     845             :     }
     846             :   };
     847             : 
     848          72 :   FindSCEVSize F;
     849          72 :   SCEVTraversal<FindSCEVSize> ST(F);
     850          72 :   ST.visitAll(S);
     851         144 :   return F.Size;
     852             : }
     853             : 
     854             : namespace {
     855             : 
     856             : struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
     857             : public:
     858             :   // Computes the Quotient and Remainder of the division of Numerator by
     859             :   // Denominator.
     860       36189 :   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
     861             :                      const SCEV *Denominator, const SCEV **Quotient,
     862             :                      const SCEV **Remainder) {
     863             :     assert(Numerator && Denominator && "Uninitialized SCEV");
     864             : 
     865       36189 :     SCEVDivision D(SE, Numerator, Denominator);
     866             : 
     867             :     // Check for the trivial case here to avoid having to check for it in the
     868             :     // rest of the code.
     869       36189 :     if (Numerator == Denominator) {
     870       10588 :       *Quotient = D.One;
     871       10588 :       *Remainder = D.Zero;
     872       23750 :       return;
     873             :     }
     874             : 
     875       25601 :     if (Numerator->isZero()) {
     876        2520 :       *Quotient = D.Zero;
     877        2520 :       *Remainder = D.Zero;
     878        2520 :       return;
     879             :     }
     880             : 
     881             :     // A simple case when N/1. The quotient is N.
     882       23081 :     if (Denominator->isOne()) {
     883          44 :       *Quotient = Numerator;
     884          44 :       *Remainder = D.Zero;
     885          44 :       return;
     886             :     }
     887             : 
     888             :     // Split the Denominator when it is a product.
     889             :     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
     890             :       const SCEV *Q, *R;
     891          10 :       *Quotient = Numerator;
     892          18 :       for (const SCEV *Op : T->operands()) {
     893          12 :         divide(SE, *Quotient, Op, &Q, &R);
     894          12 :         *Quotient = Q;
     895             : 
     896             :         // Bail out when the Numerator is not divisible by one of the terms of
     897             :         // the Denominator.
     898          12 :         if (!R->isZero()) {
     899           8 :           *Quotient = D.Zero;
     900           8 :           *Remainder = Numerator;
     901           8 :           return;
     902             :         }
     903             :       }
     904           2 :       *Remainder = D.Zero;
     905           2 :       return;
     906             :     }
     907             : 
     908       23027 :     D.visit(Numerator);
     909       23027 :     *Quotient = D.Quotient;
     910       23027 :     *Remainder = D.Remainder;
     911             :   }
     912             : 
     913             :   // Except in the trivial case described above, we do not know how to divide
     914             :   // Expr by Denominator for the following functions with empty implementation.
     915             :   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
     916             :   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
     917             :   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
     918             :   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
     919             :   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
     920             :   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
     921             :   void visitUnknown(const SCEVUnknown *Numerator) {}
     922             :   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
     923             : 
     924        3390 :   void visitConstant(const SCEVConstant *Numerator) {
     925        3390 :     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
     926             :       APInt NumeratorVal = Numerator->getAPInt();
     927             :       APInt DenominatorVal = D->getAPInt();
     928         366 :       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
     929         366 :       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
     930             : 
     931         366 :       if (NumeratorBW > DenominatorBW)
     932           0 :         DenominatorVal = DenominatorVal.sext(NumeratorBW);
     933         366 :       else if (NumeratorBW < DenominatorBW)
     934           0 :         NumeratorVal = NumeratorVal.sext(DenominatorBW);
     935             : 
     936         366 :       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
     937         366 :       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
     938         366 :       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
     939         366 :       Quotient = SE.getConstant(QuotientVal);
     940         366 :       Remainder = SE.getConstant(RemainderVal);
     941             :       return;
     942             :     }
     943             :   }
     944             : 
     945        8884 :   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
     946             :     const SCEV *StartQ, *StartR, *StepQ, *StepR;
     947        8884 :     if (!Numerator->isAffine())
     948           9 :       return cannotDivide(Numerator);
     949       17766 :     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
     950        8883 :     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
     951             :     // Bail out if the types do not match.
     952        8883 :     Type *Ty = Denominator->getType();
     953       26641 :     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
     954       26633 :         Ty != StepQ->getType() || Ty != StepR->getType())
     955             :       return cannotDivide(Numerator);
     956       17750 :     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
     957             :                                 Numerator->getNoWrapFlags());
     958       17750 :     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
     959             :                                  Numerator->getNoWrapFlags());
     960             :   }
     961             : 
     962        1075 :   void visitAddExpr(const SCEVAddExpr *Numerator) {
     963             :     SmallVector<const SCEV *, 2> Qs, Rs;
     964        1075 :     Type *Ty = Denominator->getType();
     965             : 
     966        5441 :     for (const SCEV *Op : Numerator->operands()) {
     967             :       const SCEV *Q, *R;
     968        2183 :       divide(SE, Op, Denominator, &Q, &R);
     969             : 
     970             :       // Bail out if types do not match.
     971        2183 :       if (Ty != Q->getType() || Ty != R->getType())
     972           0 :         return cannotDivide(Numerator);
     973             : 
     974        2183 :       Qs.push_back(Q);
     975        2183 :       Rs.push_back(R);
     976             :     }
     977             : 
     978        1075 :     if (Qs.size() == 1) {
     979           0 :       Quotient = Qs[0];
     980           0 :       Remainder = Rs[0];
     981           0 :       return;
     982             :     }
     983             : 
     984        1075 :     Quotient = SE.getAddExpr(Qs);
     985        1075 :     Remainder = SE.getAddExpr(Rs);
     986             :   }
     987             : 
     988        6717 :   void visitMulExpr(const SCEVMulExpr *Numerator) {
     989             :     SmallVector<const SCEV *, 2> Qs;
     990        6717 :     Type *Ty = Denominator->getType();
     991             : 
     992             :     bool FoundDenominatorTerm = false;
     993       39919 :     for (const SCEV *Op : Numerator->operands()) {
     994             :       // Bail out if types do not match.
     995       16601 :       if (Ty != Op->getType())
     996           0 :         return cannotDivide(Numerator);
     997             : 
     998       23509 :       if (FoundDenominatorTerm) {
     999        6908 :         Qs.push_back(Op);
    1000       16852 :         continue;
    1001             :       }
    1002             : 
    1003             :       // Check whether Denominator divides one of the product operands.
    1004             :       const SCEV *Q, *R;
    1005        9693 :       divide(SE, Op, Denominator, &Q, &R);
    1006       12729 :       if (!R->isZero()) {
    1007        3036 :         Qs.push_back(Op);
    1008        3036 :         continue;
    1009             :       }
    1010             : 
    1011             :       // Bail out if types do not match.
    1012        6657 :       if (Ty != Q->getType())
    1013             :         return cannotDivide(Numerator);
    1014             : 
    1015             :       FoundDenominatorTerm = true;
    1016        6657 :       Qs.push_back(Q);
    1017             :     }
    1018             : 
    1019        6717 :     if (FoundDenominatorTerm) {
    1020        6657 :       Remainder = Zero;
    1021        6657 :       if (Qs.size() == 1)
    1022           0 :         Quotient = Qs[0];
    1023             :       else
    1024        6657 :         Quotient = SE.getMulExpr(Qs);
    1025             :       return;
    1026             :     }
    1027             : 
    1028          60 :     if (!isa<SCEVUnknown>(Denominator))
    1029             :       return cannotDivide(Numerator);
    1030             : 
    1031             :     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
    1032             :     ValueToValueMap RewriteMap;
    1033         108 :     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
    1034          72 :         cast<SCEVConstant>(Zero)->getValue();
    1035          36 :     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
    1036             : 
    1037          36 :     if (Remainder->isZero()) {
    1038             :       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
    1039           0 :       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
    1040           0 :           cast<SCEVConstant>(One)->getValue();
    1041           0 :       Quotient =
    1042           0 :           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
    1043           0 :       return;
    1044             :     }
    1045             : 
    1046             :     // Quotient is (Numerator - Remainder) divided by Denominator.
    1047             :     const SCEV *Q, *R;
    1048          36 :     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
    1049             :     // This SCEV does not seem to simplify: fail the division here.
    1050          36 :     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
    1051             :       return cannotDivide(Numerator);
    1052          36 :     divide(SE, Diff, Denominator, &Q, &R);
    1053          36 :     if (R != Zero)
    1054             :       return cannotDivide(Numerator);
    1055          36 :     Quotient = Q;
    1056             :   }
    1057             : 
    1058             : private:
    1059       36189 :   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
    1060             :                const SCEV *Denominator)
    1061       36189 :       : SE(S), Denominator(Denominator) {
    1062       72378 :     Zero = SE.getZero(Denominator->getType());
    1063       72378 :     One = SE.getOne(Denominator->getType());
    1064             : 
    1065             :     // We generally do not know how to divide Expr by Denominator. We
    1066             :     // initialize the division to a "cannot divide" state to simplify the rest
    1067             :     // of the code.
    1068             :     cannotDivide(Numerator);
    1069       36189 :   }
    1070             : 
    1071             :   // Convenience function for giving up on the division. We set the quotient to
    1072             :   // be equal to zero and the remainder to be equal to the numerator.
    1073             :   void cannotDivide(const SCEV *Numerator) {
    1074       36222 :     Quotient = Zero;
    1075       36222 :     Remainder = Numerator;
    1076             :   }
    1077             : 
    1078             :   ScalarEvolution &SE;
    1079             :   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
    1080             : };
    1081             : 
    1082             : } // end anonymous namespace
    1083             : 
    1084             : //===----------------------------------------------------------------------===//
    1085             : //                      Simple SCEV method implementations
    1086             : //===----------------------------------------------------------------------===//
    1087             : 
    1088             : /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
    1089       29502 : static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
    1090             :                                        ScalarEvolution &SE,
    1091             :                                        Type *ResultTy) {
    1092             :   // Handle the simplest case efficiently.
    1093       29502 :   if (K == 1)
    1094       27100 :     return SE.getTruncateOrZeroExtend(It, ResultTy);
    1095             : 
    1096             :   // We are using the following formula for BC(It, K):
    1097             :   //
    1098             :   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
    1099             :   //
    1100             :   // Suppose, W is the bitwidth of the return value.  We must be prepared for
    1101             :   // overflow.  Hence, we must assure that the result of our computation is
    1102             :   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
    1103             :   // safe in modular arithmetic.
    1104             :   //
    1105             :   // However, this code doesn't use exactly that formula; the formula it uses
    1106             :   // is something like the following, where T is the number of factors of 2 in
    1107             :   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
    1108             :   // exponentiation:
    1109             :   //
    1110             :   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
    1111             :   //
    1112             :   // This formula is trivially equivalent to the previous formula.  However,
    1113             :   // this formula can be implemented much more efficiently.  The trick is that
    1114             :   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
    1115             :   // arithmetic.  To do exact division in modular arithmetic, all we have
    1116             :   // to do is multiply by the inverse.  Therefore, this step can be done at
    1117             :   // width W.
    1118             :   //
    1119             :   // The next issue is how to safely do the division by 2^T.  The way this
    1120             :   // is done is by doing the multiplication step at a width of at least W + T
    1121             :   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
    1122             :   // when we perform the division by 2^T (which is equivalent to a right shift
    1123             :   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
    1124             :   // truncated out after the division by 2^T.
    1125             :   //
    1126             :   // In comparison to just directly using the first formula, this technique
    1127             :   // is much more efficient; using the first formula requires W * K bits,
    1128             :   // but this formula less than W + K bits. Also, the first formula requires
    1129             :   // a division step, whereas this formula only requires multiplies and shifts.
    1130             :   //
    1131             :   // It doesn't matter whether the subtraction step is done in the calculation
    1132             :   // width or the input iteration count's width; if the subtraction overflows,
    1133             :   // the result must be zero anyway.  We prefer here to do it in the width of
    1134             :   // the induction variable because it helps a lot for certain cases; CodeGen
    1135             :   // isn't smart enough to ignore the overflow, which leads to much less
    1136             :   // efficient code if the width of the subtraction is wider than the native
    1137             :   // register width.
    1138             :   //
    1139             :   // (It's possible to not widen at all by pulling out factors of 2 before
    1140             :   // the multiplication; for example, K=2 can be calculated as
    1141             :   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
    1142             :   // extra arithmetic, so it's not an obvious win, and it gets
    1143             :   // much more complicated for K > 3.)
    1144             : 
    1145             :   // Protection from insane SCEVs; this bound is conservative,
    1146             :   // but it probably doesn't matter.
    1147        2402 :   if (K > 1000)
    1148           0 :     return SE.getCouldNotCompute();
    1149             : 
    1150        2402 :   unsigned W = SE.getTypeSizeInBits(ResultTy);
    1151             : 
    1152             :   // Calculate K! / 2^T and T; we divide out the factors of two before
    1153             :   // multiplying for calculating K! / 2^T to avoid overflow.
    1154             :   // Other overflow doesn't matter because we only care about the bottom
    1155             :   // W bits of the result.
    1156             :   APInt OddFactorial(W, 1);
    1157             :   unsigned T = 1;
    1158        5870 :   for (unsigned i = 3; i <= K; ++i) {
    1159        1734 :     APInt Mult(W, i);
    1160        1734 :     unsigned TwoFactors = Mult.countTrailingZeros();
    1161        1734 :     T += TwoFactors;
    1162             :     Mult.lshrInPlace(TwoFactors);
    1163        1734 :     OddFactorial *= Mult;
    1164             :   }
    1165             : 
    1166             :   // We need at least W + T bits for the multiplication step
    1167        2402 :   unsigned CalculationBits = W + T;
    1168             : 
    1169             :   // Calculate 2^T, at width T+W.
    1170        2402 :   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
    1171             : 
    1172             :   // Calculate the multiplicative inverse of K! / 2^T;
    1173             :   // this multiplication factor will perform the exact division by
    1174             :   // K! / 2^T.
    1175        2402 :   APInt Mod = APInt::getSignedMinValue(W+1);
    1176        2402 :   APInt MultiplyFactor = OddFactorial.zext(W+1);
    1177        4804 :   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
    1178        4804 :   MultiplyFactor = MultiplyFactor.trunc(W);
    1179             : 
    1180             :   // Calculate the product, at width T+W
    1181        2402 :   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
    1182        2402 :                                                       CalculationBits);
    1183        2402 :   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
    1184       10674 :   for (unsigned i = 1; i != K; ++i) {
    1185        4136 :     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
    1186        4136 :     Dividend = SE.getMulExpr(Dividend,
    1187             :                              SE.getTruncateOrZeroExtend(S, CalculationTy));
    1188             :   }
    1189             : 
    1190             :   // Divide by 2^T
    1191        2402 :   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
    1192             : 
    1193             :   // Truncate the result, and divide by K! / 2^T.
    1194             : 
    1195        2402 :   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
    1196        2402 :                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
    1197             : }
    1198             : 
    1199             : /// Return the value of this chain of recurrences at the specified iteration
    1200             : /// number.  We can evaluate this recurrence by multiplying each element in the
    1201             : /// chain by the binomial coefficient corresponding to it.  In other words, we
    1202             : /// can evaluate {A,+,B,+,C,+,D} as:
    1203             : ///
    1204             : ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
    1205             : ///
    1206             : /// where BC(It, k) stands for binomial coefficient.
    1207       27100 : const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
    1208             :                                                 ScalarEvolution &SE) const {
    1209       27100 :   const SCEV *Result = getStart();
    1210       56602 :   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
    1211             :     // The computation is correct in the face of overflow provided that the
    1212             :     // multiplication is performed _after_ the evaluation of the binomial
    1213             :     // coefficient.
    1214       29502 :     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
    1215       29502 :     if (isa<SCEVCouldNotCompute>(Coeff))
    1216             :       return Coeff;
    1217             : 
    1218       59004 :     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
    1219             :   }
    1220             :   return Result;
    1221             : }
    1222             : 
    1223             : //===----------------------------------------------------------------------===//
    1224             : //                    SCEV Expression folder implementations
    1225             : //===----------------------------------------------------------------------===//
    1226             : 
    1227       23776 : const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
    1228             :                                              Type *Ty) {
    1229             :   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
    1230             :          "This is not a truncating conversion!");
    1231             :   assert(isSCEVable(Ty) &&
    1232             :          "This is not a conversion to a SCEVable type!");
    1233       23776 :   Ty = getEffectiveSCEVType(Ty);
    1234             : 
    1235             :   FoldingSetNodeID ID;
    1236       23776 :   ID.AddInteger(scTruncate);
    1237       23776 :   ID.AddPointer(Op);
    1238       23776 :   ID.AddPointer(Ty);
    1239       23776 :   void *IP = nullptr;
    1240       23776 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1241             : 
    1242             :   // Fold if the operand is constant.
    1243             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    1244       13186 :     return getConstant(
    1245       26372 :       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
    1246             : 
    1247             :   // trunc(trunc(x)) --> trunc(x)
    1248             :   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
    1249          19 :     return getTruncateExpr(ST->getOperand(), Ty);
    1250             : 
    1251             :   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
    1252             :   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
    1253         241 :     return getTruncateOrSignExtend(SS->getOperand(), Ty);
    1254             : 
    1255             :   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
    1256             :   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
    1257         338 :     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
    1258             : 
    1259             :   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
    1260             :   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
    1261             :   // if after transforming we have at most one truncate, not counting truncates
    1262             :   // that replace other casts.
    1263        7237 :   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
    1264             :     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
    1265             :     SmallVector<const SCEV *, 4> Operands;
    1266             :     unsigned numTruncs = 0;
    1267        4165 :     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
    1268             :          ++i) {
    1269        5598 :       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty);
    1270        5177 :       if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
    1271        1038 :         numTruncs++;
    1272        2799 :       Operands.push_back(S);
    1273             :     }
    1274        1366 :     if (numTruncs < 2) {
    1275        1228 :       if (isa<SCEVAddExpr>(Op))
    1276         957 :         return getAddExpr(Operands);
    1277         271 :       else if (isa<SCEVMulExpr>(Op))
    1278         271 :         return getMulExpr(Operands);
    1279             :       else
    1280           0 :         llvm_unreachable("Unexpected SCEV type for Op.");
    1281             :     }
    1282             :     // Although we checked in the beginning that ID is not in the cache, it is
    1283             :     // possible that during recursion and different modification ID was inserted
    1284             :     // into the cache. So if we find it, just return it.
    1285         138 :     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
    1286             :       return S;
    1287             :   }
    1288             : 
    1289             :   // If the input value is a chrec scev, truncate the chrec's operands.
    1290             :   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
    1291             :     SmallVector<const SCEV *, 4> Operands;
    1292       15594 :     for (const SCEV *Op : AddRec->operands())
    1293        6240 :       Operands.push_back(getTruncateExpr(Op, Ty));
    1294        3114 :     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
    1295             :   }
    1296             : 
    1297             :   // The cast wasn't folded; create an explicit cast node. We can reuse
    1298             :   // the existing insert position since if we get here, we won't have
    1299             :   // made any changes which would invalidate it.
    1300        5790 :   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
    1301        2895 :                                                  Op, Ty);
    1302        2895 :   UniqueSCEVs.InsertNode(S, IP);
    1303        2895 :   addToLoopUseLists(S);
    1304        2895 :   return S;
    1305             : }
    1306             : 
    1307             : // Get the limit of a recurrence such that incrementing by Step cannot cause
    1308             : // signed overflow as long as the value of the recurrence within the
    1309             : // loop does not exceed this limit before incrementing.
    1310        5054 : static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
    1311             :                                                  ICmpInst::Predicate *Pred,
    1312             :                                                  ScalarEvolution *SE) {
    1313        5054 :   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
    1314        5054 :   if (SE->isKnownPositive(Step)) {
    1315        3065 :     *Pred = ICmpInst::ICMP_SLT;
    1316        9195 :     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
    1317        6130 :                            SE->getSignedRangeMax(Step));
    1318             :   }
    1319        1989 :   if (SE->isKnownNegative(Step)) {
    1320        1887 :     *Pred = ICmpInst::ICMP_SGT;
    1321        5661 :     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
    1322        3774 :                            SE->getSignedRangeMin(Step));
    1323             :   }
    1324             :   return nullptr;
    1325             : }
    1326             : 
    1327             : // Get the limit of a recurrence such that incrementing by Step cannot cause
    1328             : // unsigned overflow as long as the value of the recurrence within the loop does
    1329             : // not exceed this limit before incrementing.
    1330         536 : static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
    1331             :                                                    ICmpInst::Predicate *Pred,
    1332             :                                                    ScalarEvolution *SE) {
    1333         536 :   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
    1334         536 :   *Pred = ICmpInst::ICMP_ULT;
    1335             : 
    1336        1608 :   return SE->getConstant(APInt::getMinValue(BitWidth) -
    1337        1072 :                          SE->getUnsignedRangeMax(Step));
    1338             : }
    1339             : 
    1340             : namespace {
    1341             : 
    1342             : struct ExtendOpTraitsBase {
    1343             :   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
    1344             :                                                           unsigned);
    1345             : };
    1346             : 
    1347             : // Used to make code generic over signed and unsigned overflow.
    1348             : template <typename ExtendOp> struct ExtendOpTraits {
    1349             :   // Members present:
    1350             :   //
    1351             :   // static const SCEV::NoWrapFlags WrapType;
    1352             :   //
    1353             :   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
    1354             :   //
    1355             :   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
    1356             :   //                                           ICmpInst::Predicate *Pred,
    1357             :   //                                           ScalarEvolution *SE);
    1358             : };
    1359             : 
    1360             : template <>
    1361             : struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
    1362             :   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
    1363             : 
    1364             :   static const GetExtendExprTy GetExtendExpr;
    1365             : 
    1366         114 :   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
    1367             :                                              ICmpInst::Predicate *Pred,
    1368             :                                              ScalarEvolution *SE) {
    1369         144 :     return getSignedOverflowLimitForStep(Step, Pred, SE);
    1370             :   }
    1371             : };
    1372             : 
    1373             : const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
    1374             :     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
    1375             : 
    1376             : template <>
    1377             : struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
    1378             :   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
    1379             : 
    1380             :   static const GetExtendExprTy GetExtendExpr;
    1381             : 
    1382         238 :   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
    1383             :                                              ICmpInst::Predicate *Pred,
    1384             :                                              ScalarEvolution *SE) {
    1385         536 :     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
    1386             :   }
    1387             : };
    1388             : 
    1389             : const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
    1390             :     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
    1391             : 
    1392             : } // end anonymous namespace
    1393             : 
    1394             : // The recurrence AR has been shown to have no signed/unsigned wrap or something
    1395             : // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
    1396             : // easily prove NSW/NUW for its preincrement or postincrement sibling. This
    1397             : // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
    1398             : // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
    1399             : // expression "Step + sext/zext(PreIncAR)" is congruent with
    1400             : // "sext/zext(PostIncAR)"
    1401             : template <typename ExtendOpTy>
    1402       31310 : static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
    1403             :                                         ScalarEvolution *SE, unsigned Depth) {
    1404             :   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
    1405             :   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
    1406             : 
    1407       31310 :   const Loop *L = AR->getLoop();
    1408       31310 :   const SCEV *Start = AR->getStart();
    1409       31310 :   const SCEV *Step = AR->getStepRecurrence(*SE);
    1410             : 
    1411             :   // Check for a simple looking step prior to loop entry.
    1412             :   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
    1413             :   if (!SA)
    1414             :     return nullptr;
    1415             : 
    1416             :   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
    1417             :   // subtraction is expensive. For this purpose, perform a quick and dirty
    1418             :   // difference, by checking for Step in the operand list.
    1419             :   SmallVector<const SCEV *, 4> DiffOps;
    1420        4402 :   for (const SCEV *Op : SA->operands())
    1421        1766 :     if (Op != Step)
    1422        1172 :       DiffOps.push_back(Op);
    1423             : 
    1424         870 :   if (DiffOps.size() == SA->getNumOperands())
    1425             :     return nullptr;
    1426             : 
    1427             :   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
    1428             :   // `Step`:
    1429             : 
    1430             :   // 1. NSW/NUW flags on the step increment.
    1431             :   auto PreStartFlags =
    1432         594 :     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
    1433         594 :   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
    1434         594 :   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
    1435             :       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
    1436             : 
    1437             :   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
    1438             :   // "S+X does not sign/unsign-overflow".
    1439             :   //
    1440             : 
    1441         594 :   const SCEV *BECount = SE->getBackedgeTakenCount(L);
    1442        1408 :   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
    1443         781 :       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
    1444             :     return PreStart;
    1445             : 
    1446             :   // 2. Direct overflow check on the step operation's expression.
    1447         585 :   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
    1448        1170 :   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
    1449         585 :   const SCEV *OperandExtendedStart =
    1450             :       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
    1451             :                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
    1452         585 :   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
    1453         346 :     if (PreAR && AR->getNoWrapFlags(WrapType)) {
    1454             :       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
    1455             :       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
    1456             :       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
    1457             :       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
    1458             :     }
    1459             :     return PreStart;
    1460             :   }
    1461             : 
    1462             :   // 3. Loop precondition.
    1463             :   ICmpInst::Predicate Pred;
    1464         114 :   const SCEV *OverflowLimit =
    1465             :       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
    1466             : 
    1467         824 :   if (OverflowLimit &&
    1468         412 :       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
    1469             :     return PreStart;
    1470             : 
    1471             :   return nullptr;
    1472             : }
    1473             : 
    1474             : // Get the normalized zero or sign extended expression for this AddRec's Start.
    1475             : template <typename ExtendOpTy>
    1476       31310 : static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
    1477             :                                         ScalarEvolution *SE,
    1478             :                                         unsigned Depth) {
    1479             :   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
    1480             : 
    1481       31310 :   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
    1482       31310 :   if (!PreStart)
    1483       62086 :     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
    1484             : 
    1485             :   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
    1486             :                                              Depth),
    1487         267 :                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
    1488             : }
    1489             : 
    1490             : // Try to prove away overflow by looking at "nearby" add recurrences.  A
    1491             : // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
    1492             : // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
    1493             : //
    1494             : // Formally:
    1495             : //
    1496             : //     {S,+,X} == {S-T,+,X} + T
    1497             : //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
    1498             : //
    1499             : // If ({S-T,+,X} + T) does not overflow  ... (1)
    1500             : //
    1501             : //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
    1502             : //
    1503             : // If {S-T,+,X} does not overflow  ... (2)
    1504             : //
    1505             : //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
    1506             : //      == {Ext(S-T)+Ext(T),+,Ext(X)}
    1507             : //
    1508             : // If (S-T)+T does not overflow  ... (3)
    1509             : //
    1510             : //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
    1511             : //      == {Ext(S),+,Ext(X)} == LHS
    1512             : //
    1513             : // Thus, if (1), (2) and (3) are true for some T, then
    1514             : //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
    1515             : //
    1516             : // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
    1517             : // does not overflow" restricted to the 0th iteration.  Therefore we only need
    1518             : // to check for (1) and (2).
    1519             : //
    1520             : // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
    1521             : // is `Delta` (defined below).
    1522             : template <typename ExtendOpTy>
    1523       14478 : bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
    1524             :                                                 const SCEV *Step,
    1525             :                                                 const Loop *L) {
    1526             :   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
    1527             : 
    1528             :   // We restrict `Start` to a constant to prevent SCEV from spending too much
    1529             :   // time here.  It is correct (but more expensive) to continue with a
    1530             :   // non-constant `Start` and do a general SCEV subtraction to compute
    1531             :   // `PreStart` below.
    1532             :   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
    1533             :   if (!StartC)
    1534             :     return false;
    1535             : 
    1536             :   APInt StartAI = StartC->getAPInt();
    1537             : 
    1538       48873 :   for (unsigned Delta : {-2, -1, 1, 2}) {
    1539       86896 :     const SCEV *PreStart = getConstant(StartAI - Delta);
    1540             : 
    1541             :     FoldingSetNodeID ID;
    1542       21724 :     ID.AddInteger(scAddRecExpr);
    1543       21724 :     ID.AddPointer(PreStart);
    1544       21724 :     ID.AddPointer(Step);
    1545       21724 :     ID.AddPointer(L);
    1546       21724 :     void *IP = nullptr;
    1547             :     const auto *PreAR =
    1548             :       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    1549             : 
    1550             :     // Give up if we don't already have the add recurrence we need because
    1551             :     // actually constructing an add recurrence is relatively expensive.
    1552       28248 :     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
    1553         536 :       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
    1554         268 :       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
    1555         238 :       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
    1556             :           DeltaS, &Pred, this);
    1557         268 :       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
    1558           3 :         return true;
    1559             :     }
    1560             :   }
    1561             : 
    1562             :   return false;
    1563             : }
    1564             : 
    1565             : const SCEV *
    1566      223755 : ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
    1567             :   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
    1568             :          "This is not an extending conversion!");
    1569             :   assert(isSCEVable(Ty) &&
    1570             :          "This is not a conversion to a SCEVable type!");
    1571      223755 :   Ty = getEffectiveSCEVType(Ty);
    1572             : 
    1573             :   // Fold if the operand is constant.
    1574             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    1575      114411 :     return getConstant(
    1576      228822 :       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
    1577             : 
    1578             :   // zext(zext(x)) --> zext(x)
    1579             :   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
    1580        5531 :     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
    1581             : 
    1582             :   // Before doing any expensive analysis, check to see if we've already
    1583             :   // computed a SCEV for this Op and Ty.
    1584             :   FoldingSetNodeID ID;
    1585      103813 :   ID.AddInteger(scZeroExtend);
    1586      103813 :   ID.AddPointer(Op);
    1587      103813 :   ID.AddPointer(Ty);
    1588      103813 :   void *IP = nullptr;
    1589      103813 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1590       52294 :   if (Depth > MaxExtDepth) {
    1591          24 :     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
    1592          12 :                                                      Op, Ty);
    1593          12 :     UniqueSCEVs.InsertNode(S, IP);
    1594          12 :     addToLoopUseLists(S);
    1595          12 :     return S;
    1596             :   }
    1597             : 
    1598             :   // zext(trunc(x)) --> zext(x) or x or trunc(x)
    1599             :   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
    1600             :     // It's possible the bits taken off by the truncate were all zero bits. If
    1601             :     // so, we should be able to simplify this further.
    1602        1444 :     const SCEV *X = ST->getOperand();
    1603        2688 :     ConstantRange CR = getUnsignedRange(X);
    1604        1444 :     unsigned TruncBits = getTypeSizeInBits(ST->getType());
    1605        1444 :     unsigned NewBits = getTypeSizeInBits(Ty);
    1606        4332 :     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
    1607        2888 :             CR.zextOrTrunc(NewBits)))
    1608         200 :       return getTruncateOrZeroExtend(X, Ty);
    1609             :   }
    1610             : 
    1611             :   // If the input value is a chrec scev, and we can prove that the value
    1612             :   // did not overflow the old, smaller, value, we can zero extend all of the
    1613             :   // operands (often constants).  This allows analysis of something like
    1614             :   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
    1615             :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
    1616       27859 :     if (AR->isAffine()) {
    1617       27789 :       const SCEV *Start = AR->getStart();
    1618       27789 :       const SCEV *Step = AR->getStepRecurrence(*this);
    1619       27789 :       unsigned BitWidth = getTypeSizeInBits(AR->getType());
    1620       27789 :       const Loop *L = AR->getLoop();
    1621             : 
    1622       27789 :       if (!AR->hasNoUnsignedWrap()) {
    1623       21543 :         auto NewFlags = proveNoWrapViaConstantRanges(AR);
    1624             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
    1625             :       }
    1626             : 
    1627             :       // If we have special knowledge that this addrec won't overflow,
    1628             :       // we don't need to do any further analysis.
    1629       27789 :       if (AR->hasNoUnsignedWrap())
    1630        8482 :         return getAddRecExpr(
    1631             :             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
    1632        8482 :             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    1633             : 
    1634             :       // Check whether the backedge-taken count is SCEVCouldNotCompute.
    1635             :       // Note that this serves two purposes: It filters out loops that are
    1636             :       // simply not analyzable, and it covers the case where this code is
    1637             :       // being called from within backedge-taken count analysis, such that
    1638             :       // attempting to ask for the backedge-taken count would likely result
    1639             :       // in infinite recursion. In the later case, the analysis code will
    1640             :       // cope with a conservative value, and it will take care to purge
    1641             :       // that value once it has finished.
    1642       19307 :       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
    1643       19307 :       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
    1644             :         // Manually compute the final value for AR, checking for
    1645             :         // overflow.
    1646             : 
    1647             :         // Check whether the backedge-taken count can be losslessly casted to
    1648             :         // the addrec's type. The count is always unsigned.
    1649             :         const SCEV *CastedMaxBECount =
    1650       16872 :           getTruncateOrZeroExtend(MaxBECount, Start->getType());
    1651             :         const SCEV *RecastedMaxBECount =
    1652       16872 :           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
    1653       16872 :         if (MaxBECount == RecastedMaxBECount) {
    1654       31152 :           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
    1655             :           // Check whether Start+Step*MaxBECount has no unsigned overflow.
    1656       15576 :           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
    1657       15576 :                                         SCEV::FlagAnyWrap, Depth + 1);
    1658       15576 :           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
    1659             :                                                           SCEV::FlagAnyWrap,
    1660             :                                                           Depth + 1),
    1661       15576 :                                                WideTy, Depth + 1);
    1662       15576 :           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
    1663             :           const SCEV *WideMaxBECount =
    1664       15576 :             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
    1665             :           const SCEV *OperandExtendedAdd =
    1666       15576 :             getAddExpr(WideStart,
    1667             :                        getMulExpr(WideMaxBECount,
    1668             :                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
    1669             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1670       15576 :                        SCEV::FlagAnyWrap, Depth + 1);
    1671       15576 :           if (ZAdd == OperandExtendedAdd) {
    1672             :             // Cache knowledge of AR NUW, which is propagated to this AddRec.
    1673             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
    1674             :             // Return the expression with the addrec on the outside.
    1675         751 :             return getAddRecExpr(
    1676             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1677             :                                                          Depth + 1),
    1678             :                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
    1679         751 :                 AR->getNoWrapFlags());
    1680             :           }
    1681             :           // Similar to above, only this time treat the step value as signed.
    1682             :           // This covers loops that count down.
    1683       14825 :           OperandExtendedAdd =
    1684       14825 :             getAddExpr(WideStart,
    1685             :                        getMulExpr(WideMaxBECount,
    1686             :                                   getSignExtendExpr(Step, WideTy, Depth + 1),
    1687             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1688             :                        SCEV::FlagAnyWrap, Depth + 1);
    1689       14825 :           if (ZAdd == OperandExtendedAdd) {
    1690             :             // Cache knowledge of AR NW, which is propagated to this AddRec.
    1691             :             // Negative step causes unsigned wrap, but it still can't self-wrap.
    1692             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
    1693             :             // Return the expression with the addrec on the outside.
    1694         960 :             return getAddRecExpr(
    1695             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1696             :                                                          Depth + 1),
    1697             :                 getSignExtendExpr(Step, Ty, Depth + 1), L,
    1698         960 :                 AR->getNoWrapFlags());
    1699             :           }
    1700             :         }
    1701             :       }
    1702             : 
    1703             :       // Normally, in the cases we can prove no-overflow via a
    1704             :       // backedge guarding condition, we can also compute a backedge
    1705             :       // taken count for the loop.  The exceptions are assumptions and
    1706             :       // guards present in the loop -- SCEV is not great at exploiting
    1707             :       // these to compute max backedge taken counts, but can still use
    1708             :       // these to prove lack of overflow.  Use this fact to avoid
    1709             :       // doing extra work that may not pay off.
    1710       20022 :       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
    1711        2426 :           !AC.assumptions().empty()) {
    1712             :         // If the backedge is guarded by a comparison with the pre-inc
    1713             :         // value the addrec is safe. Also, if the entry is guarded by
    1714             :         // a comparison with the start value and the backedge is
    1715             :         // guarded by a comparison with the post-inc value, the addrec
    1716             :         // is safe.
    1717       15203 :         if (isKnownPositive(Step)) {
    1718        8502 :           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
    1719        8502 :                                       getUnsignedRangeMax(Step));
    1720        5622 :           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
    1721        2788 :               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
    1722             :             // Cache knowledge of AR NUW, which is propagated to this
    1723             :             // AddRec.
    1724             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
    1725             :             // Return the expression with the addrec on the outside.
    1726          79 :             return getAddRecExpr(
    1727             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1728             :                                                          Depth + 1),
    1729             :                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
    1730          79 :                 AR->getNoWrapFlags());
    1731             :           }
    1732       12369 :         } else if (isKnownNegative(Step)) {
    1733       36714 :           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
    1734       36714 :                                       getSignedRangeMin(Step));
    1735       14161 :           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
    1736        1923 :               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
    1737             :             // Cache knowledge of AR NW, which is propagated to this
    1738             :             // AddRec.  Negative step causes unsigned wrap, but it
    1739             :             // still can't self-wrap.
    1740             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
    1741             :             // Return the expression with the addrec on the outside.
    1742       10469 :             return getAddRecExpr(
    1743             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1744             :                                                          Depth + 1),
    1745             :                 getSignExtendExpr(Step, Ty, Depth + 1), L,
    1746       10469 :                 AR->getNoWrapFlags());
    1747             :           }
    1748             :         }
    1749             :       }
    1750             : 
    1751        7048 :       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
    1752             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
    1753           3 :         return getAddRecExpr(
    1754             :             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
    1755           3 :             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    1756             :       }
    1757             :     }
    1758             : 
    1759             :   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
    1760             :     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
    1761        7530 :     if (SA->hasNoUnsignedWrap()) {
    1762             :       // If the addition does not unsign overflow then we can, by definition,
    1763             :       // commute the zero extension with the addition operation.
    1764             :       SmallVector<const SCEV *, 4> Ops;
    1765        1980 :       for (const auto *Op : SA->operands())
    1766         792 :         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
    1767         396 :       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
    1768             :     }
    1769             :   }
    1770             : 
    1771             :   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
    1772             :     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
    1773        2885 :     if (SM->hasNoUnsignedWrap()) {
    1774             :       // If the multiply does not unsign overflow then we can, by definition,
    1775             :       // commute the zero extension with the multiply operation.
    1776             :       SmallVector<const SCEV *, 4> Ops;
    1777        3905 :       for (const auto *Op : SM->operands())
    1778        1562 :         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
    1779         781 :       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
    1780             :     }
    1781             : 
    1782             :     // zext(2^K * (trunc X to iN)) to iM ->
    1783             :     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
    1784             :     //
    1785             :     // Proof:
    1786             :     //
    1787             :     //     zext(2^K * (trunc X to iN)) to iM
    1788             :     //   = zext((trunc X to iN) << K) to iM
    1789             :     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
    1790             :     //     (because shl removes the top K bits)
    1791             :     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
    1792             :     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
    1793             :     //
    1794        2104 :     if (SM->getNumOperands() == 2)
    1795        2083 :       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
    1796        1931 :         if (MulLHS->getAPInt().isPowerOf2())
    1797             :           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
    1798          22 :             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
    1799             :                                MulLHS->getAPInt().logBase2();
    1800          22 :             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
    1801          11 :             return getMulExpr(
    1802             :                 getZeroExtendExpr(MulLHS, Ty),
    1803             :                 getZeroExtendExpr(
    1804             :                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
    1805          11 :                 SCEV::FlagNUW, Depth + 1);
    1806             :           }
    1807             :   }
    1808             : 
    1809             :   // The cast wasn't folded; create an explicit cast node.
    1810             :   // Recompute the insert position, as it may have been invalidated.
    1811       30150 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1812       58330 :   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
    1813       29165 :                                                    Op, Ty);
    1814       29165 :   UniqueSCEVs.InsertNode(S, IP);
    1815       29165 :   addToLoopUseLists(S);
    1816       29165 :   return S;
    1817             : }
    1818             : 
    1819             : const SCEV *
    1820      143630 : ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
    1821             :   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
    1822             :          "This is not an extending conversion!");
    1823             :   assert(isSCEVable(Ty) &&
    1824             :          "This is not a conversion to a SCEVable type!");
    1825      143630 :   Ty = getEffectiveSCEVType(Ty);
    1826             : 
    1827             :   // Fold if the operand is constant.
    1828             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    1829       92721 :     return getConstant(
    1830      185442 :       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
    1831             : 
    1832             :   // sext(sext(x)) --> sext(x)
    1833             :   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
    1834         271 :     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
    1835             : 
    1836             :   // sext(zext(x)) --> zext(x)
    1837             :   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
    1838         200 :     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
    1839             : 
    1840             :   // Before doing any expensive analysis, check to see if we've already
    1841             :   // computed a SCEV for this Op and Ty.
    1842             :   FoldingSetNodeID ID;
    1843       50438 :   ID.AddInteger(scSignExtend);
    1844       50438 :   ID.AddPointer(Op);
    1845       50438 :   ID.AddPointer(Ty);
    1846       50438 :   void *IP = nullptr;
    1847       50438 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1848             :   // Limit recursion depth.
    1849       38286 :   if (Depth > MaxExtDepth) {
    1850           8 :     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
    1851           4 :                                                      Op, Ty);
    1852           4 :     UniqueSCEVs.InsertNode(S, IP);
    1853           4 :     addToLoopUseLists(S);
    1854           4 :     return S;
    1855             :   }
    1856             : 
    1857             :   // sext(trunc(x)) --> sext(x) or x or trunc(x)
    1858             :   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
    1859             :     // It's possible the bits taken off by the truncate were all sign bits. If
    1860             :     // so, we should be able to simplify this further.
    1861         294 :     const SCEV *X = ST->getOperand();
    1862         583 :     ConstantRange CR = getSignedRange(X);
    1863         294 :     unsigned TruncBits = getTypeSizeInBits(ST->getType());
    1864         294 :     unsigned NewBits = getTypeSizeInBits(Ty);
    1865         882 :     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
    1866         588 :             CR.sextOrTrunc(NewBits)))
    1867           5 :       return getTruncateOrSignExtend(X, Ty);
    1868             :   }
    1869             : 
    1870             :   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
    1871             :   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
    1872        5585 :     if (SA->getNumOperands() == 2) {
    1873        5307 :       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
    1874             :       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
    1875        5307 :       if (SMul && SC1) {
    1876        1664 :         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
    1877             :           const APInt &C1 = SC1->getAPInt();
    1878             :           const APInt &C2 = SC2->getAPInt();
    1879        3055 :           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
    1880        1692 :               C2.ugt(C1) && C2.isPowerOf2())
    1881          21 :             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
    1882             :                               getSignExtendExpr(SMul, Ty, Depth + 1),
    1883          21 :                               SCEV::FlagAnyWrap, Depth + 1);
    1884             :         }
    1885             :       }
    1886             :     }
    1887             : 
    1888             :     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
    1889        5564 :     if (SA->hasNoSignedWrap()) {
    1890             :       // If the addition does not sign overflow then we can, by definition,
    1891             :       // commute the sign extension with the addition operation.
    1892             :       SmallVector<const SCEV *, 4> Ops;
    1893        2655 :       for (const auto *Op : SA->operands())
    1894        1062 :         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
    1895         531 :       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
    1896             :     }
    1897             :   }
    1898             :   // If the input value is a chrec scev, and we can prove that the value
    1899             :   // did not overflow the old, smaller, value, we can sign extend all of the
    1900             :   // operands (often constants).  This allows analysis of something like
    1901             :   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
    1902             :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
    1903       18705 :     if (AR->isAffine()) {
    1904       18652 :       const SCEV *Start = AR->getStart();
    1905       18652 :       const SCEV *Step = AR->getStepRecurrence(*this);
    1906       18652 :       unsigned BitWidth = getTypeSizeInBits(AR->getType());
    1907       18652 :       const Loop *L = AR->getLoop();
    1908             : 
    1909       18652 :       if (!AR->hasNoSignedWrap()) {
    1910       11082 :         auto NewFlags = proveNoWrapViaConstantRanges(AR);
    1911             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
    1912             :       }
    1913             : 
    1914             :       // If we have special knowledge that this addrec won't overflow,
    1915             :       // we don't need to do any further analysis.
    1916       18652 :       if (AR->hasNoSignedWrap())
    1917       10113 :         return getAddRecExpr(
    1918             :             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
    1919       10113 :             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
    1920             : 
    1921             :       // Check whether the backedge-taken count is SCEVCouldNotCompute.
    1922             :       // Note that this serves two purposes: It filters out loops that are
    1923             :       // simply not analyzable, and it covers the case where this code is
    1924             :       // being called from within backedge-taken count analysis, such that
    1925             :       // attempting to ask for the backedge-taken count would likely result
    1926             :       // in infinite recursion. In the later case, the analysis code will
    1927             :       // cope with a conservative value, and it will take care to purge
    1928             :       // that value once it has finished.
    1929        8539 :       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
    1930        8539 :       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
    1931             :         // Manually compute the final value for AR, checking for
    1932             :         // overflow.
    1933             : 
    1934             :         // Check whether the backedge-taken count can be losslessly casted to
    1935             :         // the addrec's type. The count is always unsigned.
    1936             :         const SCEV *CastedMaxBECount =
    1937        5167 :           getTruncateOrZeroExtend(MaxBECount, Start->getType());
    1938             :         const SCEV *RecastedMaxBECount =
    1939        5167 :           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
    1940        5167 :         if (MaxBECount == RecastedMaxBECount) {
    1941        9784 :           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
    1942             :           // Check whether Start+Step*MaxBECount has no signed overflow.
    1943        4892 :           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
    1944        4892 :                                         SCEV::FlagAnyWrap, Depth + 1);
    1945        4892 :           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
    1946             :                                                           SCEV::FlagAnyWrap,
    1947             :                                                           Depth + 1),
    1948        4892 :                                                WideTy, Depth + 1);
    1949        4892 :           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
    1950             :           const SCEV *WideMaxBECount =
    1951        4892 :             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
    1952             :           const SCEV *OperandExtendedAdd =
    1953        4892 :             getAddExpr(WideStart,
    1954             :                        getMulExpr(WideMaxBECount,
    1955             :                                   getSignExtendExpr(Step, WideTy, Depth + 1),
    1956             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1957        4892 :                        SCEV::FlagAnyWrap, Depth + 1);
    1958        4892 :           if (SAdd == OperandExtendedAdd) {
    1959             :             // Cache knowledge of AR NSW, which is propagated to this AddRec.
    1960             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
    1961             :             // Return the expression with the addrec on the outside.
    1962         274 :             return getAddRecExpr(
    1963             :                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
    1964             :                                                          Depth + 1),
    1965             :                 getSignExtendExpr(Step, Ty, Depth + 1), L,
    1966         274 :                 AR->getNoWrapFlags());
    1967             :           }
    1968             :           // Similar to above, only this time treat the step value as unsigned.
    1969             :           // This covers loops that count up with an unsigned step.
    1970        4618 :           OperandExtendedAdd =
    1971        4618 :             getAddExpr(WideStart,
    1972             :                        getMulExpr(WideMaxBECount,
    1973             :                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
    1974             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1975             :                        SCEV::FlagAnyWrap, Depth + 1);
    1976        4618 :           if (SAdd == OperandExtendedAdd) {
    1977             :             // If AR wraps around then
    1978             :             //
    1979             :             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
    1980             :             // => SAdd != OperandExtendedAdd
    1981             :             //
    1982             :             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
    1983             :             // (SAdd == OperandExtendedAdd => AR is NW)
    1984             : 
    1985             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
    1986             : 
    1987             :             // Return the expression with the addrec on the outside.
    1988           1 :             return getAddRecExpr(
    1989             :                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
    1990             :                                                          Depth + 1),
    1991             :                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
    1992           1 :                 AR->getNoWrapFlags());
    1993             :           }
    1994             :         }
    1995             :       }
    1996             : 
    1997             :       // Normally, in the cases we can prove no-overflow via a
    1998             :       // backedge guarding condition, we can also compute a backedge
    1999             :       // taken count for the loop.  The exceptions are assumptions and
    2000             :       // guards present in the loop -- SCEV is not great at exploiting
    2001             :       // these to compute max backedge taken counts, but can still use
    2002             :       // these to prove lack of overflow.  Use this fact to avoid
    2003             :       // doing extra work that may not pay off.
    2004             : 
    2005       11627 :       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
    2006        3363 :           !AC.assumptions().empty()) {
    2007             :         // If the backedge is guarded by a comparison with the pre-inc
    2008             :         // value the addrec is safe. Also, if the entry is guarded by
    2009             :         // a comparison with the start value and the backedge is
    2010             :         // guarded by a comparison with the post-inc value, the addrec
    2011             :         // is safe.
    2012             :         ICmpInst::Predicate Pred;
    2013             :         const SCEV *OverflowLimit =
    2014        4910 :             getSignedOverflowLimitForStep(Step, &Pred, this);
    2015        9718 :         if (OverflowLimit &&
    2016        9491 :             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
    2017        4683 :              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
    2018             :           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
    2019             :           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
    2020         178 :           return getAddRecExpr(
    2021             :               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
    2022         178 :               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    2023             :         }
    2024             :       }
    2025             : 
    2026             :       // If Start and Step are constants, check if we can apply this
    2027             :       // transformation:
    2028             :       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
    2029             :       auto *SC1 = dyn_cast<SCEVConstant>(Start);
    2030             :       auto *SC2 = dyn_cast<SCEVConstant>(Step);
    2031        8086 :       if (SC1 && SC2) {
    2032             :         const APInt &C1 = SC1->getAPInt();
    2033             :         const APInt &C2 = SC2->getAPInt();
    2034        5350 :         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
    2035         676 :             C2.isPowerOf2()) {
    2036         656 :           Start = getSignExtendExpr(Start, Ty, Depth + 1);
    2037         656 :           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
    2038         656 :                                             AR->getNoWrapFlags());
    2039         656 :           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
    2040         656 :                             SCEV::FlagAnyWrap, Depth + 1);
    2041             :         }
    2042             :       }
    2043             : 
    2044        7430 :       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
    2045             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
    2046           0 :         return getAddRecExpr(
    2047             :             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
    2048           0 :             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    2049             :       }
    2050             :     }
    2051             : 
    2052             :   // If the input value is provably positive and we could not simplify
    2053             :   // away the sext build a zext instead.
    2054       26503 :   if (isKnownNonNegative(Op))
    2055        8292 :     return getZeroExtendExpr(Op, Ty, Depth + 1);
    2056             : 
    2057             :   // The cast wasn't folded; create an explicit cast node.
    2058             :   // Recompute the insert position, as it may have been invalidated.
    2059       18211 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    2060       36044 :   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
    2061       18022 :                                                    Op, Ty);
    2062       18022 :   UniqueSCEVs.InsertNode(S, IP);
    2063       18022 :   addToLoopUseLists(S);
    2064       18022 :   return S;
    2065             : }
    2066             : 
    2067             : /// getAnyExtendExpr - Return a SCEV for the given operand extended with
    2068             : /// unspecified bits out to the given type.
    2069        8876 : const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
    2070             :                                               Type *Ty) {
    2071             :   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
    2072             :          "This is not an extending conversion!");
    2073             :   assert(isSCEVable(Ty) &&
    2074             :          "This is not a conversion to a SCEVable type!");
    2075        8876 :   Ty = getEffectiveSCEVType(Ty);
    2076             : 
    2077             :   // Sign-extend negative constants.
    2078             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    2079       11884 :     if (SC->getAPInt().isNegative())
    2080        3903 :       return getSignExtendExpr(Op, Ty);
    2081             : 
    2082             :   // Peel off a truncate cast.
    2083             :   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
    2084         112 :     const SCEV *NewOp = T->getOperand();
    2085         112 :     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
    2086           0 :       return getAnyExtendExpr(NewOp, Ty);
    2087         112 :     return getTruncateOrNoop(NewOp, Ty);
    2088             :   }
    2089             : 
    2090             :   // Next try a zext cast. If the cast is folded, use it.
    2091        4861 :   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
    2092        4861 :   if (!isa<SCEVZeroExtendExpr>(ZExt))
    2093             :     return ZExt;
    2094             : 
    2095             :   // Next try a sext cast. If the cast is folded, use it.
    2096        2122 :   const SCEV *SExt = getSignExtendExpr(Op, Ty);
    2097        2122 :   if (!isa<SCEVSignExtendExpr>(SExt))
    2098             :     return SExt;
    2099             : 
    2100             :   // Force the cast to be folded into the operands of an addrec.
    2101             :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
    2102             :     SmallVector<const SCEV *, 4> Ops;
    2103        3660 :     for (const SCEV *Op : AR->operands())
    2104        1464 :       Ops.push_back(getAnyExtendExpr(Op, Ty));
    2105         732 :     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
    2106             :   }
    2107             : 
    2108             :   // If the expression is obviously signed, use the sext cast value.
    2109        1245 :   if (isa<SCEVSMaxExpr>(Op))
    2110             :     return SExt;
    2111             : 
    2112             :   // Absent any other information, use the zext cast value.
    2113        1245 :   return ZExt;
    2114             : }
    2115             : 
    2116             : /// Process the given Ops list, which is a list of operands to be added under
    2117             : /// the given scale, update the given map. This is a helper function for
    2118             : /// getAddRecExpr. As an example of what it does, given a sequence of operands
    2119             : /// that would form an add expression like this:
    2120             : ///
    2121             : ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
    2122             : ///
    2123             : /// where A and B are constants, update the map with these values:
    2124             : ///
    2125             : ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
    2126             : ///
    2127             : /// and add 13 + A*B*29 to AccumulatedConstant.
    2128             : /// This will allow getAddRecExpr to produce this:
    2129             : ///
    2130             : ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
    2131             : ///
    2132             : /// This form often exposes folding opportunities that are hidden in
    2133             : /// the original operand list.
    2134             : ///
    2135             : /// Return true iff it appears that any interesting folding opportunities
    2136             : /// may be exposed. This helps getAddRecExpr short-circuit extra work in
    2137             : /// the common case where no interesting opportunities are present, and
    2138             : /// is also used as a check to avoid infinite recursion.
    2139             : static bool
    2140      451161 : CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
    2141             :                              SmallVectorImpl<const SCEV *> &NewOps,
    2142             :                              APInt &AccumulatedConstant,
    2143             :                              const SCEV *const *Ops, size_t NumOperands,
    2144             :                              const APInt &Scale,
    2145             :                              ScalarEvolution &SE) {
    2146             :   bool Interesting = false;
    2147             : 
    2148             :   // Iterate over the add operands. They are sorted, with constants first.
    2149             :   unsigned i = 0;
    2150      782181 :   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
    2151      331020 :     ++i;
    2152             :     // Pull a buried constant out to the outside.
    2153      992292 :     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
    2154             :       Interesting = true;
    2155      662040 :     AccumulatedConstant += Scale * C->getAPInt();
    2156      331020 :   }
    2157             : 
    2158             :   // Next comes everything else. We're especially interested in multiplies
    2159             :   // here, but they're in the middle, so just visit the rest with one loop.
    2160     3278999 :   for (; i != NumOperands; ++i) {
    2161     1413919 :     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
    2162     1527184 :     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
    2163             :       APInt NewScale =
    2164      737230 :           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
    2165     1454941 :       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
    2166             :         // A multiplication of a constant with another add; recurse.
    2167             :         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
    2168        4239 :         Interesting |=
    2169        4239 :           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
    2170             :                                        Add->op_begin(), Add->getNumOperands(),
    2171             :                                        NewScale, SE);
    2172             :       } else {
    2173             :         // A multiplication of a constant with some other value. Update
    2174             :         // the map.
    2175     1465982 :         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
    2176      732991 :         const SCEV *Key = SE.getMulExpr(MulOps);
    2177      732991 :         auto Pair = M.insert({Key, NewScale});
    2178      732991 :         if (Pair.second) {
    2179      730362 :           NewOps.push_back(Pair.first->first);
    2180             :         } else {
    2181        2629 :           Pair.first->second += NewScale;
    2182             :           // The map already had an entry for this value, which may indicate
    2183             :           // a folding opportunity.
    2184             :           Interesting = true;
    2185             :         }
    2186             :       }
    2187             :     } else {
    2188             :       // An ordinary operand. Update the map.
    2189             :       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
    2190      676689 :           M.insert({Ops[i], Scale});
    2191      676689 :       if (Pair.second) {
    2192      462801 :         NewOps.push_back(Pair.first->first);
    2193             :       } else {
    2194      213888 :         Pair.first->second += Scale;
    2195             :         // The map already had an entry for this value, which may indicate
    2196             :         // a folding opportunity.
    2197             :         Interesting = true;
    2198             :       }
    2199             :     }
    2200             :   }
    2201             : 
    2202      451161 :   return Interesting;
    2203             : }
    2204             : 
    2205             : // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
    2206             : // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
    2207             : // can't-overflow flags for the operation if possible.
    2208             : static SCEV::NoWrapFlags
    2209     4241254 : StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
    2210             :                       const SmallVectorImpl<const SCEV *> &Ops,
    2211             :                       SCEV::NoWrapFlags Flags) {
    2212             :   using namespace std::placeholders;
    2213             : 
    2214             :   using OBO = OverflowingBinaryOperator;
    2215             : 
    2216             :   bool CanAnalyze =
    2217             :       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
    2218             :   (void)CanAnalyze;
    2219             :   assert(CanAnalyze && "don't call from other places!");
    2220             : 
    2221             :   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
    2222             :   SCEV::NoWrapFlags SignOrUnsignWrap =
    2223             :       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
    2224             : 
    2225             :   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
    2226             :   auto IsKnownNonNegative = [&](const SCEV *S) {
    2227     1240078 :     return SE->isKnownNonNegative(S);
    2228     1240078 :   };
    2229             : 
    2230     4966242 :   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
    2231             :     Flags =
    2232             :         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
    2233             : 
    2234             :   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
    2235             : 
    2236     3867574 :   if (SignOrUnsignWrap != SignOrUnsignMask &&
    2237    10402041 :       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
    2238     2883365 :       isa<SCEVConstant>(Ops[0])) {
    2239             : 
    2240             :     auto Opcode = [&] {
    2241     2486603 :       switch (Type) {
    2242             :       case scAddExpr:
    2243             :         return Instruction::Add;
    2244      893057 :       case scMulExpr:
    2245             :         return Instruction::Mul;
    2246           0 :       default:
    2247           0 :         llvm_unreachable("Unexpected SCEV op.");
    2248             :       }
    2249             :     }();
    2250             : 
    2251             :     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
    2252             : 
    2253             :     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
    2254     2486603 :     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
    2255             :       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    2256     6370812 :           Opcode, C, OBO::NoSignedWrap);
    2257     6370812 :       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
    2258             :         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
    2259             :     }
    2260             : 
    2261             :     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
    2262     2486603 :     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
    2263             :       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    2264     7418214 :           Instruction::Add, C, OBO::NoUnsignedWrap);
    2265     7418214 :       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
    2266             :         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
    2267             :     }
    2268             :   }
    2269             : 
    2270     4241254 :   return Flags;
    2271             : }
    2272             : 
    2273      734950 : bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
    2274     1098693 :   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
    2275             : }
    2276             : 
    2277             : /// Get a canonical add expression, or something simpler if possible.
    2278     2419228 : const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
    2279             :                                         SCEV::NoWrapFlags Flags,
    2280             :                                         unsigned Depth) {
    2281             :   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
    2282             :          "only nuw or nsw allowed");
    2283             :   assert(!Ops.empty() && "Cannot get empty add!");
    2284     2419228 :   if (Ops.size() == 1) return Ops[0];
    2285             : #ifndef NDEBUG
    2286             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    2287             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    2288             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    2289             :            "SCEVAddExpr operand types don't match!");
    2290             : #endif
    2291             : 
    2292             :   // Sort by complexity, this groups all similar expression types together.
    2293     2319113 :   GroupByComplexity(Ops, &LI, DT);
    2294             : 
    2295     2319113 :   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
    2296             : 
    2297             :   // If there are any constants, fold them together.
    2298     2319113 :   unsigned Idx = 0;
    2299     2319113 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    2300     1930615 :     ++Idx;
    2301             :     assert(Idx < Ops.size());
    2302     4017810 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    2303             :       // We found two constants, fold them together!
    2304     2702574 :       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
    2305      900858 :       if (Ops.size() == 2) return Ops[0];
    2306       78290 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    2307       78290 :       LHSC = cast<SCEVConstant>(Ops[0]);
    2308       78290 :     }
    2309             : 
    2310             :     // If we are left with a constant zero being added, strip it off.
    2311     2216094 :     if (LHSC->getValue()->isZero()) {
    2312      245511 :       Ops.erase(Ops.begin());
    2313      245511 :       --Idx;
    2314             :     }
    2315             : 
    2316     1108047 :     if (Ops.size() == 1) return Ops[0];
    2317             :   }
    2318             : 
    2319             :   // Limit recursion calls depth.
    2320     1256574 :   if (Depth > MaxArithDepth)
    2321        3085 :     return getOrCreateAddExpr(Ops, Flags);
    2322             : 
    2323             :   // Okay, check to see if the same value occurs in the operand list more than
    2324             :   // once.  If so, merge them together into an multiply expression.  Since we
    2325             :   // sorted the list, these values are required to be adjacent.
    2326     1253489 :   Type *Ty = Ops[0]->getType();
    2327             :   bool FoundMatch = false;
    2328     3358961 :   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
    2329     6317739 :     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
    2330             :       // Scan ahead to count how many equal operands there are.
    2331             :       unsigned Count = 2;
    2332        1617 :       while (i+Count != e && Ops[i+Count] == Ops[i])
    2333         126 :         ++Count;
    2334             :       // Merge the values into a multiply.
    2335         929 :       const SCEV *Scale = getConstant(Ty, Count);
    2336        1858 :       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
    2337         929 :       if (Ops.size() == Count)
    2338             :         return Mul;
    2339         488 :       Ops[i] = Mul;
    2340         488 :       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
    2341         488 :       --i; e -= Count - 1;
    2342             :       FoundMatch = true;
    2343             :     }
    2344     1253048 :   if (FoundMatch)
    2345         454 :     return getAddExpr(Ops, Flags, Depth + 1);
    2346             : 
    2347             :   // Check for truncates. If all the operands are truncated from the same
    2348             :   // type, see if factoring out the truncate would permit the result to be
    2349             :   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
    2350             :   // if the contents of the resulting outer trunc fold to something simple.
    2351     1252594 :   auto FindTruncSrcType = [&]() -> Type * {
    2352             :     // We're ultimately looking to fold an addrec of truncs and muls of only
    2353             :     // constants and truncs, so if we find any other types of SCEV
    2354             :     // as operands of the addrec then we bail and return nullptr here.
    2355             :     // Otherwise, we return the type of the operand of a trunc that we find.
    2356     2505188 :     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
    2357        1579 :       return T->getOperand()->getType();
    2358             :     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
    2359      442232 :       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
    2360             :       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
    2361        1701 :         return T->getOperand()->getType();
    2362             :     }
    2363             :     return nullptr;
    2364     1252594 :   };
    2365     1252594 :   if (auto *SrcType = FindTruncSrcType()) {
    2366             :     SmallVector<const SCEV *, 8> LargeOps;
    2367             :     bool Ok = true;
    2368             :     // Check all the operands to see if they can be represented in the
    2369             :     // source type of the truncate.
    2370       10334 :     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
    2371       15724 :       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
    2372        1922 :         if (T->getOperand()->getType() != SrcType) {
    2373             :           Ok = false;
    2374             :           break;
    2375             :         }
    2376        1901 :         LargeOps.push_back(T->getOperand());
    2377             :       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
    2378        2290 :         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
    2379             :       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
    2380             :         SmallVector<const SCEV *, 8> LargeMulOps;
    2381        7601 :         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
    2382             :           if (const SCEVTruncateExpr *T =
    2383        5357 :                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
    2384        2262 :             if (T->getOperand()->getType() != SrcType) {
    2385             :               Ok = false;
    2386             :               break;
    2387             :             }
    2388        2256 :             LargeMulOps.push_back(T->getOperand());
    2389             :           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
    2390        2482 :             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
    2391             :           } else {
    2392             :             Ok = false;
    2393             :             break;
    2394             :           }
    2395             :         }
    2396        2863 :         if (Ok)
    2397        2116 :           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
    2398             :       } else {
    2399             :         Ok = false;
    2400             :         break;
    2401             :       }
    2402             :     }
    2403        3280 :     if (Ok) {
    2404             :       // Evaluate the expression in the larger type.
    2405        1896 :       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
    2406             :       // If it folds to something simple, use it. Otherwise, don't.
    2407        1896 :       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
    2408           7 :         return getTruncateExpr(Fold, Ty);
    2409             :     }
    2410             :   }
    2411             : 
    2412             :   // Skip past any other cast SCEVs.
    2413     3945478 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
    2414       58898 :     ++Idx;
    2415             : 
    2416             :   // If there are add operands they would be next.
    2417     1252587 :   if (Idx < Ops.size()) {
    2418             :     bool DeletedAdd = false;
    2419     3031314 :     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
    2420      621891 :       if (Ops.size() > AddOpsInlineThreshold ||
    2421      310945 :           Add->getNumOperands() > AddOpsInlineThreshold)
    2422             :         break;
    2423             :       // If we have an add, expand the add operands onto the end of the operands
    2424             :       // list.
    2425      310945 :       Ops.erase(Ops.begin()+Idx);
    2426      621890 :       Ops.append(Add->op_begin(), Add->op_end());
    2427             :       DeletedAdd = true;
    2428      310945 :     }
    2429             : 
    2430             :     // If we deleted at least one add, we added operands to the end of the list,
    2431             :     // and they are not necessarily sorted.  Recurse to resort and resimplify
    2432             :     // any operands we just acquired.
    2433     1204712 :     if (DeletedAdd)
    2434      288398 :       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2435             :   }
    2436             : 
    2437             :   // Skip over the add expression until we get to a multiply.
    2438     2844696 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
    2439           1 :     ++Idx;
    2440             : 
    2441             :   // Check to see if there are any folding opportunities present with
    2442             :   // operands multiplied by constant values.
    2443     2796817 :   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
    2444      446922 :     uint64_t BitWidth = getTypeSizeInBits(Ty);
    2445             :     DenseMap<const SCEV *, APInt> M;
    2446             :     SmallVector<const SCEV *, 8> NewOps;
    2447      446922 :     APInt AccumulatedConstant(BitWidth, 0);
    2448      893844 :     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
    2449             :                                      Ops.data(), Ops.size(),
    2450      446922 :                                      APInt(BitWidth, 1), *this)) {
    2451             :       struct APIntCompare {
    2452             :         bool operator()(const APInt &LHS, const APInt &RHS) const {
    2453             :           return LHS.ult(RHS);
    2454             :         }
    2455             :       };
    2456             : 
    2457             :       // Some interesting folding opportunity is present, so its worthwhile to
    2458             :       // re-generate the operands list. Group the operands by constant scale,
    2459             :       // to avoid multiplying by the same constant scale multiple times.
    2460             :       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
    2461      665070 :       for (const SCEV *NewOp : NewOps)
    2462      224909 :         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
    2463             :       // Re-generate the operands list.
    2464             :       Ops.clear();
    2465      215252 :       if (AccumulatedConstant != 0)
    2466      196797 :         Ops.push_back(getConstant(AccumulatedConstant));
    2467      438140 :       for (auto &MulOp : MulOpLists)
    2468      445776 :         if (MulOp.first != 0)
    2469        9102 :           Ops.push_back(getMulExpr(
    2470             :               getConstant(MulOp.first),
    2471             :               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
    2472             :               SCEV::FlagAnyWrap, Depth + 1));
    2473      215252 :       if (Ops.empty())
    2474       12444 :         return getZero(Ty);
    2475      202808 :       if (Ops.size() == 1)
    2476      200313 :         return Ops[0];
    2477        2495 :       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2478             :     }
    2479             :   }
    2480             : 
    2481             :   // If we are adding something to a multiply expression, make sure the
    2482             :   // something is not already an operand of the multiply.  If so, merge it into
    2483             :   // the multiply.
    2484     5304229 :   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
    2485             :     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
    2486     1608371 :     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
    2487     1083138 :       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
    2488     1083138 :       if (isa<SCEVConstant>(MulOpSCEV))
    2489             :         continue;
    2490    24742050 :       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
    2491    48333816 :         if (MulOpSCEV == Ops[AddOp]) {
    2492             :           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
    2493         126 :           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
    2494         126 :           if (Mul->getNumOperands() != 2) {
    2495             :             // If the multiply has more than two operands, we must get the
    2496             :             // Y*Z term.
    2497             :             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
    2498             :                                                 Mul->op_begin()+MulOp);
    2499          68 :             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
    2500          34 :             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
    2501             :           }
    2502         252 :           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
    2503         126 :           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
    2504         126 :           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
    2505         126 :                                             SCEV::FlagAnyWrap, Depth + 1);
    2506         126 :           if (Ops.size() == 2) return OuterMul;
    2507          44 :           if (AddOp < Idx) {
    2508           3 :             Ops.erase(Ops.begin()+AddOp);
    2509           3 :             Ops.erase(Ops.begin()+Idx-1);
    2510             :           } else {
    2511          41 :             Ops.erase(Ops.begin()+Idx);
    2512          41 :             Ops.erase(Ops.begin()+AddOp-1);
    2513             :           }
    2514          44 :           Ops.push_back(OuterMul);
    2515          44 :           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2516             :         }
    2517             : 
    2518             :       // Check this multiply against other multiplies being added together.
    2519     6161885 :       for (unsigned OtherMulIdx = Idx+1;
    2520    18149037 :            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
    2521             :            ++OtherMulIdx) {
    2522             :         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
    2523             :         // If MulOp occurs in OtherMul, we can fold the two multiplies
    2524             :         // together.
    2525    16839279 :         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
    2526    16839279 :              OMulOp != e; ++OMulOp)
    2527    22505072 :           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
    2528             :             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
    2529        4196 :             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
    2530        4196 :             if (Mul->getNumOperands() != 2) {
    2531             :               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
    2532             :                                                   Mul->op_begin()+MulOp);
    2533        4974 :               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
    2534        2487 :               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
    2535             :             }
    2536        4196 :             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
    2537        4196 :             if (OtherMul->getNumOperands() != 2) {
    2538             :               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
    2539        3827 :                                                   OtherMul->op_begin()+OMulOp);
    2540        7654 :               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
    2541        3827 :               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
    2542             :             }
    2543        8392 :             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
    2544             :             const SCEV *InnerMulSum =
    2545        4196 :                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
    2546        4196 :             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
    2547        4196 :                                               SCEV::FlagAnyWrap, Depth + 1);
    2548        4196 :             if (Ops.size() == 2) return OuterMul;
    2549        1435 :             Ops.erase(Ops.begin()+Idx);
    2550        1435 :             Ops.erase(Ops.begin()+OtherMulIdx-1);
    2551        1435 :             Ops.push_back(OuterMul);
    2552        1435 :             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2553             :           }
    2554             :       }
    2555             :     }
    2556             :   }
    2557             : 
    2558             :   // If there are any add recurrences in the operands list, see if any other
    2559             :   // added values are loop invariant.  If so, we can fold them into the
    2560             :   // recurrence.
    2561     1348077 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
    2562        8405 :     ++Idx;
    2563             : 
    2564             :   // Scan over all recurrences, trying to fold loop invariants into them.
    2565     2083921 :   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
    2566             :     // Scan all of the other operands to this add and add them to the vector if
    2567             :     // they are loop invariant w.r.t. the recurrence.
    2568             :     SmallVector<const SCEV *, 8> LIOps;
    2569      317284 :     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
    2570      317284 :     const Loop *AddRecLoop = AddRec->getLoop();
    2571      959900 :     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    2572     1285232 :       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
    2573      310356 :         LIOps.push_back(Ops[i]);
    2574      310356 :         Ops.erase(Ops.begin()+i);
    2575      310356 :         --i; --e;
    2576             :       }
    2577             : 
    2578             :     // If we found some loop invariants, fold them into the recurrence.
    2579      317284 :     if (!LIOps.empty()) {
    2580             :       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
    2581      610070 :       LIOps.push_back(AddRec->getStart());
    2582             : 
    2583             :       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
    2584      305035 :                                              AddRec->op_end());
    2585             :       // This follows from the fact that the no-wrap flags on the outer add
    2586             :       // expression are applicable on the 0th iteration, when the add recurrence
    2587             :       // will be equal to its start value.
    2588      610070 :       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
    2589             : 
    2590             :       // Build the new addrec. Propagate the NUW and NSW flags if both the
    2591             :       // outer add and the inner addrec are guaranteed to have no overflow.
    2592             :       // Always propagate NW.
    2593      305035 :       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
    2594      305035 :       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
    2595             : 
    2596             :       // If all of the other operands were loop invariant, we are done.
    2597      305035 :       if (Ops.size() == 1) return NewRec;
    2598             : 
    2599             :       // Otherwise, add the folded AddRec by the non-invariant parts.
    2600         842 :       for (unsigned i = 0;; ++i)
    2601        4362 :         if (Ops[i] == AddRec) {
    2602         918 :           Ops[i] = NewRec;
    2603             :           break;
    2604             :         }
    2605         918 :       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2606             :     }
    2607             : 
    2608             :     // Okay, if there weren't any loop invariants to be folded, check to see if
    2609             :     // there are multiple AddRec's with the same loop induction variable being
    2610             :     // added together.  If so, we can fold them.
    2611       12249 :     for (unsigned OtherIdx = Idx+1;
    2612       34711 :          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
    2613             :          ++OtherIdx) {
    2614             :       // We expect the AddRecExpr's to be sorted in reverse dominance order,
    2615             :       // so that the 1st found AddRecExpr is dominated by all others.
    2616             :       assert(DT.dominates(
    2617             :            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
    2618             :            AddRec->getLoop()->getHeader()) &&
    2619             :         "AddRecExprs are not sorted in reverse dominance order?");
    2620        7629 :       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
    2621             :         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
    2622             :         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
    2623        7629 :                                                AddRec->op_end());
    2624       45805 :         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
    2625             :              ++OtherIdx) {
    2626             :           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
    2627        7634 :           if (OtherAddRec->getLoop() == AddRecLoop) {
    2628       23724 :             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
    2629       23724 :                  i != e; ++i) {
    2630       32864 :               if (i >= AddRecOps.size()) {
    2631         684 :                 AddRecOps.append(OtherAddRec->op_begin()+i,
    2632             :                                  OtherAddRec->op_end());
    2633         342 :                 break;
    2634             :               }
    2635             :               SmallVector<const SCEV *, 2> TwoOps = {
    2636       48270 :                   AddRecOps[i], OtherAddRec->getOperand(i)};
    2637       32180 :               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
    2638             :             }
    2639        7634 :             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
    2640             :           }
    2641             :         }
    2642             :         // Step size has changed, so we cannot guarantee no self-wraparound.
    2643       15258 :         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
    2644        7629 :         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2645             :       }
    2646             :     }
    2647             : 
    2648             :     // Otherwise couldn't fold anything into this recurrence.  Move onto the
    2649             :     // next one.
    2650             :   }
    2651             : 
    2652             :   // Okay, it looks like we really DO need an add expr.  Check to see if we
    2653             :   // already have one, otherwise create a new one.
    2654      431951 :   return getOrCreateAddExpr(Ops, Flags);
    2655             : }
    2656             : 
    2657             : const SCEV *
    2658      435036 : ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
    2659             :                                     SCEV::NoWrapFlags Flags) {
    2660             :   FoldingSetNodeID ID;
    2661      435036 :   ID.AddInteger(scAddExpr);
    2662     3445420 :   for (const SCEV *Op : Ops)
    2663     1505192 :     ID.AddPointer(Op);
    2664      435036 :   void *IP = nullptr;
    2665             :   SCEVAddExpr *S =
    2666             :       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    2667      435036 :   if (!S) {
    2668      250451 :     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    2669             :     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    2670             :     S = new (SCEVAllocator)
    2671      500902 :         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
    2672      250451 :     UniqueSCEVs.InsertNode(S, IP);
    2673      250451 :     addToLoopUseLists(S);
    2674             :   }
    2675             :   S->setNoWrapFlags(Flags);
    2676      435036 :   return S;
    2677             : }
    2678             : 
    2679             : const SCEV *
    2680      435700 : ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
    2681             :                                     SCEV::NoWrapFlags Flags) {
    2682             :   FoldingSetNodeID ID;
    2683      435700 :   ID.AddInteger(scMulExpr);
    2684     1375970 :   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    2685     1880540 :     ID.AddPointer(Ops[i]);
    2686      435700 :   void *IP = nullptr;
    2687             :   SCEVMulExpr *S =
    2688             :     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    2689      435700 :   if (!S) {
    2690      109066 :     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    2691             :     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    2692      218132 :     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
    2693             :                                         O, Ops.size());
    2694      109066 :     UniqueSCEVs.InsertNode(S, IP);
    2695      109066 :     addToLoopUseLists(S);
    2696             :   }
    2697             :   S->setNoWrapFlags(Flags);
    2698      435700 :   return S;
    2699             : }
    2700             : 
    2701             : static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
    2702        8864 :   uint64_t k = i*j;
    2703        8864 :   if (j > 1 && k / j != i) Overflow = true;
    2704             :   return k;
    2705             : }
    2706             : 
    2707             : /// Compute the result of "n choose k", the binomial coefficient.  If an
    2708             : /// intermediate computation overflows, Overflow will be set and the return will
    2709             : /// be garbage. Overflow is not cleared on absence of overflow.
    2710       13394 : static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
    2711             :   // We use the multiplicative formula:
    2712             :   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
    2713             :   // At each iteration, we take the n-th term of the numeral and divide by the
    2714             :   // (k-n)th term of the denominator.  This division will always produce an
    2715             :   // integral result, and helps reduce the chance of overflow in the
    2716             :   // intermediate computations. However, we can still overflow even when the
    2717             :   // final result would fit.
    2718             : 
    2719       13394 :   if (n == 0 || n == k) return 1;
    2720        8711 :   if (k > n) return 0;
    2721             : 
    2722        8711 :   if (k > n/2)
    2723        1553 :     k = n-k;
    2724             : 
    2725             :   uint64_t r = 1;
    2726       26429 :   for (uint64_t i = 1; i <= k; ++i) {
    2727        8859 :     r = umul_ov(r, n-(i-1), Overflow);
    2728        8859 :     r /= i;
    2729             :   }
    2730             :   return r;
    2731             : }
    2732             : 
    2733             : /// Determine if any of the operands in this SCEV are a constant or if
    2734             : /// any of the add or multiply expressions in this SCEV contain a constant.
    2735       55337 : static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
    2736             :   struct FindConstantInAddMulChain {
    2737             :     bool FoundConstant = false;
    2738             : 
    2739             :     bool follow(const SCEV *S) {
    2740      191225 :       FoundConstant |= isa<SCEVConstant>(S);
    2741      191225 :       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
    2742             :     }
    2743             : 
    2744             :     bool isDone() const {
    2745       79421 :       return FoundConstant;
    2746             :     }
    2747             :   };
    2748             : 
    2749       55337 :   FindConstantInAddMulChain F;
    2750       55337 :   SCEVTraversal<FindConstantInAddMulChain> ST(F);
    2751       55337 :   ST.visitAll(StartExpr);
    2752      110674 :   return F.FoundConstant;
    2753             : }
    2754             : 
    2755             : /// Get a canonical multiply expression, or something simpler if possible.
    2756     1994027 : const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
    2757             :                                         SCEV::NoWrapFlags Flags,
    2758             :                                         unsigned Depth) {
    2759             :   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
    2760             :          "only nuw or nsw allowed");
    2761             :   assert(!Ops.empty() && "Cannot get empty mul!");
    2762     1994027 :   if (Ops.size() == 1) return Ops[0];
    2763             : #ifndef NDEBUG
    2764             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    2765             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    2766             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    2767             :            "SCEVMulExpr operand types don't match!");
    2768             : #endif
    2769             : 
    2770             :   // Sort by complexity, this groups all similar expression types together.
    2771     1251296 :   GroupByComplexity(Ops, &LI, DT);
    2772             : 
    2773     1251296 :   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
    2774             : 
    2775             :   // Limit recursion calls depth.
    2776     1251296 :   if (Depth > MaxArithDepth)
    2777       16616 :     return getOrCreateMulExpr(Ops, Flags);
    2778             : 
    2779             :   // If there are any constants, fold them together.
    2780             :   unsigned Idx = 0;
    2781     1234680 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    2782             : 
    2783     1189718 :     if (Ops.size() == 2)
    2784             :       // C1*(C2+V) -> C1*C2 + C1*V
    2785     1129405 :       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
    2786             :         // If any of Add's ops are Adds or Muls with a constant, apply this
    2787             :         // transformation as well.
    2788             :         //
    2789             :         // TODO: There are some cases where this transformation is not
    2790             :         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
    2791             :         // this transformation should be narrowed down.
    2792       63511 :         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
    2793      159813 :           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
    2794             :                                        SCEV::FlagAnyWrap, Depth + 1),
    2795             :                             getMulExpr(LHSC, Add->getOperand(1),
    2796             :                                        SCEV::FlagAnyWrap, Depth + 1),
    2797       53271 :                             SCEV::FlagAnyWrap, Depth + 1);
    2798             : 
    2799             :     ++Idx;
    2800     1180550 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    2801             :       // We found two constants, fold them together!
    2802             :       ConstantInt *Fold =
    2803     1828767 :           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
    2804      609589 :       Ops[0] = getConstant(Fold);
    2805      609589 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    2806      609589 :       if (Ops.size() == 1) return Ops[0];
    2807       44103 :       LHSC = cast<SCEVConstant>(Ops[0]);
    2808       44103 :     }
    2809             : 
    2810             :     // If we are left with a constant one being multiplied, strip it off.
    2811     1141922 :     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
    2812       42488 :       Ops.erase(Ops.begin());
    2813             :       --Idx;
    2814      528473 :     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
    2815             :       // If we have a multiply of zero, it will always be zero.
    2816             :       return Ops[0];
    2817      522614 :     } else if (Ops[0]->isAllOnesValue()) {
    2818             :       // If we have a mul by -1 of an add, try distributing the -1 among the
    2819             :       // add operands.
    2820      403158 :       if (Ops.size() == 2) {
    2821      401754 :         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
    2822             :           SmallVector<const SCEV *, 4> NewOps;
    2823             :           bool AnyFolded = false;
    2824       46057 :           for (const SCEV *AddOp : Add->operands()) {
    2825       39424 :             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
    2826       19712 :                                          Depth + 1);
    2827       19712 :             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
    2828       19712 :             NewOps.push_back(Mul);
    2829             :           }
    2830        6633 :           if (AnyFolded)
    2831        5548 :             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
    2832             :         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
    2833             :           // Negation preserves a recurrence's no self-wrap property.
    2834             :           SmallVector<const SCEV *, 4> Operands;
    2835      358364 :           for (const SCEV *AddRecOp : AddRec->operands())
    2836      288462 :             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
    2837             :                                           Depth + 1));
    2838             : 
    2839      139804 :           return getAddRecExpr(Operands, AddRec->getLoop(),
    2840       69902 :                                AddRec->getNoWrapFlags(SCEV::FlagNW));
    2841             :         }
    2842             :       }
    2843             :     }
    2844             : 
    2845      489652 :     if (Ops.size() == 1)
    2846       37384 :       return Ops[0];
    2847             :   }
    2848             : 
    2849             :   // Skip over the add expression until we get to a multiply.
    2850     2020774 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
    2851      148773 :     ++Idx;
    2852             : 
    2853             :   // If there are mul operands inline them all into this expression.
    2854      497230 :   if (Idx < Ops.size()) {
    2855             :     bool DeletedMul = false;
    2856      482188 :     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
    2857       51332 :       if (Ops.size() > MulOpsInlineThreshold)
    2858             :         break;
    2859             :       // If we have an mul, expand the mul operands onto the end of the
    2860             :       // operands list.
    2861       50966 :       Ops.erase(Ops.begin()+Idx);
    2862      101932 :       Ops.append(Mul->op_begin(), Mul->op_end());
    2863             :       DeletedMul = true;
    2864       50966 :     }
    2865             : 
    2866             :     // If we deleted at least one mul, we added operands to the end of the
    2867             :     // list, and they are not necessarily sorted.  Recurse to resort and
    2868             :     // resimplify any operands we just acquired.
    2869      431222 :     if (DeletedMul)
    2870       49415 :       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2871             :   }
    2872             : 
    2873             :   // If there are any add recurrences in the operands list, see if any other
    2874             :   // added values are loop invariant.  If so, we can fold them into the
    2875             :   // recurrence.
    2876     1363004 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
    2877       26634 :     ++Idx;
    2878             : 
    2879             :   // Scan over all recurrences, trying to fold loop invariants into them.
    2880     1262697 :   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
    2881             :     // Scan all of the other operands to this mul and add them to the vector
    2882             :     // if they are loop invariant w.r.t. the recurrence.
    2883             :     SmallVector<const SCEV *, 8> LIOps;
    2884       30481 :     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
    2885       30481 :     const Loop *AddRecLoop = AddRec->getLoop();
    2886       98534 :     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    2887      136106 :       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
    2888       28418 :         LIOps.push_back(Ops[i]);
    2889       28418 :         Ops.erase(Ops.begin()+i);
    2890       28418 :         --i; --e;
    2891             :       }
    2892             : 
    2893             :     // If we found some loop invariants, fold them into the recurrence.
    2894       30481 :     if (!LIOps.empty()) {
    2895             :       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
    2896             :       SmallVector<const SCEV *, 4> NewOps;
    2897       28115 :       NewOps.reserve(AddRec->getNumOperands());
    2898       28115 :       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
    2899       86093 :       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
    2900      115956 :         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
    2901             :                                     SCEV::FlagAnyWrap, Depth + 1));
    2902             : 
    2903             :       // Build the new addrec. Propagate the NUW and NSW flags if both the
    2904             :       // outer mul and the inner addrec are guaranteed to have no overflow.
    2905             :       //
    2906             :       // No self-wrap cannot be guaranteed after changing the step size, but
    2907             :       // will be inferred if either NUW or NSW is true.
    2908       28115 :       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
    2909       28115 :       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
    2910             : 
    2911             :       // If all of the other operands were loop invariant, we are done.
    2912       28115 :       if (Ops.size() == 1) return NewRec;
    2913             : 
    2914             :       // Otherwise, multiply the folded AddRec by the non-invariant parts.
    2915          16 :       for (unsigned i = 0;; ++i)
    2916        2178 :         if (Ops[i] == AddRec) {
    2917        1065 :           Ops[i] = NewRec;
    2918             :           break;
    2919             :         }
    2920        1065 :       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2921             :     }
    2922             : 
    2923             :     // Okay, if there weren't any loop invariants to be folded, check to see
    2924             :     // if there are multiple AddRec's with the same loop induction variable
    2925             :     // being multiplied together.  If so, we can fold them.
    2926             : 
    2927             :     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
    2928             :     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
    2929             :     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
    2930             :     //   ]]],+,...up to x=2n}.
    2931             :     // Note that the arguments to choose() are always integers with values
    2932             :     // known at compile time, never SCEV objects.
    2933             :     //
    2934             :     // The implementation avoids pointless extra computations when the two
    2935             :     // addrec's are of different length (mathematically, it's equivalent to
    2936             :     // an infinite stream of zeros on the right).
    2937             :     bool OpsModified = false;
    2938        3616 :     for (unsigned OtherIdx = Idx+1;
    2939        9173 :          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
    2940             :          ++OtherIdx) {
    2941             :       const SCEVAddRecExpr *OtherAddRec =
    2942             :         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
    2943        1726 :       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
    2944        1088 :         continue;
    2945             : 
    2946             :       // Limit max number of arguments to avoid creation of unreasonably big
    2947             :       // SCEVAddRecs with very complex operands.
    2948        4540 :       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
    2949        1726 :           MaxAddRecSize)
    2950        1088 :         continue;
    2951             : 
    2952         638 :       bool Overflow = false;
    2953             :       Type *Ty = AddRec->getType();
    2954         638 :       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
    2955             :       SmallVector<const SCEV*, 7> AddRecOps;
    2956        3785 :       for (int x = 0, xe = AddRec->getNumOperands() +
    2957        1276 :              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
    2958        2509 :         const SCEV *Term = getZero(Ty);
    2959        9934 :         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
    2960        7425 :           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
    2961       20819 :           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
    2962       14850 :                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
    2963       13394 :                z < ze && !Overflow; ++z) {
    2964        5969 :             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
    2965             :             uint64_t Coeff;
    2966        5969 :             if (LargerThan64Bits)
    2967             :               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
    2968             :             else
    2969        5964 :               Coeff = Coeff1*Coeff2;
    2970        5969 :             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
    2971        5969 :             const SCEV *Term1 = AddRec->getOperand(y-z);
    2972        5969 :             const SCEV *Term2 = OtherAddRec->getOperand(z);
    2973        5969 :             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
    2974             :                                                SCEV::FlagAnyWrap, Depth + 1),
    2975             :                               SCEV::FlagAnyWrap, Depth + 1);
    2976             :           }
    2977             :         }
    2978        2509 :         AddRecOps.push_back(Term);
    2979             :       }
    2980         638 :       if (!Overflow) {
    2981         638 :         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
    2982         638 :                                               SCEV::FlagAnyWrap);
    2983         638 :         if (Ops.size() == 2) return NewAddRec;
    2984         163 :         Ops[Idx] = NewAddRec;
    2985         163 :         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
    2986             :         OpsModified = true;
    2987             :         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
    2988             :         if (!AddRec)
    2989             :           break;
    2990             :       }
    2991             :     }
    2992        1890 :     if (OpsModified)
    2993         141 :       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2994             : 
    2995             :     // Otherwise couldn't fold anything into this recurrence.  Move onto the
    2996             :     // next one.
    2997             :   }
    2998             : 
    2999             :   // Okay, it looks like we really DO need an mul expr.  Check to see if we
    3000             :   // already have one, otherwise create a new one.
    3001      419084 :   return getOrCreateMulExpr(Ops, Flags);
    3002             : }
    3003             : 
    3004             : /// Represents an unsigned remainder expression based on unsigned division.
    3005         481 : const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
    3006             :                                          const SCEV *RHS) {
    3007             :   assert(getEffectiveSCEVType(LHS->getType()) ==
    3008             :          getEffectiveSCEVType(RHS->getType()) &&
    3009             :          "SCEVURemExpr operand types don't match!");
    3010             : 
    3011             :   // Short-circuit easy cases
    3012             :   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
    3013             :     // If constant is one, the result is trivial
    3014         706 :     if (RHSC->getValue()->isOne())
    3015           2 :       return getZero(LHS->getType()); // X urem 1 --> 0
    3016             : 
    3017             :     // If constant is a power of two, fold into a zext(trunc(LHS)).
    3018         352 :     if (RHSC->getAPInt().isPowerOf2()) {
    3019         185 :       Type *FullTy = LHS->getType();
    3020             :       Type *TruncTy =
    3021         370 :           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
    3022         185 :       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
    3023             :     }
    3024             :   }
    3025             : 
    3026             :   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
    3027         295 :   const SCEV *UDiv = getUDivExpr(LHS, RHS);
    3028         295 :   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
    3029         295 :   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
    3030             : }
    3031             : 
    3032             : /// Get a canonical unsigned division expression, or something simpler if
    3033             : /// possible.
    3034       26912 : const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
    3035             :                                          const SCEV *RHS) {
    3036             :   assert(getEffectiveSCEVType(LHS->getType()) ==
    3037             :          getEffectiveSCEVType(RHS->getType()) &&
    3038             :          "SCEVUDivExpr operand types don't match!");
    3039             : 
    3040             :   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
    3041       52854 :     if (RHSC->getValue()->isOne())
    3042             :       return LHS;                               // X udiv 1 --> x
    3043             :     // If the denominator is zero, the result of the udiv is undefined. Don't
    3044             :     // try to analyze it, because the resolution chosen here may differ from
    3045             :     // the resolution chosen in other parts of the compiler.
    3046       16282 :     if (!RHSC->getValue()->isZero()) {
    3047             :       // Determine if the division can be folded into the operands of
    3048             :       // its operands.
    3049             :       // TODO: Generalize this to non-constants by using known-bits information.
    3050       16281 :       Type *Ty = LHS->getType();
    3051       16281 :       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
    3052       16281 :       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
    3053             :       // For non-power-of-two values, effectively round the value up to the
    3054             :       // nearest power of two.
    3055       16281 :       if (!RHSC->getAPInt().isPowerOf2())
    3056             :         ++MaxShiftAmt;
    3057             :       IntegerType *ExtTy =
    3058       32562 :         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
    3059             :       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
    3060             :         if (const SCEVConstant *Step =
    3061         405 :             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
    3062             :           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
    3063             :           const APInt &StepInt = Step->getAPInt();
    3064             :           const APInt &DivInt = RHSC->getAPInt();
    3065        1197 :           if (!StepInt.urem(DivInt) &&
    3066          24 :               getZeroExtendExpr(AR, ExtTy) ==
    3067          48 :               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
    3068             :                             getZeroExtendExpr(Step, ExtTy),
    3069             :                             AR->getLoop(), SCEV::FlagAnyWrap)) {
    3070             :             SmallVector<const SCEV *, 4> Operands;
    3071          65 :             for (const SCEV *Op : AR->operands())
    3072          26 :               Operands.push_back(getUDivExpr(Op, RHS));
    3073          13 :             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
    3074             :           }
    3075             :           /// Get a canonical UDivExpr for a recurrence.
    3076             :           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
    3077             :           // We can currently only fold X%N if X is constant.
    3078         378 :           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
    3079        1377 :           if (StartC && !DivInt.urem(StepInt) &&
    3080         285 :               getZeroExtendExpr(AR, ExtTy) ==
    3081         570 :               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
    3082             :                             getZeroExtendExpr(Step, ExtTy),
    3083             :                             AR->getLoop(), SCEV::FlagAnyWrap)) {
    3084             :             const APInt &StartInt = StartC->getAPInt();
    3085         166 :             const APInt &StartRem = StartInt.urem(StepInt);
    3086         166 :             if (StartRem != 0)
    3087          36 :               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
    3088             :                                   AR->getLoop(), SCEV::FlagNW);
    3089             :           }
    3090             :         }
    3091             :       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
    3092             :       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
    3093             :         SmallVector<const SCEV *, 4> Operands;
    3094       12758 :         for (const SCEV *Op : M->operands())
    3095        5178 :           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
    3096        2402 :         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
    3097             :           // Find an operand that's safely divisible.
    3098           2 :           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
    3099           2 :             const SCEV *Op = M->getOperand(i);
    3100           2 :             const SCEV *Div = getUDivExpr(Op, RHSC);
    3101           2 :             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
    3102           4 :               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
    3103             :                                                       M->op_end());
    3104           2 :               Operands[i] = Div;
    3105           2 :               return getMulExpr(Operands);
    3106             :             }
    3107             :           }
    3108             :       }
    3109             : 
    3110             :       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
    3111             :       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
    3112             :         if (auto *DivisorConstant =
    3113          18 :                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
    3114          18 :           bool Overflow = false;
    3115             :           APInt NewRHS =
    3116          18 :               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
    3117          18 :           if (Overflow) {
    3118           4 :             return getConstant(RHSC->getType(), 0, false);
    3119             :           }
    3120          16 :           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
    3121             :         }
    3122             :       }
    3123             : 
    3124             :       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
    3125             :       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
    3126             :         SmallVector<const SCEV *, 4> Operands;
    3127       11930 :         for (const SCEV *Op : A->operands())
    3128        4885 :           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
    3129        2160 :         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
    3130             :           Operands.clear();
    3131          55 :           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
    3132         110 :             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
    3133         110 :             if (isa<SCEVUDivExpr>(Op) ||
    3134          55 :                 getMulExpr(Op, RHS) != A->getOperand(i))
    3135             :               break;
    3136           0 :             Operands.push_back(Op);
    3137             :           }
    3138          55 :           if (Operands.size() == A->getNumOperands())
    3139           0 :             return getAddExpr(Operands);
    3140             :         }
    3141             :       }
    3142             : 
    3143             :       // Fold if both operands are constant.
    3144             :       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
    3145        9791 :         Constant *LHSCV = LHSC->getValue();
    3146        9791 :         Constant *RHSCV = RHSC->getValue();
    3147        9791 :         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
    3148        9791 :                                                                    RHSCV)));
    3149             :       }
    3150             :     }
    3151             :   }
    3152             : 
    3153             :   FoldingSetNodeID ID;
    3154        6943 :   ID.AddInteger(scUDivExpr);
    3155        6943 :   ID.AddPointer(LHS);
    3156        6943 :   ID.AddPointer(RHS);
    3157        6943 :   void *IP = nullptr;
    3158        6943 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    3159        8370 :   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
    3160             :                                              LHS, RHS);
    3161        4185 :   UniqueSCEVs.InsertNode(S, IP);
    3162        4185 :   addToLoopUseLists(S);
    3163        4185 :   return S;
    3164             : }
    3165             : 
    3166           0 : static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
    3167           0 :   APInt A = C1->getAPInt().abs();
    3168           0 :   APInt B = C2->getAPInt().abs();
    3169           0 :   uint32_t ABW = A.getBitWidth();
    3170           0 :   uint32_t BBW = B.getBitWidth();
    3171             : 
    3172           0 :   if (ABW > BBW)
    3173           0 :     B = B.zext(ABW);
    3174           0 :   else if (ABW < BBW)
    3175           0 :     A = A.zext(BBW);
    3176             : 
    3177           0 :   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
    3178             : }
    3179             : 
    3180             : /// Get a canonical unsigned division expression, or something simpler if
    3181             : /// possible. There is no representation for an exact udiv in SCEV IR, but we
    3182             : /// can attempt to remove factors from the LHS and RHS.  We can't do this when
    3183             : /// it's not exact because the udiv may be clearing bits.
    3184         169 : const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
    3185             :                                               const SCEV *RHS) {
    3186             :   // TODO: we could try to find factors in all sorts of things, but for now we
    3187             :   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
    3188             :   // end of this file for inspiration.
    3189             : 
    3190             :   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
    3191           1 :   if (!Mul || !Mul->hasNoUnsignedWrap())
    3192         169 :     return getUDivExpr(LHS, RHS);
    3193             : 
    3194             :   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
    3195             :     // If the mulexpr multiplies by a constant, then that constant must be the
    3196             :     // first element of the mulexpr.
    3197           0 :     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
    3198           0 :       if (LHSCst == RHSCst) {
    3199             :         SmallVector<const SCEV *, 2> Operands;
    3200           0 :         Operands.append(Mul->op_begin() + 1, Mul->op_end());
    3201           0 :         return getMulExpr(Operands);
    3202             :       }
    3203             : 
    3204             :       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
    3205             :       // that there's a factor provided by one of the other terms. We need to
    3206             :       // check.
    3207           0 :       APInt Factor = gcd(LHSCst, RHSCst);
    3208           0 :       if (!Factor.isIntN(1)) {
    3209             :         LHSCst =
    3210           0 :             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
    3211             :         RHSCst =
    3212           0 :             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
    3213             :         SmallVector<const SCEV *, 2> Operands;
    3214           0 :         Operands.push_back(LHSCst);
    3215           0 :         Operands.append(Mul->op_begin() + 1, Mul->op_end());
    3216           0 :         LHS = getMulExpr(Operands);
    3217             :         RHS = RHSCst;
    3218             :         Mul = dyn_cast<SCEVMulExpr>(LHS);
    3219             :         if (!Mul)
    3220           0 :           return getUDivExactExpr(LHS, RHS);
    3221             :       }
    3222             :     }
    3223             :   }
    3224             : 
    3225           0 :   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
    3226           0 :     if (Mul->getOperand(i) == RHS) {
    3227             :       SmallVector<const SCEV *, 2> Operands;
    3228           0 :       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
    3229           0 :       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
    3230           0 :       return getMulExpr(Operands);
    3231             :     }
    3232             :   }
    3233             : 
    3234           0 :   return getUDivExpr(LHS, RHS);
    3235             : }
    3236             : 
    3237             : /// Get an add recurrence expression for the specified loop.  Simplify the
    3238             : /// expression as much as possible.
    3239      153392 : const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
    3240             :                                            const Loop *L,
    3241             :                                            SCEV::NoWrapFlags Flags) {
    3242             :   SmallVector<const SCEV *, 4> Operands;
    3243      153392 :   Operands.push_back(Start);
    3244      153392 :   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
    3245         209 :     if (StepChrec->getLoop() == L) {
    3246         136 :       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
    3247          68 :       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
    3248             :     }
    3249             : 
    3250      153324 :   Operands.push_back(Step);
    3251      153324 :   return getAddRecExpr(Operands, L, Flags);
    3252             : }
    3253             : 
    3254             : /// Get an add recurrence expression for the specified loop.  Simplify the
    3255             : /// expression as much as possible.
    3256             : const SCEV *
    3257      706316 : ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
    3258             :                                const Loop *L, SCEV::NoWrapFlags Flags) {
    3259      706316 :   if (Operands.size() == 1) return Operands[0];
    3260             : #ifndef NDEBUG
    3261             :   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
    3262             :   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
    3263             :     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
    3264             :            "SCEVAddRecExpr operand types don't match!");
    3265             :   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
    3266             :     assert(isLoopInvariant(Operands[i], L) &&
    3267             :            "SCEVAddRecExpr operand is not loop-invariant!");
    3268             : #endif
    3269             : 
    3270      689585 :   if (Operands.back()->isZero()) {
    3271             :     Operands.pop_back();
    3272       18740 :     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
    3273             :   }
    3274             : 
    3275             :   // It's tempting to want to call getMaxBackedgeTakenCount count here and
    3276             :   // use that information to infer NUW and NSW flags. However, computing a
    3277             :   // BE count requires calling getAddRecExpr, so we may not yet have a
    3278             :   // meaningful BE count at this point (and if we don't, we'd be stuck
    3279             :   // with a SCEVCouldNotCompute as the cached BE count).
    3280             : 
    3281      670845 :   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
    3282             : 
    3283             :   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
    3284      670845 :   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
    3285      136458 :     const Loop *NestedLoop = NestedAR->getLoop();
    3286      136458 :     if (L->contains(NestedLoop)
    3287      136458 :             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
    3288      391223 :             : (!NestedLoop->contains(L) &&
    3289      236614 :                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
    3290             :       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
    3291           0 :                                                   NestedAR->op_end());
    3292           0 :       Operands[0] = NestedAR->getStart();
    3293             :       // AddRecs require their operands be loop-invariant with respect to their
    3294             :       // loops. Don't perform this transformation if it would break this
    3295             :       // requirement.
    3296             :       bool AllInvariant = all_of(
    3297           0 :           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
    3298             : 
    3299           0 :       if (AllInvariant) {
    3300             :         // Create a recurrence for the outer loop with the same step size.
    3301             :         //
    3302             :         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
    3303             :         // inner recurrence has the same property.
    3304             :         SCEV::NoWrapFlags OuterFlags =
    3305           0 :           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
    3306             : 
    3307           0 :         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
    3308             :         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
    3309           0 :           return isLoopInvariant(Op, NestedLoop);
    3310           0 :         });
    3311             : 
    3312           0 :         if (AllInvariant) {
    3313             :           // Ok, both add recurrences are valid after the transformation.
    3314             :           //
    3315             :           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
    3316             :           // the outer recurrence has the same property.
    3317             :           SCEV::NoWrapFlags InnerFlags =
    3318           0 :             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
    3319           0 :           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
    3320             :         }
    3321             :       }
    3322             :       // Reset Operands to its original state.
    3323           0 :       Operands[0] = NestedAR;
    3324             :     }
    3325             :   }
    3326             : 
    3327             :   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
    3328             :   // already have one, otherwise create a new one.
    3329             :   FoldingSetNodeID ID;
    3330      670845 :   ID.AddInteger(scAddRecExpr);
    3331     2025978 :   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
    3332     2710266 :     ID.AddPointer(Operands[i]);
    3333      670845 :   ID.AddPointer(L);
    3334      670845 :   void *IP = nullptr;
    3335             :   SCEVAddRecExpr *S =
    3336             :     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    3337      670845 :   if (!S) {
    3338      160722 :     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
    3339             :     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
    3340      321444 :     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
    3341      160722 :                                            O, Operands.size(), L);
    3342      160722 :     UniqueSCEVs.InsertNode(S, IP);
    3343      160722 :     addToLoopUseLists(S);
    3344             :   }
    3345             :   S->setNoWrapFlags(Flags);
    3346             :   return S;
    3347             : }
    3348             : 
    3349             : const SCEV *
    3350      186688 : ScalarEvolution::getGEPExpr(GEPOperator *GEP,
    3351             :                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
    3352      186688 :   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
    3353             :   // getSCEV(Base)->getType() has the same address space as Base->getType()
    3354             :   // because SCEV::getType() preserves the address space.
    3355      186688 :   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
    3356             :   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
    3357             :   // instruction to its SCEV, because the Instruction may be guarded by control
    3358             :   // flow and the no-overflow bits may not be valid for the expression in any
    3359             :   // context. This can be fixed similarly to how these flags are handled for
    3360             :   // adds.
    3361      186688 :   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
    3362             :                                              : SCEV::FlagAnyWrap;
    3363             : 
    3364             :   const SCEV *TotalOffset = getZero(IntPtrTy);
    3365             :   // The array size is unimportant. The first thing we do on CurTy is getting
    3366             :   // its element type.
    3367      186688 :   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
    3368      854514 :   for (const SCEV *IndexExpr : IndexExprs) {
    3369             :     // Compute the (potentially symbolic) offset in bytes for this index.
    3370             :     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
    3371             :       // For a struct, add the member offset.
    3372       30504 :       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
    3373       30504 :       unsigned FieldNo = Index->getZExtValue();
    3374       30504 :       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
    3375             : 
    3376             :       // Add the field offset to the running total offset.
    3377       30504 :       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
    3378             : 
    3379             :       // Update CurTy to the type of the field at Index.
    3380       30504 :       CurTy = STy->getTypeAtIndex(Index);
    3381             :     } else {
    3382             :       // Update CurTy to its element type.
    3383      303409 :       CurTy = cast<SequentialType>(CurTy)->getElementType();
    3384             :       // For an array, add the element offset, explicitly scaled.
    3385      303409 :       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
    3386             :       // Getelementptr indices are signed.
    3387      303409 :       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
    3388             : 
    3389             :       // Multiply the index by the element size to compute the element offset.
    3390      303409 :       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
    3391             : 
    3392             :       // Add the element offset to the running total offset.
    3393      303409 :       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
    3394             :     }
    3395             :   }
    3396             : 
    3397             :   // Add the total offset from all the GEP indices to the base.
    3398      186688 :   return getAddExpr(BaseExpr, TotalOffset, Wrap);
    3399             : }
    3400             : 
    3401        4424 : const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
    3402             :                                          const SCEV *RHS) {
    3403        8848 :   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
    3404        8848 :   return getSMaxExpr(Ops);
    3405             : }
    3406             : 
    3407             : const SCEV *
    3408       21633 : ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3409             :   assert(!Ops.empty() && "Cannot get empty smax!");
    3410       21633 :   if (Ops.size() == 1) return Ops[0];
    3411             : #ifndef NDEBUG
    3412             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    3413             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    3414             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    3415             :            "SCEVSMaxExpr operand types don't match!");
    3416             : #endif
    3417             : 
    3418             :   // Sort by complexity, this groups all similar expression types together.
    3419       21633 :   GroupByComplexity(Ops, &LI, DT);
    3420             : 
    3421             :   // If there are any constants, fold them together.
    3422             :   unsigned Idx = 0;
    3423       21633 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    3424             :     ++Idx;
    3425             :     assert(Idx < Ops.size());
    3426       21089 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    3427             :       // We found two constants, fold them together!
    3428       19008 :       ConstantInt *Fold = ConstantInt::get(
    3429       19008 :           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
    3430       19008 :       Ops[0] = getConstant(Fold);
    3431       19008 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    3432       19008 :       if (Ops.size() == 1) return Ops[0];
    3433           2 :       LHSC = cast<SCEVConstant>(Ops[0]);
    3434           2 :     }
    3435             : 
    3436             :     // If we are left with a constant minimum-int, strip it off.
    3437        2081 :     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
    3438          10 :       Ops.erase(Ops.begin());
    3439             :       --Idx;
    3440        2071 :     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
    3441             :       // If we have an smax with a constant maximum-int, it will always be
    3442             :       // maximum-int.
    3443             :       return Ops[0];
    3444             :     }
    3445             : 
    3446        2079 :     if (Ops.size() == 1) return Ops[0];
    3447             :   }
    3448             : 
    3449             :   // Find the first SMax
    3450       14146 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
    3451        1943 :     ++Idx;
    3452             : 
    3453             :   // Check to see if one of the operands is an SMax. If so, expand its operands
    3454             :   // onto our operand list, and recurse to simplify.
    3455        2615 :   if (Idx < Ops.size()) {
    3456             :     bool DeletedSMax = false;
    3457        1222 :     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
    3458          78 :       Ops.erase(Ops.begin()+Idx);
    3459         156 :       Ops.append(SMax->op_begin(), SMax->op_end());
    3460             :       DeletedSMax = true;
    3461          78 :     }
    3462             : 
    3463        1144 :     if (DeletedSMax)
    3464          78 :       return getSMaxExpr(Ops);
    3465             :   }
    3466             : 
    3467             :   // Okay, check to see if the same value occurs in the operand list twice.  If
    3468             :   // so, delete one.  Since we sorted the list, these values are required to
    3469             :   // be adjacent.
    3470        5492 :   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
    3471             :     //  X smax Y smax Y  -->  X smax Y
    3472             :     //  X smax Y         -->  X, if X is always greater than Y
    3473       11815 :     if (Ops[i] == Ops[i+1] ||
    3474        2950 :         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
    3475         134 :       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
    3476         134 :       --i; --e;
    3477        5642 :     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
    3478          48 :       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
    3479          48 :       --i; --e;
    3480             :     }
    3481             : 
    3482        2537 :   if (Ops.size() == 1) return Ops[0];
    3483             : 
    3484             :   assert(!Ops.empty() && "Reduced smax down to nothing!");
    3485             : 
    3486             :   // Okay, it looks like we really DO need an smax expr.  Check to see if we
    3487             :   // already have one, otherwise create a new one.
    3488             :   FoldingSetNodeID ID;
    3489        2355 :   ID.AddInteger(scSMaxExpr);
    3490        7483 :   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    3491       10256 :     ID.AddPointer(Ops[i]);
    3492        2355 :   void *IP = nullptr;
    3493        2355 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    3494        2116 :   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    3495             :   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    3496        4232 :   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
    3497             :                                              O, Ops.size());
    3498        2116 :   UniqueSCEVs.InsertNode(S, IP);
    3499        2116 :   addToLoopUseLists(S);
    3500        2116 :   return S;
    3501             : }
    3502             : 
    3503         748 : const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
    3504             :                                          const SCEV *RHS) {
    3505        1496 :   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
    3506        1496 :   return getUMaxExpr(Ops);
    3507             : }
    3508             : 
    3509             : const SCEV *
    3510        1780 : ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3511             :   assert(!Ops.empty() && "Cannot get empty umax!");
    3512        1780 :   if (Ops.size() == 1) return Ops[0];
    3513             : #ifndef NDEBUG
    3514             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    3515             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    3516             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    3517             :            "SCEVUMaxExpr operand types don't match!");
    3518             : #endif
    3519             : 
    3520             :   // Sort by complexity, this groups all similar expression types together.
    3521        1780 :   GroupByComplexity(Ops, &LI, DT);
    3522             : 
    3523             :   // If there are any constants, fold them together.
    3524             :   unsigned Idx = 0;
    3525        1780 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    3526             :     ++Idx;
    3527             :     assert(Idx < Ops.size());
    3528        1227 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    3529             :       // We found two constants, fold them together!
    3530         532 :       ConstantInt *Fold = ConstantInt::get(
    3531         532 :           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
    3532         532 :       Ops[0] = getConstant(Fold);
    3533         532 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    3534         532 :       if (Ops.size() == 1) return Ops[0];
    3535          25 :       LHSC = cast<SCEVConstant>(Ops[0]);
    3536          25 :     }
    3537             : 
    3538             :     // If we are left with a constant minimum-int, strip it off.
    3539         695 :     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
    3540         174 :       Ops.erase(Ops.begin());
    3541             :       --Idx;
    3542         521 :     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
    3543             :       // If we have an umax with a constant maximum-int, it will always be
    3544             :       // maximum-int.
    3545             :       return Ops[0];
    3546             :     }
    3547             : 
    3548         672 :     if (Ops.size() == 1) return Ops[0];
    3549             :   }
    3550             : 
    3551             :   // Find the first UMax
    3552        7443 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
    3553        1225 :     ++Idx;
    3554             : 
    3555             :   // Check to see if one of the operands is a UMax. If so, expand its operands
    3556             :   // onto our operand list, and recurse to simplify.
    3557        1076 :   if (Idx < Ops.size()) {
    3558             :     bool DeletedUMax = false;
    3559         421 :     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
    3560          30 :       Ops.erase(Ops.begin()+Idx);
    3561          60 :       Ops.append(UMax->op_begin(), UMax->op_end());
    3562             :       DeletedUMax = true;
    3563          30 :     }
    3564             : 
    3565         391 :     if (DeletedUMax)
    3566          30 :       return getUMaxExpr(Ops);
    3567             :   }
    3568             : 
    3569             :   // Okay, check to see if the same value occurs in the operand list twice.  If
    3570             :   // so, delete one.  Since we sorted the list, these values are required to
    3571             :   // be adjacent.
    3572        2146 :   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
    3573             :     //  X umax Y umax Y  -->  X umax Y
    3574             :     //  X umax Y         -->  X, if X is always greater than Y
    3575        3300 :     if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
    3576             :                                     ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
    3577          24 :       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
    3578          24 :       --i; --e;
    3579        2152 :     } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
    3580             :                                                Ops[i + 1])) {
    3581          41 :       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
    3582          41 :       --i; --e;
    3583             :     }
    3584             : 
    3585        1046 :   if (Ops.size() == 1) return Ops[0];
    3586             : 
    3587             :   assert(!Ops.empty() && "Reduced umax down to nothing!");
    3588             : 
    3589             :   // Okay, it looks like we really DO need a umax expr.  Check to see if we
    3590             :   // already have one, otherwise create a new one.
    3591             :   FoldingSetNodeID ID;
    3592         983 :   ID.AddInteger(scUMaxExpr);
    3593        3001 :   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    3594        4036 :     ID.AddPointer(Ops[i]);
    3595         983 :   void *IP = nullptr;
    3596         983 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    3597         684 :   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    3598             :   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    3599        1368 :   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
    3600             :                                              O, Ops.size());
    3601         684 :   UniqueSCEVs.InsertNode(S, IP);
    3602         684 :   addToLoopUseLists(S);
    3603         684 :   return S;
    3604             : }
    3605             : 
    3606       17072 : const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
    3607             :                                          const SCEV *RHS) {
    3608       34144 :   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
    3609       34144 :   return getSMinExpr(Ops);
    3610             : }
    3611             : 
    3612       17072 : const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3613             :   // ~smax(~x, ~y, ~z) == smin(x, y, z).
    3614             :   SmallVector<const SCEV *, 2> NotOps;
    3615       85360 :   for (auto *S : Ops)
    3616       34144 :     NotOps.push_back(getNotSCEV(S));
    3617       34144 :   return getNotSCEV(getSMaxExpr(NotOps));
    3618             : }
    3619             : 
    3620         301 : const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
    3621             :                                          const SCEV *RHS) {
    3622         602 :   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
    3623         602 :   return getUMinExpr(Ops);
    3624             : }
    3625             : 
    3626         993 : const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3627             :   assert(!Ops.empty() && "At least one operand must be!");
    3628             :   // Trivial case.
    3629         993 :   if (Ops.size() == 1)
    3630           0 :     return Ops[0];
    3631             : 
    3632             :   // ~umax(~x, ~y, ~z) == umin(x, y, z).
    3633             :   SmallVector<const SCEV *, 2> NotOps;
    3634        5015 :   for (auto *S : Ops)
    3635        2011 :     NotOps.push_back(getNotSCEV(S));
    3636         993 :   return getNotSCEV(getUMaxExpr(NotOps));
    3637             : }
    3638             : 
    3639      341930 : const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
    3640             :   // We can bypass creating a target-independent
    3641             :   // constant expression and then folding it back into a ConstantInt.
    3642             :   // This is just a compile-time optimization.
    3643      683860 :   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
    3644             : }
    3645             : 
    3646       30504 : const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
    3647             :                                              StructType *STy,
    3648             :                                              unsigned FieldNo) {
    3649             :   // We can bypass creating a target-independent
    3650             :   // constant expression and then folding it back into a ConstantInt.
    3651             :   // This is just a compile-time optimization.
    3652       30504 :   return getConstant(
    3653       61008 :       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
    3654             : }
    3655             : 
    3656      236044 : const SCEV *ScalarEvolution::getUnknown(Value *V) {
    3657             :   // Don't attempt to do anything other than create a SCEVUnknown object
    3658             :   // here.  createSCEV only calls getUnknown after checking for all other
    3659             :   // interesting possibilities, and any other code that calls getUnknown
    3660             :   // is doing so in order to hide a value from SCEV canonicalization.
    3661             : 
    3662             :   FoldingSetNodeID ID;
    3663      236044 :   ID.AddInteger(scUnknown);
    3664      236044 :   ID.AddPointer(V);
    3665      236044 :   void *IP = nullptr;
    3666      236044 :   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
    3667             :     assert(cast<SCEVUnknown>(S)->getValue() == V &&
    3668             :            "Stale SCEVUnknown in uniquing map!");
    3669             :     return S;
    3670             :   }
    3671      394036 :   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
    3672      197018 :                                             FirstUnknown);
    3673      197018 :   FirstUnknown = cast<SCEVUnknown>(S);
    3674      197018 :   UniqueSCEVs.InsertNode(S, IP);
    3675      197018 :   return S;
    3676             : }
    3677             : 
    3678             : //===----------------------------------------------------------------------===//
    3679             : //            Basic SCEV Analysis and PHI Idiom Recognition Code
    3680             : //
    3681             : 
    3682             : /// Test if values of the given type are analyzable within the SCEV
    3683             : /// framework. This primarily includes integer types, and it can optionally
    3684             : /// include pointer types if the ScalarEvolution class has access to
    3685             : /// target-specific information.
    3686     1351107 : bool ScalarEvolution::isSCEVable(Type *Ty) const {
    3687             :   // Integers and pointers are always SCEVable.
    3688     1351107 :   return Ty->isIntegerTy() || Ty->isPointerTy();
    3689             : }
    3690             : 
    3691             : /// Return the size in bits of the specified type, for which isSCEVable must
    3692             : /// return true.
    3693     3212648 : uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
    3694             :   assert(isSCEVable(Ty) && "Type is not SCEVable!");
    3695     3212648 :   if (Ty->isPointerTy())
    3696      661778 :     return getDataLayout().getIndexTypeSizeInBits(Ty);
    3697     5763518 :   return getDataLayout().getTypeSizeInBits(Ty);
    3698             : }
    3699             : 
    3700             : /// Return a type with the same bitwidth as the given type and which represents
    3701             : /// how SCEV will treat the given type, for which isSCEVable must return
    3702             : /// true. For pointer types, this is the pointer-sized integer type.
    3703     2378929 : Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
    3704             :   assert(isSCEVable(Ty) && "Type is not SCEVable!");
    3705             : 
    3706     2378929 :   if (Ty->isIntegerTy())
    3707             :     return Ty;
    3708             : 
    3709             :   // The only other support type is pointer.
    3710             :   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
    3711     1278240 :   return getDataLayout().getIntPtrType(Ty);
    3712             : }
    3713             : 
    3714         803 : Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
    3715         803 :   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
    3716             : }
    3717             : 
    3718      479621 : const SCEV *ScalarEvolution::getCouldNotCompute() {
    3719      479621 :   return CouldNotCompute.get();
    3720             : }
    3721             : 
    3722     1650089 : bool ScalarEvolution::checkValidity(const SCEV *S) const {
    3723             :   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
    3724             :     auto *SU = dyn_cast<SCEVUnknown>(S);
    3725     2155106 :     return SU && SU->getValue() == nullptr;
    3726             :   });
    3727             : 
    3728     1650089 :   return !ContainsNulls;
    3729             : }
    3730             : 
    3731       60447 : bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
    3732       60447 :   HasRecMapType::iterator I = HasRecMap.find(S);
    3733       60447 :   if (I != HasRecMap.end())
    3734       12934 :     return I->second;
    3735             : 
    3736             :   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
    3737       47513 :   HasRecMap.insert({S, FoundAddRec});
    3738       47513 :   return FoundAddRec;
    3739             : }
    3740             : 
    3741             : /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
    3742             : /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
    3743             : /// offset I, then return {S', I}, else return {\p S, nullptr}.
    3744      625019 : static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
    3745             :   const auto *Add = dyn_cast<SCEVAddExpr>(S);
    3746             :   if (!Add)
    3747      493812 :     return {S, nullptr};
    3748             : 
    3749      131207 :   if (Add->getNumOperands() != 2)
    3750        6270 :     return {S, nullptr};
    3751             : 
    3752      124937 :   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
    3753             :   if (!ConstOp)
    3754       31972 :     return {S, nullptr};
    3755             : 
    3756       92965 :   return {Add->getOperand(1), ConstOp->getValue()};
    3757             : }
    3758             : 
    3759             : /// Return the ValueOffsetPair set for \p S. \p S can be represented
    3760             : /// by the value and offset from any ValueOffsetPair in the set.
    3761             : SetVector<ScalarEvolution::ValueOffsetPair> *
    3762      183052 : ScalarEvolution::getSCEVValues(const SCEV *S) {
    3763      183052 :   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
    3764      183052 :   if (SI == ExprValueMap.end())
    3765             :     return nullptr;
    3766             : #ifndef NDEBUG
    3767             :   if (VerifySCEVMap) {
    3768             :     // Check there is no dangling Value in the set returned.
    3769             :     for (const auto &VE : SI->second)
    3770             :       assert(ValueExprMap.count(VE.first));
    3771             :   }
    3772             : #endif
    3773       75411 :   return &SI->second;
    3774             : }
    3775             : 
    3776             : /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
    3777             : /// cannot be used separately. eraseValueFromMap should be used to remove
    3778             : /// V from ValueExprMap and ExprValueMap at the same time.
    3779      103331 : void ScalarEvolution::eraseValueFromMap(Value *V) {
    3780      103331 :   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
    3781      103331 :   if (I != ValueExprMap.end()) {
    3782       92981 :     const SCEV *S = I->second;
    3783             :     // Remove {V, 0} from the set of ExprValueMap[S]
    3784       92981 :     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
    3785       51693 :       SV->remove({V, nullptr});
    3786             : 
    3787             :     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
    3788             :     const SCEV *Stripped;
    3789             :     ConstantInt *Offset;
    3790      185962 :     std::tie(Stripped, Offset) = splitAddExpr(S);
    3791       92981 :     if (Offset != nullptr) {
    3792       10686 :       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
    3793         767 :         SV->remove({V, Offset});
    3794             :     }
    3795      185962 :     ValueExprMap.erase(V);
    3796             :   }
    3797      103331 : }
    3798             : 
    3799             : /// Check whether value has nuw/nsw/exact set but SCEV does not.
    3800             : /// TODO: In reality it is better to check the poison recursevely
    3801             : /// but this is better than nothing.
    3802      550037 : static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
    3803             :   if (auto *I = dyn_cast<Instruction>(V)) {
    3804             :     if (isa<OverflowingBinaryOperator>(I)) {
    3805             :       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
    3806       91791 :         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
    3807             :           return true;
    3808       58963 :         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
    3809             :           return true;
    3810             :       }
    3811        4917 :     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
    3812             :       return true;
    3813             :   }
    3814             :   return false;
    3815             : }
    3816             : 
    3817             : /// Return an existing SCEV if it exists, otherwise analyze the expression and
    3818             : /// create a new one.
    3819     2245727 : const SCEV *ScalarEvolution::getSCEV(Value *V) {
    3820             :   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
    3821             : 
    3822     2245727 :   const SCEV *S = getExistingSCEV(V);
    3823     2245727 :   if (S == nullptr) {
    3824      601070 :     S = createSCEV(V);
    3825             :     // During PHI resolution, it is possible to create two SCEVs for the same
    3826             :     // V, so it is needed to double check whether V->S is inserted into
    3827             :     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
    3828             :     std::pair<ValueExprMapType::iterator, bool> Pair =
    3829     1803210 :         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
    3830      601070 :     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
    3831     1064076 :       ExprValueMap[S].insert({V, nullptr});
    3832             : 
    3833             :       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
    3834             :       // ExprValueMap.
    3835      532038 :       const SCEV *Stripped = S;
    3836             :       ConstantInt *Offset = nullptr;
    3837     1064076 :       std::tie(Stripped, Offset) = splitAddExpr(S);
    3838             :       // If stripped is SCEVUnknown, don't bother to save
    3839             :       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
    3840             :       // increase the complexity of the expansion code.
    3841             :       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
    3842             :       // because it may generate add/sub instead of GEP in SCEV expansion.
    3843      614317 :       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
    3844             :           !isa<GetElementPtrInst>(V))
    3845        2495 :         ExprValueMap[Stripped].insert({V, Offset});
    3846             :     }
    3847             :   }
    3848     2245727 :   return S;
    3849             : }
    3850             : 
    3851     2317771 : const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
    3852             :   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
    3853             : 
    3854     2317771 :   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
    3855     2317771 :   if (I != ValueExprMap.end()) {
    3856     1650089 :     const SCEV *S = I->second;
    3857     1650089 :     if (checkValidity(S))
    3858             :       return S;
    3859           0 :     eraseValueFromMap(V);
    3860           0 :     forgetMemoizedResults(S);
    3861             :   }
    3862             :   return nullptr;
    3863             : }
    3864             : 
    3865             : /// Return a SCEV corresponding to -V = -1*V
    3866      699131 : const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
    3867             :                                              SCEV::NoWrapFlags Flags) {
    3868             :   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
    3869      383066 :     return getConstant(
    3870      766132 :                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
    3871             : 
    3872      316065 :   Type *Ty = V->getType();
    3873      316065 :   Ty = getEffectiveSCEVType(Ty);
    3874      316065 :   return getMulExpr(
    3875      316065 :       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
    3876             : }
    3877             : 
    3878             : /// Return a SCEV corresponding to ~V = -1-V
    3879      144283 : const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
    3880             :   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
    3881       79886 :     return getConstant(
    3882      159772 :                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
    3883             : 
    3884       64397 :   Type *Ty = V->getType();
    3885       64397 :   Ty = getEffectiveSCEVType(Ty);
    3886             :   const SCEV *AllOnes =
    3887       64397 :                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
    3888       64397 :   return getMinusSCEV(AllOnes, V);
    3889             : }
    3890             : 
    3891      827027 : const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
    3892             :                                           SCEV::NoWrapFlags Flags,
    3893             :                                           unsigned Depth) {
    3894             :   // Fast path: X - X --> 0.
    3895      827027 :   if (LHS == RHS)
    3896      281702 :     return getZero(LHS->getType());
    3897             : 
    3898             :   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
    3899             :   // makes it so that we cannot make much use of NUW.
    3900             :   auto AddFlags = SCEV::FlagAnyWrap;
    3901             :   const bool RHSIsNotMinSigned =
    3902     1372352 :       !getSignedRangeMin(RHS).isMinSignedValue();
    3903      686176 :   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
    3904             :     // Let M be the minimum representable signed value. Then (-1)*RHS
    3905             :     // signed-wraps if and only if RHS is M. That can happen even for
    3906             :     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
    3907             :     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
    3908             :     // (-1)*RHS, we need to prove that RHS != M.
    3909             :     //
    3910             :     // If LHS is non-negative and we know that LHS - RHS does not
    3911             :     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
    3912             :     // either by proving that RHS > M or that LHS >= 0.
    3913         311 :     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
    3914             :       AddFlags = SCEV::FlagNSW;
    3915             :     }
    3916             :   }
    3917             : 
    3918             :   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
    3919             :   // RHS is NSW and LHS >= 0.
    3920             :   //
    3921             :   // The difficulty here is that the NSW flag may have been proven
    3922             :   // relative to a loop that is to be found in a recurrence in LHS and
    3923             :   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
    3924             :   // larger scope than intended.
    3925      686176 :   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
    3926             : 
    3927      686176 :   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
    3928             : }
    3929             : 
    3930             : const SCEV *
    3931       82781 : ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
    3932       82781 :   Type *SrcTy = V->getType();
    3933             :   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
    3934             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
    3935             :          "Cannot truncate or zero extend with non-integer arguments!");
    3936       82781 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3937             :     return V;  // No conversion
    3938       16625 :   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
    3939        8094 :     return getTruncateExpr(V, Ty);
    3940        8531 :   return getZeroExtendExpr(V, Ty);
    3941             : }
    3942             : 
    3943             : const SCEV *
    3944      303655 : ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
    3945             :                                          Type *Ty) {
    3946      303655 :   Type *SrcTy = V->getType();
    3947             :   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
    3948             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
    3949             :          "Cannot truncate or zero extend with non-integer arguments!");
    3950      303655 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3951             :     return V;  // No conversion
    3952       22967 :   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
    3953         681 :     return getTruncateExpr(V, Ty);
    3954       22286 :   return getSignExtendExpr(V, Ty);
    3955             : }
    3956             : 
    3957             : const SCEV *
    3958      165400 : ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
    3959      165400 :   Type *SrcTy = V->getType();
    3960             :   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
    3961             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
    3962             :          "Cannot noop or zero extend with non-integer arguments!");
    3963             :   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
    3964             :          "getNoopOrZeroExtend cannot truncate!");
    3965      165400 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3966             :     return V;  // No conversion
    3967       21446 :   return getZeroExtendExpr(V, Ty);
    3968             : }
    3969             : 
    3970             : const SCEV *
    3971        3206 : ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
    3972        3206 :   Type *SrcTy = V->getType();
    3973             :   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
    3974             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
    3975             :          "Cannot noop or sign extend with non-integer arguments!");
    3976             :   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
    3977             :          "getNoopOrSignExtend cannot truncate!");
    3978        3206 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3979             :     return V;  // No conversion
    3980         288 :   return getSignExtendExpr(V, Ty);
    3981             : }
    3982             : 
    3983             : const SCEV *
    3984          81 : ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
    3985          81 :   Type *SrcTy = V->getType();
    3986             :   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
    3987             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
    3988             :          "Cannot noop or any extend with non-integer arguments!");
    3989             :   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
    3990             :          "getNoopOrAnyExtend cannot truncate!");
    3991          81 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3992             :     return V;  // No conversion
    3993           0 :   return getAnyExtendExpr(V, Ty);
    3994             : }
    3995             : 
    3996             : const SCEV *
    3997         275 : ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
    3998         275 :   Type *SrcTy = V->getType();
    3999             :   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
    4000             :          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
    4001             :          "Cannot truncate or noop with non-integer arguments!");
    4002             :   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
    4003             :          "getTruncateOrNoop cannot extend!");
    4004         275 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    4005             :     return V;  // No conversion
    4006          24 :   return getTruncateExpr(V, Ty);
    4007             : }
    4008             : 
    4009           0 : const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
    4010             :                                                         const SCEV *RHS) {
    4011             :   const SCEV *PromotedLHS = LHS;
    4012             :   const SCEV *PromotedRHS = RHS;
    4013             : 
    4014           0 :   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
    4015           0 :     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
    4016             :   else
    4017           0 :     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
    4018             : 
    4019           0 :   return getUMaxExpr(PromotedLHS, PromotedRHS);
    4020             : }
    4021             : 
    4022         396 : const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
    4023             :                                                         const SCEV *RHS) {
    4024         792 :   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
    4025         792 :   return getUMinFromMismatchedTypes(Ops);
    4026             : }
    4027             : 
    4028       30293 : const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
    4029             :     SmallVectorImpl<const SCEV *> &Ops) {
    4030             :   assert(!Ops.empty() && "At least one operand must be!");
    4031             :   // Trivial case.
    4032       30293 :   if (Ops.size() == 1)
    4033       29601 :     return Ops[0];
    4034             : 
    4035             :   // Find the max type first.
    4036             :   Type *MaxType = nullptr;
    4037        3510 :   for (auto *S : Ops)
    4038        1409 :     if (MaxType)
    4039         717 :       MaxType = getWiderType(MaxType, S->getType());
    4040             :     else
    4041         692 :       MaxType = S->getType();
    4042             : 
    4043             :   // Extend all ops to max type.
    4044             :   SmallVector<const SCEV *, 2> PromotedOps;
    4045        3510 :   for (auto *S : Ops)
    4046        1409 :     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
    4047             : 
    4048             :   // Generate umin.
    4049         692 :   return getUMinExpr(PromotedOps);
    4050             : }
    4051             : 
    4052       54977 : const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
    4053             :   // A pointer operand may evaluate to a nonpointer expression, such as null.
    4054      215270 :   if (!V->getType()->isPointerTy())
    4055             :     return V;
    4056             : 
    4057             :   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
    4058           0 :     return getPointerBase(Cast->getOperand());
    4059             :   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
    4060             :     const SCEV *PtrOp = nullptr;
    4061      266070 :     for (const SCEV *NAryOp : NAry->operands()) {
    4062      213412 :       if (NAryOp->getType()->isPointerTy()) {
    4063             :         // Cannot find the base of an expression with multiple pointer operands.
    4064       52658 :         if (PtrOp)
    4065             :           return V;
    4066             :         PtrOp = NAryOp;
    4067             :       }
    4068             :     }
    4069       52658 :     if (!PtrOp)
    4070             :       return V;
    4071             :     return getPointerBase(PtrOp);
    4072             :   }
    4073             :   return V;
    4074             : }
    4075             : 
    4076             : /// Push users of the given Instruction onto the given Worklist.
    4077             : static void
    4078      376373 : PushDefUseChildren(Instruction *I,
    4079             :                    SmallVectorImpl<Instruction *> &Worklist) {
    4080             :   // Push the def-use children onto the Worklist stack.
    4081      794839 :   for (User *U : I->users())
    4082      418466 :     Worklist.push_back(cast<Instruction>(U));
    4083      376373 : }
    4084             : 
    4085        7255 : void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
    4086             :   SmallVector<Instruction *, 16> Worklist;
    4087        7255 :   PushDefUseChildren(PN, Worklist);
    4088             : 
    4089             :   SmallPtrSet<Instruction *, 8> Visited;
    4090        7255 :   Visited.insert(PN);
    4091      167781 :   while (!Worklist.empty()) {
    4092             :     Instruction *I = Worklist.pop_back_val();
    4093      160526 :     if (!Visited.insert(I).second)
    4094       47365 :       continue;
    4095             : 
    4096      138253 :     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
    4097      138253 :     if (It != ValueExprMap.end()) {
    4098       12813 :       const SCEV *Old = It->second;
    4099             : 
    4100             :       // Short-circuit the def-use traversal if the symbolic name
    4101             :       // ceases to appear in expressions.
    4102       12813 :       if (Old != SymName && !hasOperand(Old, SymName))
    4103             :         continue;
    4104             : 
    4105             :       // SCEVUnknown for a PHI either means that it has an unrecognized
    4106             :       // structure, it's a PHI that's in the progress of being computed
    4107             :       // by createNodeForPHI, or it's a single-value PHI. In the first case,
    4108             :       // additional loop trip count information isn't going to change anything.
    4109             :       // In the second case, createNodeForPHI will perform the necessary
    4110             :       // updates on its own when it gets to that point. In the third, we do
    4111             :       // want to forget the SCEVUnknown.
    4112          18 :       if (!isa<PHINode>(I) ||
    4113        9999 :           !isa<SCEVUnknown>(Old) ||
    4114           5 :           (I != PN && Old == SymName)) {
    4115        9994 :         eraseValueFromMap(It->first);
    4116        9994 :         forgetMemoizedResults(Old);
    4117             :       }
    4118             :     }
    4119             : 
    4120      135434 :     PushDefUseChildren(I, Worklist);
    4121             :   }
    4122        7255 : }
    4123             : 
    4124             : namespace {
    4125             : 
    4126             : /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
    4127             : /// expression in case its Loop is L. If it is not L then
    4128             : /// if IgnoreOtherLoops is true then use AddRec itself
    4129             : /// otherwise rewrite cannot be done.
    4130             : /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
    4131             : class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
    4132             : public:
    4133       30781 :   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
    4134             :                              bool IgnoreOtherLoops = true) {
    4135             :     SCEVInitRewriter Rewriter(L, SE);
    4136       30781 :     const SCEV *Result = Rewriter.visit(S);
    4137       30781 :     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
    4138        1045 :       return SE.getCouldNotCompute();
    4139       29986 :     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
    4140       29736 :                ? SE.getCouldNotCompute()
    4141             :                : Result;
    4142             :   }
    4143             : 
    4144             :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4145        4523 :     if (!SE.isLoopInvariant(Expr, L))
    4146        1065 :       SeenLoopVariantSCEVUnknown = true;
    4147             :     return Expr;
    4148             :   }
    4149             : 
    4150             :   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
    4151             :     // Only re-write AddRecExprs for this loop.
    4152       13574 :     if (Expr->getLoop() == L)
    4153       13320 :       return Expr->getStart();
    4154         254 :     SeenOtherLoops = true;
    4155             :     return Expr;
    4156             :   }
    4157             : 
    4158             :   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
    4159             : 
    4160             :   bool hasSeenOtherLoops() { return SeenOtherLoops; }
    4161             : 
    4162             : private:
    4163             :   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
    4164       61562 :       : SCEVRewriteVisitor(SE), L(L) {}
    4165             : 
    4166             :   const Loop *L;
    4167             :   bool SeenLoopVariantSCEVUnknown = false;
    4168             :   bool SeenOtherLoops = false;
    4169             : };
    4170             : 
    4171             : /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
    4172             : /// increment expression in case its Loop is L. If it is not L then
    4173             : /// use AddRec itself.
    4174             : /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
    4175             : class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
    4176             : public:
    4177       24635 :   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
    4178             :     SCEVPostIncRewriter Rewriter(L, SE);
    4179       24635 :     const SCEV *Result = Rewriter.visit(S);
    4180       24635 :     return Rewriter.hasSeenLoopVariantSCEVUnknown()
    4181       24635 :         ? SE.getCouldNotCompute()
    4182       24635 :         : Result;
    4183             :   }
    4184             : 
    4185             :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4186        3315 :     if (!SE.isLoopInvariant(Expr, L))
    4187           0 :       SeenLoopVariantSCEVUnknown = true;
    4188             :     return Expr;
    4189             :   }
    4190             : 
    4191       13028 :   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
    4192             :     // Only re-write AddRecExprs for this loop.
    4193       13028 :     if (Expr->getLoop() == L)
    4194       12778 :       return Expr->getPostIncExpr(SE);
    4195         250 :     SeenOtherLoops = true;
    4196         250 :     return Expr;
    4197             :   }
    4198             : 
    4199             :   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
    4200             : 
    4201             :   bool hasSeenOtherLoops() { return SeenOtherLoops; }
    4202             : 
    4203             : private:
    4204             :   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
    4205       49270 :       : SCEVRewriteVisitor(SE), L(L) {}
    4206             : 
    4207             :   const Loop *L;
    4208             :   bool SeenLoopVariantSCEVUnknown = false;
    4209             :   bool SeenOtherLoops = false;
    4210             : };
    4211             : 
    4212             : /// This class evaluates the compare condition by matching it against the
    4213             : /// condition of loop latch. If there is a match we assume a true value
    4214             : /// for the condition while building SCEV nodes.
    4215             : class SCEVBackedgeConditionFolder
    4216             :     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
    4217             : public:
    4218        8145 :   static const SCEV *rewrite(const SCEV *S, const Loop *L,
    4219             :                              ScalarEvolution &SE) {
    4220             :     bool IsPosBECond = false;
    4221             :     Value *BECond = nullptr;
    4222        8145 :     if (BasicBlock *Latch = L->getLoopLatch()) {
    4223             :       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
    4224        8139 :       if (BI && BI->isConditional()) {
    4225             :         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
    4226             :                "Both outgoing branches should not target same header!");
    4227             :         BECond = BI->getCondition();
    4228        7419 :         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
    4229             :       } else {
    4230             :         return S;
    4231             :       }
    4232             :     }
    4233             :     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
    4234        7423 :     return Rewriter.visit(S);
    4235             :   }
    4236             : 
    4237        1794 :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4238        1794 :     const SCEV *Result = Expr;
    4239        1794 :     bool InvariantF = SE.isLoopInvariant(Expr, L);
    4240             : 
    4241        1794 :     if (!InvariantF) {
    4242             :       Instruction *I = cast<Instruction>(Expr->getValue());
    4243        1507 :       switch (I->getOpcode()) {
    4244             :       case Instruction::Select: {
    4245             :         SelectInst *SI = cast<SelectInst>(I);
    4246             :         Optional<const SCEV *> Res =
    4247          96 :             compareWithBackedgeCondition(SI->getCondition());
    4248          96 :         if (Res.hasValue()) {
    4249           5 :           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
    4250          10 :           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
    4251             :         }
    4252             :         break;
    4253             :       }
    4254        1411 :       default: {
    4255        1411 :         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
    4256        1411 :         if (Res.hasValue())
    4257           4 :           Result = Res.getValue();
    4258             :         break;
    4259             :       }
    4260             :       }
    4261             :     }
    4262        1794 :     return Result;
    4263             :   }
    4264             : 
    4265             : private:
    4266             :   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
    4267             :                                        bool IsPosBECond, ScalarEvolution &SE)
    4268        7423 :       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
    4269        7423 :         IsPositiveBECond(IsPosBECond) {}
    4270             : 
    4271             :   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
    4272             : 
    4273             :   const Loop *L;
    4274             :   /// Loop back condition.
    4275             :   Value *BackedgeCond = nullptr;
    4276             :   /// Set to true if loop back is on positive branch condition.
    4277             :   bool IsPositiveBECond;
    4278             : };
    4279             : 
    4280             : Optional<const SCEV *>
    4281        1507 : SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
    4282             : 
    4283             :   // If value matches the backedge condition for loop latch,
    4284             :   // then return a constant evolution node based on loopback
    4285             :   // branch taken.
    4286        1507 :   if (BackedgeCond == IC)
    4287          17 :     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
    4288           2 :                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
    4289             :   return None;
    4290             : }
    4291             : 
    4292             : class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
    4293             : public:
    4294        5101 :   static const SCEV *rewrite(const SCEV *S, const Loop *L,
    4295             :                              ScalarEvolution &SE) {
    4296             :     SCEVShiftRewriter Rewriter(L, SE);
    4297        5101 :     const SCEV *Result = Rewriter.visit(S);
    4298       10202 :     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
    4299             :   }
    4300             : 
    4301             :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4302             :     // Only allow AddRecExprs for this loop.
    4303        4499 :     if (!SE.isLoopInvariant(Expr, L))
    4304        4377 :       Valid = false;
    4305             :     return Expr;
    4306             :   }
    4307             : 
    4308         648 :   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
    4309        1206 :     if (Expr->getLoop() == L && Expr->isAffine())
    4310         558 :       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
    4311          90 :     Valid = false;
    4312          90 :     return Expr;
    4313             :   }
    4314             : 
    4315             :   bool isValid() { return Valid; }
    4316             : 
    4317             : private:
    4318             :   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
    4319       10202 :       : SCEVRewriteVisitor(SE), L(L) {}
    4320             : 
    4321             :   const Loop *L;
    4322             :   bool Valid = true;
    4323             : };
    4324             : 
    4325             : } // end anonymous namespace
    4326             : 
    4327             : SCEV::NoWrapFlags
    4328       32625 : ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
    4329       32625 :   if (!AR->isAffine())
    4330             :     return SCEV::FlagAnyWrap;
    4331             : 
    4332             :   using OBO = OverflowingBinaryOperator;
    4333             : 
    4334             :   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
    4335             : 
    4336       32625 :   if (!AR->hasNoSignedWrap()) {
    4337       21444 :     ConstantRange AddRecRange = getSignedRange(AR);
    4338       42888 :     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
    4339             : 
    4340             :     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    4341       42888 :         Instruction::Add, IncRange, OBO::NoSignedWrap);
    4342       21444 :     if (NSWRegion.contains(AddRecRange))
    4343             :       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
    4344             :   }
    4345             : 
    4346       32625 :   if (!AR->hasNoUnsignedWrap()) {
    4347       31296 :     ConstantRange AddRecRange = getUnsignedRange(AR);
    4348       62592 :     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
    4349             : 
    4350             :     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    4351       62592 :         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
    4352       31296 :     if (NUWRegion.contains(AddRecRange))
    4353             :       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
    4354             :   }
    4355             : 
    4356             :   return Result;
    4357             : }
    4358             : 
    4359             : namespace {
    4360             : 
    4361             : /// Represents an abstract binary operation.  This may exist as a
    4362             : /// normal instruction or constant expression, or may have been
    4363             : /// derived from an expression tree.
    4364             : struct BinaryOp {
    4365             :   unsigned Opcode;
    4366             :   Value *LHS;
    4367             :   Value *RHS;
    4368             :   bool IsNSW = false;
    4369             :   bool IsNUW = false;
    4370             : 
    4371             :   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
    4372             :   /// constant expression.
    4373             :   Operator *Op = nullptr;
    4374             : 
    4375      130686 :   explicit BinaryOp(Operator *Op)
    4376      261372 :       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
    4377      392058 :         Op(Op) {
    4378             :     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
    4379      123449 :       IsNSW = OBO->hasNoSignedWrap();
    4380      123449 :       IsNUW = OBO->hasNoUnsignedWrap();
    4381             :     }
    4382      130686 :   }
    4383             : 
    4384             :   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
    4385             :                     bool IsNUW = false)
    4386             :       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
    4387             : };
    4388             : 
    4389             : } // end anonymous namespace
    4390             : 
    4391             : /// Try to map \p V into a BinaryOp, and return \c None on failure.
    4392      528697 : static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
    4393             :   auto *Op = dyn_cast<Operator>(V);
    4394             :   if (!Op)
    4395             :     return None;
    4396             : 
    4397             :   // Implementation detail: all the cleverness here should happen without
    4398             :   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
    4399             :   // SCEV expressions when possible, and we should not break that.
    4400             : 
    4401      525176 :   switch (Op->getOpcode()) {
    4402      129950 :   case Instruction::Add:
    4403             :   case Instruction::Sub:
    4404             :   case Instruction::Mul:
    4405             :   case Instruction::UDiv:
    4406             :   case Instruction::URem:
    4407             :   case Instruction::And:
    4408             :   case Instruction::Or:
    4409             :   case Instruction::AShr:
    4410             :   case Instruction::Shl:
    4411      259900 :     return BinaryOp(Op);
    4412             : 
    4413         439 :   case Instruction::Xor:
    4414         439 :     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
    4415             :       // If the RHS of the xor is a signmask, then this is just an add.
    4416             :       // Instcombine turns add of signmask into xor as a strength reduction step.
    4417         159 :       if (RHSC->getValue().isSignMask())
    4418             :         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
    4419         824 :     return BinaryOp(Op);
    4420             : 
    4421        4408 :   case Instruction::LShr:
    4422             :     // Turn logical shift right of a constant into a unsigned divide.
    4423        4408 :     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
    4424        4086 :       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
    4425             : 
    4426             :       // If the shift count is not less than the bitwidth, the result of
    4427             :       // the shift is undefined. Don't try to analyze it, because the
    4428             :       // resolution chosen here may differ from the resolution chosen in
    4429             :       // other parts of the compiler.
    4430        4086 :       if (SA->getValue().ult(BitWidth)) {
    4431             :         Constant *X =
    4432        4084 :             ConstantInt::get(SA->getContext(),
    4433       12252 :                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
    4434             :         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
    4435             :       }
    4436             :     }
    4437         648 :     return BinaryOp(Op);
    4438             : 
    4439             :   case Instruction::ExtractValue: {
    4440             :     auto *EVI = cast<ExtractValueInst>(Op);
    4441         892 :     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
    4442             :       break;
    4443             : 
    4444             :     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
    4445             :     if (!CI)
    4446             :       break;
    4447             : 
    4448             :     if (auto *F = CI->getCalledFunction())
    4449         177 :       switch (F->getIntrinsicID()) {
    4450             :       case Intrinsic::sadd_with_overflow:
    4451             :       case Intrinsic::uadd_with_overflow:
    4452          84 :         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
    4453          30 :           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
    4454             :                           CI->getArgOperand(1));
    4455             : 
    4456             :         // Now that we know that all uses of the arithmetic-result component of
    4457             :         // CI are guarded by the overflow check, we can go ahead and pretend
    4458             :         // that the arithmetic is non-overflowing.
    4459          54 :         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
    4460          47 :           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
    4461             :                           CI->getArgOperand(1), /* IsNSW = */ true,
    4462             :                           /* IsNUW = */ false);
    4463             :         else
    4464           7 :           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
    4465             :                           CI->getArgOperand(1), /* IsNSW = */ false,
    4466             :                           /* IsNUW*/ true);
    4467             :       case Intrinsic::ssub_with_overflow:
    4468             :       case Intrinsic::usub_with_overflow:
    4469          60 :         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
    4470          22 :           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
    4471             :                           CI->getArgOperand(1));
    4472             : 
    4473             :         // The same reasoning as sadd/uadd above.
    4474          38 :         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
    4475          20 :           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
    4476             :                           CI->getArgOperand(1), /* IsNSW = */ true,
    4477             :                           /* IsNUW = */ false);
    4478             :         else
    4479          18 :           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
    4480             :                           CI->getArgOperand(1), /* IsNSW = */ false,
    4481             :                           /* IsNUW = */ true);
    4482           7 :       case Intrinsic::smul_with_overflow:
    4483             :       case Intrinsic::umul_with_overflow:
    4484           7 :         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
    4485             :                         CI->getArgOperand(1));
    4486             :       default:
    4487             :         break;
    4488             :       }
    4489             :     break;
    4490             :   }
    4491             : 
    4492             :   default:
    4493             :     break;
    4494             :   }
    4495             : 
    4496             :   return None;
    4497             : }
    4498             : 
    4499             : /// Helper function to createAddRecFromPHIWithCasts. We have a phi
    4500             : /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
    4501             : /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
    4502             : /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
    4503             : /// follows one of the following patterns:
    4504             : /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
    4505             : /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
    4506             : /// If the SCEV expression of \p Op conforms with one of the expected patterns
    4507             : /// we return the type of the truncation operation, and indicate whether the
    4508             : /// truncated type should be treated as signed/unsigned by setting
    4509             : /// \p Signed to true/false, respectively.
    4510          97 : static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
    4511             :                                bool &Signed, ScalarEvolution &SE) {
    4512             :   // The case where Op == SymbolicPHI (that is, with no type conversions on
    4513             :   // the way) is handled by the regular add recurrence creating logic and
    4514             :   // would have already been triggered in createAddRecForPHI. Reaching it here
    4515             :   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
    4516             :   // because one of the other operands of the SCEVAddExpr updating this PHI is
    4517             :   // not invariant).
    4518             :   //
    4519             :   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
    4520             :   // this case predicates that allow us to prove that Op == SymbolicPHI will
    4521             :   // be added.
    4522          97 :   if (Op == SymbolicPHI)
    4523             :     return nullptr;
    4524             : 
    4525          83 :   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
    4526          83 :   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
    4527          83 :   if (SourceBits != NewBits)
    4528             :     return nullptr;
    4529             : 
    4530             :   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
    4531             :   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
    4532          83 :   if (!SExt && !ZExt)
    4533             :     return nullptr;
    4534             :   const SCEVTruncateExpr *Trunc =
    4535          23 :       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
    4536          12 :            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
    4537          19 :   if (!Trunc)
    4538             :     return nullptr;
    4539          19 :   const SCEV *X = Trunc->getOperand();
    4540          19 :   if (X != SymbolicPHI)
    4541             :     return nullptr;
    4542          19 :   Signed = SExt != nullptr;
    4543          19 :   return Trunc->getType();
    4544             : }
    4545             : 
    4546        1329 : static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
    4547        2658 :   if (!PN->getType()->isIntegerTy())
    4548             :     return nullptr;
    4549         933 :   const Loop *L = LI.getLoopFor(PN->getParent());
    4550        1696 :   if (!L || L->getHeader() != PN->getParent())
    4551             :     return nullptr;
    4552             :   return L;
    4553             : }
    4554             : 
    4555             : // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
    4556             : // computation that updates the phi follows the following pattern:
    4557             : //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
    4558             : // which correspond to a phi->trunc->sext/zext->add->phi update chain.
    4559             : // If so, try to see if it can be rewritten as an AddRecExpr under some
    4560             : // Predicates. If successful, return them as a pair. Also cache the results
    4561             : // of the analysis.
    4562             : //
    4563             : // Example usage scenario:
    4564             : //    Say the Rewriter is called for the following SCEV:
    4565             : //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
    4566             : //    where:
    4567             : //         %X = phi i64 (%Start, %BEValue)
    4568             : //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
    4569             : //    and call this function with %SymbolicPHI = %X.
    4570             : //
    4571             : //    The analysis will find that the value coming around the backedge has
    4572             : //    the following SCEV:
    4573             : //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
    4574             : //    Upon concluding that this matches the desired pattern, the function
    4575             : //    will return the pair {NewAddRec, SmallPredsVec} where:
    4576             : //         NewAddRec = {%Start,+,%Step}
    4577             : //         SmallPredsVec = {P1, P2, P3} as follows:
    4578             : //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
    4579             : //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
    4580             : //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
    4581             : //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
    4582             : //    under the predicates {P1,P2,P3}.
    4583             : //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
    4584             : //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
    4585             : //
    4586             : // TODO's:
    4587             : //
    4588             : // 1) Extend the Induction descriptor to also support inductions that involve
    4589             : //    casts: When needed (namely, when we are called in the context of the
    4590             : //    vectorizer induction analysis), a Set of cast instructions will be
    4591             : //    populated by this method, and provided back to isInductionPHI. This is
    4592             : //    needed to allow the vectorizer to properly record them to be ignored by
    4593             : //    the cost model and to avoid vectorizing them (otherwise these casts,
    4594             : //    which are redundant under the runtime overflow checks, will be
    4595             : //    vectorized, which can be costly).
    4596             : //
    4597             : // 2) Support additional induction/PHISCEV patterns: We also want to support
    4598             : //    inductions where the sext-trunc / zext-trunc operations (partly) occur
    4599             : //    after the induction update operation (the induction increment):
    4600             : //
    4601             : //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
    4602             : //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
    4603             : //
    4604             : //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
    4605             : //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
    4606             : //
    4607             : // 3) Outline common code with createAddRecFromPHI to avoid duplication.
    4608             : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
    4609         285 : ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
    4610             :   SmallVector<const SCEVPredicate *, 3> Predicates;
    4611             : 
    4612             :   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
    4613             :   // return an AddRec expression under some predicate.
    4614             : 
    4615             :   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
    4616         285 :   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
    4617             :   assert(L && "Expecting an integer loop header phi");
    4618             : 
    4619             :   // The loop may have multiple entrances or multiple exits; we can analyze
    4620             :   // this phi as an addrec if it has a unique entry value and a unique
    4621             :   // backedge value.
    4622             :   Value *BEValueV = nullptr, *StartValueV = nullptr;
    4623        1425 :   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    4624             :     Value *V = PN->getIncomingValue(i);
    4625         571 :     if (L->contains(PN->getIncomingBlock(i))) {
    4626         285 :       if (!BEValueV) {
    4627             :         BEValueV = V;
    4628           0 :       } else if (BEValueV != V) {
    4629             :         BEValueV = nullptr;
    4630             :         break;
    4631             :       }
    4632         286 :     } else if (!StartValueV) {
    4633             :       StartValueV = V;
    4634           1 :     } else if (StartValueV != V) {
    4635             :       StartValueV = nullptr;
    4636             :       break;
    4637             :     }
    4638             :   }
    4639         285 :   if (!BEValueV || !StartValueV)
    4640             :     return None;
    4641             : 
    4642         284 :   const SCEV *BEValue = getSCEV(BEValueV);
    4643             : 
    4644             :   // If the value coming around the backedge is an add with the symbolic
    4645             :   // value we just inserted, possibly with casts that we can ignore under
    4646             :   // an appropriate runtime guard, then we found a simple induction variable!
    4647             :   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
    4648             :   if (!Add)
    4649             :     return None;
    4650             : 
    4651             :   // If there is a single occurrence of the symbolic value, possibly
    4652             :   // casted, replace it with a recurrence.
    4653          48 :   unsigned FoundIndex = Add->getNumOperands();
    4654          48 :   Type *TruncTy = nullptr;
    4655             :   bool Signed;
    4656         204 :   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4657          97 :     if ((TruncTy =
    4658         194 :              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
    4659             :       if (FoundIndex == e) {
    4660             :         FoundIndex = i;
    4661             :         break;
    4662             :       }
    4663             : 
    4664          48 :   if (FoundIndex == Add->getNumOperands())
    4665             :     return None;
    4666             : 
    4667             :   // Create an add with everything but the specified operand.
    4668             :   SmallVector<const SCEV *, 8> Ops;
    4669          57 :   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4670          38 :     if (i != FoundIndex)
    4671          38 :       Ops.push_back(Add->getOperand(i));
    4672          19 :   const SCEV *Accum = getAddExpr(Ops);
    4673             : 
    4674             :   // The runtime checks will not be valid if the step amount is
    4675             :   // varying inside the loop.
    4676          19 :   if (!isLoopInvariant(Accum, L))
    4677             :     return None;
    4678             : 
    4679             :   // *** Part2: Create the predicates
    4680             : 
    4681             :   // Analysis was successful: we have a phi-with-cast pattern for which we
    4682             :   // can return an AddRec expression under the following predicates:
    4683             :   //
    4684             :   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
    4685             :   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
    4686             :   // P2: An Equal predicate that guarantees that
    4687             :   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
    4688             :   // P3: An Equal predicate that guarantees that
    4689             :   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
    4690             :   //
    4691             :   // As we next prove, the above predicates guarantee that:
    4692             :   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
    4693             :   //
    4694             :   //
    4695             :   // More formally, we want to prove that:
    4696             :   //     Expr(i+1) = Start + (i+1) * Accum
    4697             :   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
    4698             :   //
    4699             :   // Given that:
    4700             :   // 1) Expr(0) = Start
    4701             :   // 2) Expr(1) = Start + Accum
    4702             :   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
    4703             :   // 3) Induction hypothesis (step i):
    4704             :   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
    4705             :   //
    4706             :   // Proof:
    4707             :   //  Expr(i+1) =
    4708             :   //   = Start + (i+1)*Accum
    4709             :   //   = (Start + i*Accum) + Accum
    4710             :   //   = Expr(i) + Accum
    4711             :   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
    4712             :   //                                                             :: from step i
    4713             :   //
    4714             :   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
    4715             :   //
    4716             :   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
    4717             :   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
    4718             :   //     + Accum                                                     :: from P3
    4719             :   //
    4720             :   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
    4721             :   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
    4722             :   //
    4723             :   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
    4724             :   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
    4725             :   //
    4726             :   // By induction, the same applies to all iterations 1<=i<n:
    4727             :   //
    4728             : 
    4729             :   // Create a truncated addrec for which we will add a no overflow check (P1).
    4730          18 :   const SCEV *StartVal = getSCEV(StartValueV);
    4731             :   const SCEV *PHISCEV =
    4732          18 :       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
    4733          18 :                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
    4734             : 
    4735             :   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
    4736             :   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
    4737             :   // will be constant.
    4738             :   //
    4739             :   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
    4740             :   // add P1.
    4741             :   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
    4742             :     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
    4743          16 :         Signed ? SCEVWrapPredicate::IncrementNSSW
    4744             :                : SCEVWrapPredicate::IncrementNUSW;
    4745          16 :     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
    4746          16 :     Predicates.push_back(AddRecPred);
    4747             :   }
    4748             : 
    4749             :   // Create the Equal Predicates P2,P3:
    4750             : 
    4751             :   // It is possible that the predicates P2 and/or P3 are computable at
    4752             :   // compile time due to StartVal and/or Accum being constants.
    4753             :   // If either one is, then we can check that now and escape if either P2
    4754             :   // or P3 is false.
    4755             : 
    4756             :   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
    4757             :   // for each of StartVal and Accum
    4758             :   auto getExtendedExpr = [&](const SCEV *Expr, 
    4759          35 :                              bool CreateSignExtend) -> const SCEV * {
    4760             :     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
    4761          70 :     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
    4762             :     const SCEV *ExtendedExpr =
    4763          70 :         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
    4764          10 :                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
    4765          35 :     return ExtendedExpr;
    4766          18 :   };
    4767             : 
    4768             :   // Given:
    4769             :   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
    4770             :   //               = getExtendedExpr(Expr)
    4771             :   // Determine whether the predicate P: Expr == ExtendedExpr
    4772             :   // is known to be false at compile time
    4773             :   auto PredIsKnownFalse = [&](const SCEV *Expr,
    4774             :                               const SCEV *ExtendedExpr) -> bool {
    4775          53 :     return Expr != ExtendedExpr &&
    4776          18 :            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
    4777             :   };
    4778             : 
    4779          18 :   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
    4780             :   if (PredIsKnownFalse(StartVal, StartExtended)) {
    4781             :     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
    4782             :     return None;
    4783             :   }
    4784             : 
    4785             :   // The Step is always Signed (because the overflow checks are either
    4786             :   // NSSW or NUSW)
    4787          17 :   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
    4788             :   if (PredIsKnownFalse(Accum, AccumExtended)) {
    4789             :     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
    4790             :     return None;
    4791             :   }
    4792             : 
    4793             :   auto AppendPredicate = [&](const SCEV *Expr,
    4794          26 :                              const SCEV *ExtendedExpr) -> void {
    4795          35 :     if (Expr != ExtendedExpr &&
    4796          18 :         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
    4797           9 :       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
    4798             :       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
    4799           9 :       Predicates.push_back(Pred);
    4800             :     }
    4801          39 :   };
    4802             : 
    4803          13 :   AppendPredicate(StartVal, StartExtended);
    4804          13 :   AppendPredicate(Accum, AccumExtended);
    4805             : 
    4806             :   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
    4807             :   // which the casts had been folded away. The caller can rewrite SymbolicPHI
    4808             :   // into NewAR if it will also add the runtime overflow checks specified in
    4809             :   // Predicates.
    4810          13 :   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
    4811             : 
    4812             :   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
    4813             :       std::make_pair(NewAR, Predicates);
    4814             :   // Remember the result of the analysis for this SCEV at this locayyytion.
    4815          26 :   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
    4816             :   return PredRewrite;
    4817             : }
    4818             : 
    4819             : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
    4820        1044 : ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
    4821             :   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
    4822        1044 :   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
    4823        1044 :   if (!L)
    4824             :     return None;
    4825             : 
    4826             :   // Check to see if we already analyzed this PHI.
    4827        1066 :   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
    4828         533 :   if (I != PredicatedSCEVRewrites.end()) {
    4829             :     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
    4830             :         I->second;
    4831             :     // Analysis was done before and failed to create an AddRec:
    4832         248 :     if (Rewrite.first == SymbolicPHI)
    4833             :       return None;
    4834             :     // Analysis was done before and succeeded to create an AddRec under
    4835             :     // a predicate:
    4836             :     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
    4837             :     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
    4838             :     return Rewrite;
    4839             :   }
    4840             : 
    4841             :   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
    4842         285 :     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
    4843             : 
    4844             :   // Record in the cache that the analysis failed
    4845         285 :   if (!Rewrite) {
    4846             :     SmallVector<const SCEVPredicate *, 3> Predicates;
    4847         544 :     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
    4848             :     return None;
    4849             :   }
    4850             : 
    4851             :   return Rewrite;
    4852             : }
    4853             : 
    4854             : // FIXME: This utility is currently required because the Rewriter currently 
    4855             : // does not rewrite this expression: 
    4856             : // {0, +, (sext ix (trunc iy to ix) to iy)} 
    4857             : // into {0, +, %step},
    4858             : // even when the following Equal predicate exists: 
    4859             : // "%step == (sext ix (trunc iy to ix) to iy)".
    4860          28 : bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
    4861             :     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
    4862          28 :   if (AR1 == AR2)
    4863             :     return true;
    4864             : 
    4865          39 :   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
    4866          64 :     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
    4867          25 :         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
    4868             :       return false;
    4869             :     return true;
    4870          25 :   };
    4871             : 
    4872          89 :   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
    4873          14 :       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
    4874             :     return false;
    4875             :   return true;
    4876             : }
    4877             : 
    4878             : /// A helper function for createAddRecFromPHI to handle simple cases.
    4879             : ///
    4880             : /// This function tries to find an AddRec expression for the simplest (yet most
    4881             : /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
    4882             : /// If it fails, createAddRecFromPHI will use a more general, but slow,
    4883             : /// technique for finding the AddRec expression.
    4884       48073 : const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
    4885             :                                                       Value *BEValueV,
    4886             :                                                       Value *StartValueV) {
    4887       48073 :   const Loop *L = LI.getLoopFor(PN->getParent());
    4888             :   assert(L && L->getHeader() == PN->getParent());
    4889             :   assert(BEValueV && StartValueV);
    4890             : 
    4891       48073 :   auto BO = MatchBinaryOp(BEValueV, DT);
    4892       48073 :   if (!BO)
    4893             :     return nullptr;
    4894             : 
    4895       37929 :   if (BO->Opcode != Instruction::Add)
    4896             :     return nullptr;
    4897             : 
    4898             :   const SCEV *Accum = nullptr;
    4899       37103 :   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
    4900       35089 :     Accum = getSCEV(BO->RHS);
    4901        2014 :   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
    4902          34 :     Accum = getSCEV(BO->LHS);
    4903             : 
    4904       35123 :   if (!Accum)
    4905             :     return nullptr;
    4906             : 
    4907             :   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    4908       35123 :   if (BO->IsNUW)
    4909             :     Flags = setFlags(Flags, SCEV::FlagNUW);
    4910       35123 :   if (BO->IsNSW)
    4911             :     Flags = setFlags(Flags, SCEV::FlagNSW);
    4912             : 
    4913       35123 :   const SCEV *StartVal = getSCEV(StartValueV);
    4914       35123 :   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
    4915             : 
    4916      105369 :   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
    4917             : 
    4918             :   // We can add Flags to the post-inc expression only if we
    4919             :   // know that it is *undefined behavior* for BEValueV to
    4920             :   // overflow.
    4921             :   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
    4922       35123 :     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
    4923       14641 :       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
    4924             : 
    4925             :   return PHISCEV;
    4926             : }
    4927             : 
    4928       54883 : const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
    4929       54883 :   const Loop *L = LI.getLoopFor(PN->getParent());
    4930      105148 :   if (!L || L->getHeader() != PN->getParent())
    4931             :     return nullptr;
    4932             : 
    4933             :   // The loop may have multiple entrances or multiple exits; we can analyze
    4934             :   // this phi as an addrec if it has a unique entry value and a unique
    4935             :   // backedge value.
    4936             :   Value *BEValueV = nullptr, *StartValueV = nullptr;
    4937      240608 :   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    4938             :     Value *V = PN->getIncomingValue(i);
    4939       96284 :     if (L->contains(PN->getIncomingBlock(i))) {
    4940       48157 :       if (!BEValueV) {
    4941             :         BEValueV = V;
    4942          51 :       } else if (BEValueV != V) {
    4943             :         BEValueV = nullptr;
    4944             :         break;
    4945             :       }
    4946       48127 :     } else if (!StartValueV) {
    4947             :       StartValueV = V;
    4948          28 :     } else if (StartValueV != V) {
    4949             :       StartValueV = nullptr;
    4950             :       break;
    4951             :     }
    4952             :   }
    4953       48106 :   if (!BEValueV || !StartValueV)
    4954             :     return nullptr;
    4955             : 
    4956             :   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
    4957             :          "PHI node already processed?");
    4958             : 
    4959             :   // First, try to find AddRec expression without creating a fictituos symbolic
    4960             :   // value for PN.
    4961       48073 :   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
    4962             :     return S;
    4963             : 
    4964             :   // Handle PHI node value symbolically.
    4965       12950 :   const SCEV *SymbolicName = getUnknown(PN);
    4966       51800 :   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
    4967             : 
    4968             :   // Using this symbolic name for the PHI, analyze the value coming around
    4969             :   // the back-edge.
    4970       12950 :   const SCEV *BEValue = getSCEV(BEValueV);
    4971             : 
    4972             :   // NOTE: If BEValue is loop invariant, we know that the PHI node just
    4973             :   // has a special value for the first iteration of the loop.
    4974             : 
    4975             :   // If the value coming around the backedge is an add with the symbolic
    4976             :   // value we just inserted, then we found a simple induction variable!
    4977             :   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
    4978             :     // If there is a single occurrence of the symbolic value, replace it
    4979             :     // with a recurrence.
    4980        7849 :     unsigned FoundIndex = Add->getNumOperands();
    4981       25447 :     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4982       32446 :       if (Add->getOperand(i) == SymbolicName)
    4983             :         if (FoundIndex == e) {
    4984             :           FoundIndex = i;
    4985             :           break;
    4986             :         }
    4987             : 
    4988        7849 :     if (FoundIndex != Add->getNumOperands()) {
    4989             :       // Create an add with everything but the specified operand.
    4990             :       SmallVector<const SCEV *, 8> Ops;
    4991       22993 :       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4992       15569 :         if (i != FoundIndex)
    4993       16290 :           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
    4994             :                                                              L, *this));
    4995        7424 :       const SCEV *Accum = getAddExpr(Ops);
    4996             : 
    4997             :       // This is not a valid addrec if the step amount is varying each
    4998             :       // loop iteration, but is not itself an addrec in this loop.
    4999        8198 :       if (isLoopInvariant(Accum, L) ||
    5000          68 :           (isa<SCEVAddRecExpr>(Accum) &&
    5001          68 :            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
    5002             :         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    5003             : 
    5004        6718 :         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
    5005        1185 :           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
    5006          49 :             if (BO->IsNUW)
    5007             :               Flags = setFlags(Flags, SCEV::FlagNUW);
    5008          49 :             if (BO->IsNSW)
    5009             :               Flags = setFlags(Flags, SCEV::FlagNSW);
    5010             :           }
    5011             :         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
    5012             :           // If the increment is an inbounds GEP, then we know the address
    5013             :           // space cannot be wrapped around. We cannot make any guarantee
    5014             :           // about signed or unsigned overflow because pointers are
    5015             :           // unsigned but we may have a negative index from the base
    5016             :           // pointer. We can guarantee that no unsigned wrap occurs if the
    5017             :           // indices form a positive value.
    5018        9406 :           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
    5019             :             Flags = setFlags(Flags, SCEV::FlagNW);
    5020             : 
    5021        4204 :             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
    5022        4204 :             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
    5023             :               Flags = setFlags(Flags, SCEV::FlagNUW);
    5024             :           }
    5025             : 
    5026             :           // We cannot transfer nuw and nsw flags from subtraction
    5027             :           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
    5028             :           // for instance.
    5029             :         }
    5030             : 
    5031        6718 :         const SCEV *StartVal = getSCEV(StartValueV);
    5032        6718 :         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
    5033             : 
    5034             :         // Okay, for the entire analysis of this edge we assumed the PHI
    5035             :         // to be symbolic.  We now need to go back and purge all of the
    5036             :         // entries for the scalars that use the symbolic expression.
    5037        6718 :         forgetSymbolicName(PN, SymbolicName);
    5038       20154 :         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
    5039             : 
    5040             :         // We can add Flags to the post-inc expression only if we
    5041             :         // know that it is *undefined behavior* for BEValueV to
    5042             :         // overflow.
    5043             :         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
    5044        6718 :           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
    5045        1902 :             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
    5046             : 
    5047             :         return PHISCEV;
    5048             :       }
    5049             :     }
    5050             :   } else {
    5051             :     // Otherwise, this could be a loop like this:
    5052             :     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
    5053             :     // In this case, j = {1,+,1}  and BEValue is j.
    5054             :     // Because the other in-value of i (0) fits the evolution of BEValue
    5055             :     // i really is an addrec evolution.
    5056             :     //
    5057             :     // We can generalize this saying that i is the shifted value of BEValue
    5058             :     // by one iteration:
    5059             :     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
    5060        5101 :     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
    5061        5101 :     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
    5062        5850 :     if (Shifted != getCouldNotCompute() &&
    5063         749 :         Start != getCouldNotCompute()) {
    5064         749 :       const SCEV *StartVal = getSCEV(StartValueV);
    5065         749 :       if (Start == StartVal) {
    5066             :         // Okay, for the entire analysis of this edge we assumed the PHI
    5067             :         // to be symbolic.  We now need to go back and purge all of the
    5068             :         // entries for the scalars that use the symbolic expression.
    5069         537 :         forgetSymbolicName(PN, SymbolicName);
    5070        1611 :         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
    5071         537 :         return Shifted;
    5072             :       }
    5073             :     }
    5074             :   }
    5075             : 
    5076             :   // Remove the temporary PHI node SCEV that has been inserted while intending
    5077             :   // to create an AddRecExpr for this PHI node. We can not keep this temporary
    5078             :   // as it will prevent later (possibly simpler) SCEV expressions to be added
    5079             :   // to the ValueExprMap.
    5080        5695 :   eraseValueFromMap(PN);
    5081             : 
    5082        5695 :   return nullptr;
    5083             : }
    5084             : 
    5085             : // Checks if the SCEV S is available at BB.  S is considered available at BB
    5086             : // if S can be materialized at BB without introducing a fault.
    5087        8101 : static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
    5088             :                                BasicBlock *BB) {
    5089             :   struct CheckAvailable {
    5090             :     bool TraversalDone = false;
    5091             :     bool Available = true;
    5092             : 
    5093             :     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
    5094             :     BasicBlock *BB = nullptr;
    5095             :     DominatorTree &DT;
    5096             : 
    5097             :     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
    5098        8101 :       : L(L), BB(BB), DT(DT) {}
    5099             : 
    5100             :     bool setUnavailable() {
    5101        2863 :       TraversalDone = true;
    5102        2863 :       Available = false;
    5103             :       return false;
    5104             :     }
    5105             : 
    5106       14656 :     bool follow(const SCEV *S) {
    5107       29312 :       switch (S->getSCEVType()) {
    5108             :       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
    5109             :       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
    5110             :         // These expressions are available if their operand(s) is/are.
    5111             :         return true;
    5112             : 
    5113             :       case scAddRecExpr: {
    5114             :         // We allow add recurrences that are on the loop BB is in, or some
    5115             :         // outer loop.  This guarantees availability because the value of the
    5116             :         // add recurrence at BB is simply the "current" value of the induction
    5117             :         // variable.  We can relax this in the future; for instance an add
    5118             :         // recurrence on a sibling dominating loop is also available at BB.
    5119         380 :         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
    5120         409 :         if (L && (ARLoop == L || ARLoop->contains(L)))
    5121             :           return true;
    5122             : 
    5123         227 :         return setUnavailable();
    5124             :       }
    5125             : 
    5126             :       case scUnknown: {
    5127             :         // For SCEVUnknown, we check for simple dominance.
    5128             :         const auto *SU = cast<SCEVUnknown>(S);
    5129             :         Value *V = SU->getValue();
    5130             : 
    5131        6003 :         if (isa<Argument>(V))
    5132             :           return false;
    5133             : 
    5134        5633 :         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
    5135             :           return false;
    5136             : 
    5137        1726 :         return setUnavailable();
    5138             :       }
    5139             : 
    5140         910 :       case scUDivExpr:
    5141             :       case scCouldNotCompute:
    5142             :         // We do not try to smart about these at all.
    5143         910 :         return setUnavailable();
    5144             :       }
    5145           0 :       llvm_unreachable("switch should be fully covered!");
    5146             :     }
    5147             : 
    5148             :     bool isDone() { return TraversalDone; }
    5149             :   };
    5150             : 
    5151             :   CheckAvailable CA(L, BB, DT);
    5152        8101 :   SCEVTraversal<CheckAvailable> ST(CA);
    5153             : 
    5154        8101 :   ST.visitAll(S);
    5155       16202 :   return CA.Available;
    5156             : }
    5157             : 
    5158             : // Try to match a control flow sequence that branches out at BI and merges back
    5159             : // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
    5160             : // match.
    5161        4772 : static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
    5162             :                           Value *&C, Value *&LHS, Value *&RHS) {
    5163        4772 :   C = BI->getCondition();
    5164             : 
    5165        4772 :   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
    5166             :   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
    5167             : 
    5168        4772 :   if (!LeftEdge.isSingleEdge())
    5169             :     return false;
    5170             : 
    5171             :   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
    5172             : 
    5173        4772 :   Use &LeftUse = Merge->getOperandUse(0);
    5174             :   Use &RightUse = Merge->getOperandUse(1);
    5175             : 
    5176        4772 :   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
    5177        3409 :     LHS = LeftUse;
    5178        3409 :     RHS = RightUse;
    5179        3409 :     return true;
    5180             :   }
    5181             : 
    5182        1363 :   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
    5183        1270 :     LHS = RightUse;
    5184        1270 :     RHS = LeftUse;
    5185        1270 :     return true;
    5186             :   }
    5187             : 
    5188             :   return false;
    5189             : }
    5190             : 
    5191       12505 : const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
    5192             :   auto IsReachable =
    5193       21218 :       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
    5194       23114 :   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
    5195       10608 :     const Loop *L = LI.getLoopFor(PN->getParent());
    5196             : 
    5197             :     // We don't want to break LCSSA, even in a SCEV expression tree.
    5198       34708 :     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    5199       35722 :       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
    5200        7629 :         return nullptr;
    5201             : 
    5202             :     // Try to match
    5203             :     //
    5204             :     //  br %cond, label %left, label %right
    5205             :     // left:
    5206             :     //  br label %merge
    5207             :     // right:
    5208             :     //  br label %merge
    5209             :     // merge:
    5210             :     //  V = phi [ %x, %left ], [ %y, %right ]
    5211             :     //
    5212             :     // as "select %cond, %x, %y"
    5213             : 
    5214        9594 :     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
    5215             :     assert(IDom && "At least the entry block should dominate PN");
    5216             : 
    5217             :     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
    5218        4797 :     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
    5219             : 
    5220        9544 :     if (BI && BI->isConditional() &&
    5221        9451 :         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
    5222       12898 :         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
    5223        3422 :         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
    5224        1818 :       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
    5225             :   }
    5226             : 
    5227             :   return nullptr;
    5228             : }
    5229             : 
    5230       54883 : const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
    5231       54883 :   if (const SCEV *S = createAddRecFromPHI(PN))
    5232             :     return S;
    5233             : 
    5234       12505 :   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
    5235             :     return S;
    5236             : 
    5237             :   // If the PHI has a single incoming value, follow that value, unless the
    5238             :   // PHI's incoming blocks are in a different loop, in which case doing so
    5239             :   // risks breaking LCSSA form. Instcombine would normally zap these, but
    5240             :   // it doesn't have DominatorTree information, so it may miss cases.
    5241       32061 :   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
    5242         829 :     if (LI.replacementPreservesLCSSAForm(PN, V))
    5243         144 :       return getSCEV(V);
    5244             : 
    5245             :   // If it's not a loop phi, we can't handle it yet.
    5246       10543 :   return getUnknown(PN);
    5247             : }
    5248             : 
    5249       15592 : const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
    5250             :                                                       Value *Cond,
    5251             :                                                       Value *TrueVal,
    5252             :                                                       Value *FalseVal) {
    5253             :   // Handle "constant" branch or select. This can occur for instance when a
    5254             :   // loop pass transforms an inner loop and moves on to process the outer loop.
    5255             :   if (auto *CI = dyn_cast<ConstantInt>(Cond))
    5256          90 :     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
    5257             : 
    5258             :   // Try to match some simple smax or umax patterns.
    5259             :   auto *ICI = dyn_cast<ICmpInst>(Cond);
    5260             :   if (!ICI)
    5261         567 :     return getUnknown(I);
    5262             : 
    5263             :   Value *LHS = ICI->getOperand(0);
    5264             :   Value *RHS = ICI->getOperand(1);
    5265             : 
    5266       14935 :   switch (ICI->getPredicate()) {
    5267             :   case ICmpInst::ICMP_SLT:
    5268             :   case ICmpInst::ICMP_SLE:
    5269             :     std::swap(LHS, RHS);
    5270             :     LLVM_FALLTHROUGH;
    5271         926 :   case ICmpInst::ICMP_SGT:
    5272             :   case ICmpInst::ICMP_SGE:
    5273             :     // a >s b ? a+x : b+x  ->  smax(a, b)+x
    5274             :     // a >s b ? b+x : a+x  ->  smin(a, b)+x
    5275         926 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
    5276         904 :       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
    5277         904 :       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
    5278         904 :       const SCEV *LA = getSCEV(TrueVal);
    5279         904 :       const SCEV *RA = getSCEV(FalseVal);
    5280         904 :       const SCEV *LDiff = getMinusSCEV(LA, LS);
    5281         904 :       const SCEV *RDiff = getMinusSCEV(RA, RS);
    5282         904 :       if (LDiff == RDiff)
    5283         411 :         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
    5284         493 :       LDiff = getMinusSCEV(LA, RS);
    5285         493 :       RDiff = getMinusSCEV(RA, LS);
    5286         493 :       if (LDiff == RDiff)
    5287         102 :         return getAddExpr(getSMinExpr(LS, RS), LDiff);
    5288             :     }
    5289             :     break;
    5290             :   case ICmpInst::ICMP_ULT:
    5291             :   case ICmpInst::ICMP_ULE:
    5292             :     std::swap(LHS, RHS);
    5293             :     LLVM_FALLTHROUGH;
    5294        3270 :   case ICmpInst::ICMP_UGT:
    5295             :   case ICmpInst::ICMP_UGE:
    5296             :     // a >u b ? a+x : b+x  ->  umax(a, b)+x
    5297             :     // a >u b ? b+x : a+x  ->  umin(a, b)+x
    5298        3270 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
    5299        3245 :       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
    5300        3245 :       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
    5301        3245 :       const SCEV *LA = getSCEV(TrueVal);
    5302        3245 :       const SCEV *RA = getSCEV(FalseVal);
    5303        3245 :       const SCEV *LDiff = getMinusSCEV(LA, LS);
    5304        3245 :       const SCEV *RDiff = getMinusSCEV(RA, RS);
    5305        3245 :       if (LDiff == RDiff)
    5306         201 :         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
    5307        3044 :       LDiff = getMinusSCEV(LA, RS);
    5308        3044 :       RDiff = getMinusSCEV(RA, LS);
    5309        3044 :       if (LDiff == RDiff)
    5310         199 :         return getAddExpr(getUMinExpr(LS, RS), LDiff);
    5311             :     }
    5312             :     break;
    5313        7127 :   case ICmpInst::ICMP_NE:
    5314             :     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
    5315       14117 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
    5316        8459 :         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
    5317        1240 :       const SCEV *One = getOne(I->getType());
    5318        1240 :       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
    5319        1240 :       const SCEV *LA = getSCEV(TrueVal);
    5320        1240 :       const SCEV *RA = getSCEV(FalseVal);
    5321        1240 :       const SCEV *LDiff = getMinusSCEV(LA, LS);
    5322        1240 :       const SCEV *RDiff = getMinusSCEV(RA, One);
    5323        1240 :       if (LDiff == RDiff)
    5324           1 :         return getAddExpr(getUMaxExpr(One, LS), LDiff);
    5325             :     }
    5326             :     break;
    5327        3612 :   case ICmpInst::ICMP_EQ:
    5328             :     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
    5329        7083 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
    5330        5862 :         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
    5331        1308 :       const SCEV *One = getOne(I->getType());
    5332        1308 :       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
    5333        1308 :       const SCEV *LA = getSCEV(TrueVal);
    5334        1308 :       const SCEV *RA = getSCEV(FalseVal);
    5335        1308 :       const SCEV *LDiff = getMinusSCEV(LA, One);
    5336        1308 :       const SCEV *RDiff = getMinusSCEV(RA, LS);
    5337        1308 :       if (LDiff == RDiff)
    5338          50 :         return getAddExpr(getUMaxExpr(One, LS), LDiff);
    5339             :     }
    5340             :     break;
    5341             :   default:
    5342             :     break;
    5343             :   }
    5344             : 
    5345       13971 :   return getUnknown(I);
    5346             : }
    5347             : 
    5348             : /// Expand GEP instructions into add and multiply operations. This allows them
    5349             : /// to be analyzed by regular SCEV code.
    5350      170225 : const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
    5351             :   // Don't attempt to analyze GEPs over unsized objects.
    5352      170225 :   if (!GEP->getSourceElementType()->isSized())
    5353           0 :     return getUnknown(GEP);
    5354             : 
    5355             :   SmallVector<const SCEV *, 4> IndexExprs;
    5356      796493 :   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
    5357      313134 :     IndexExprs.push_back(getSCEV(*Index));
    5358      170225 :   return getGEPExpr(GEP, IndexExprs);
    5359             : }
    5360             : 
    5361      522423 : uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
    5362             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
    5363       96789 :     return C->getAPInt().countTrailingZeros();
    5364             : 
    5365             :   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
    5366        4292 :     return std::min(GetMinTrailingZeros(T->getOperand()),
    5367        6438 :                     (uint32_t)getTypeSizeInBits(T->getType()));
    5368             : 
    5369             :   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
    5370       15249 :     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
    5371       15249 :     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
    5372           0 :                ? getTypeSizeInBits(E->getType())
    5373       15249 :                : OpRes;
    5374             :   }
    5375             : 
    5376             :   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
    5377        8153 :     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
    5378        8153 :     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
    5379           0 :                ? getTypeSizeInBits(E->getType())
    5380        8153 :                : OpRes;
    5381             :   }
    5382             : 
    5383             :   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
    5384             :     // The result is the min of all operands results.
    5385      175920 :     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
    5386      143336 :     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
    5387      166128 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
    5388             :     return MinOpRes;
    5389             :   }
    5390             : 
    5391             :   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
    5392             :     // The result is the sum of all operands results.
    5393      112284 :     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
    5394       56142 :     uint32_t BitWidth = getTypeSizeInBits(M->getType());
    5395      118498 :     for (unsigned i = 1, e = M->getNumOperands();
    5396      118498 :          SumOpRes != BitWidth && i != e; ++i)
    5397       62356 :       SumOpRes =
    5398      187068 :           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
    5399             :     return SumOpRes;
    5400             :   }
    5401             : 
    5402             :   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
    5403             :     // The result is the min of all operands results.
    5404      232838 :     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
    5405      187166 :     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
    5406      212241 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
    5407             :     return MinOpRes;
    5408             :   }
    5409             : 
    5410             :   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
    5411             :     // The result is the min of all operands results.
    5412        4138 :     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
    5413        3339 :     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
    5414        3810 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
    5415             :     return MinOpRes;
    5416             :   }
    5417             : 
    5418             :   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
    5419             :     // The result is the min of all operands results.
    5420        1378 :     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
    5421         753 :     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
    5422         192 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
    5423             :     return MinOpRes;
    5424             :   }
    5425             : 
    5426      133387 :   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
    5427             :     // For a SCEVUnknown, ask ValueTracking.
    5428      400161 :     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
    5429             :     return Known.countMinTrailingZeros();
    5430             :   }
    5431             : 
    5432             :   // SCEVUDivExpr
    5433             :   return 0;
    5434             : }
    5435             : 
    5436     1285891 : uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
    5437     1285891 :   auto I = MinTrailingZerosCache.find(S);
    5438     1285891 :   if (I != MinTrailingZerosCache.end())
    5439      763468 :     return I->second;
    5440             : 
    5441      522423 :   uint32_t Result = GetMinTrailingZerosImpl(S);
    5442      522423 :   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
    5443             :   assert(InsertPair.second && "Should insert a new key");
    5444      522423 :   return InsertPair.first->second;
    5445             : }
    5446             : 
    5447             : /// Helper method to assign a range to V from metadata present in the IR.
    5448      265082 : static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
    5449             :   if (Instruction *I = dyn_cast<Instruction>(V))
    5450       72350 :     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
    5451       24962 :       return getConstantRangeFromMetadata(*MD);
    5452             : 
    5453             :   return None;
    5454             : }
    5455             : 
    5456             : /// Determine the range for a particular SCEV.  If SignHint is
    5457             : /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
    5458             : /// with a "cleaner" unsigned (resp. signed) representation.
    5459             : const ConstantRange &
    5460     9490241 : ScalarEvolution::getRangeRef(const SCEV *S,
    5461             :                              ScalarEvolution::RangeSignHint SignHint) {
    5462     9490241 :   DenseMap<const SCEV *, ConstantRange> &Cache =
    5463             :       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
    5464             :                                                        : SignedRanges;
    5465             : 
    5466             :   // See if we've computed this range already.
    5467     9490241 :   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
    5468     9490241 :   if (I != Cache.end())
    5469     8219067 :     return I->second;
    5470             : 
    5471             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
    5472      936034 :     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
    5473             : 
    5474      803157 :   unsigned BitWidth = getTypeSizeInBits(S->getType());
    5475     1606314 :   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
    5476             : 
    5477             :   // If the value has known zeros, the maximum value will have those known zeros
    5478             :   // as well.
    5479      803157 :   uint32_t TZ = GetMinTrailingZeros(S);
    5480      803157 :   if (TZ != 0) {
    5481      264984 :     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
    5482      128612 :       ConservativeResult =
    5483      385836 :           ConstantRange(APInt::getMinValue(BitWidth),
    5484      643060 :                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
    5485             :     else
    5486      136372 :       ConservativeResult = ConstantRange(
    5487      272744 :           APInt::getSignedMinValue(BitWidth),
    5488      681860 :           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
    5489             :   }
    5490             : 
    5491             :   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
    5492      455922 :     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
    5493      878041 :     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
    5494     1452134 :       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
    5495      151974 :     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
    5496             :   }
    5497             : 
    5498             :   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
    5499      321744 :     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
    5500      231814 :     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
    5501      249132 :       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
    5502      107248 :     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
    5503             :   }
    5504             : 
    5505             :   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
    5506       12414 :     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
    5507        9108 :     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
    5508        9940 :       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
    5509        4138 :     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
    5510             :   }
    5511             : 
    5512             :   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
    5513        4134 :     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
    5514        2812 :     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
    5515        2868 :       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
    5516        1378 :     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
    5517             :   }
    5518             : 
    5519             :   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
    5520       13338 :     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
    5521       13338 :     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
    5522             :     return setRange(UDiv, SignHint,
    5523        6669 :                     ConservativeResult.intersectWith(X.udiv(Y)));
    5524             :   }
    5525             : 
    5526             :   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
    5527       59638 :     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
    5528             :     return setRange(ZExt, SignHint,
    5529       29819 :                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
    5530             :   }
    5531             : 
    5532             :   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
    5533       31992 :     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
    5534             :     return setRange(SExt, SignHint,
    5535       15996 :                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
    5536             :   }
    5537             : 
    5538             :   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
    5539        8136 :     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
    5540             :     return setRange(Trunc, SignHint,
    5541        4068 :                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
    5542             :   }
    5543             : 
    5544             :   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
    5545             :     // If there's no unsigned wrap, the value will never be less than its
    5546             :     // initial value.
    5547      216785 :     if (AddRec->hasNoUnsignedWrap())
    5548       76837 :       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
    5549      135294 :         if (!C->getValue()->isZero())
    5550       21294 :           ConservativeResult = ConservativeResult.intersectWith(
    5551       85176 :               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
    5552             : 
    5553             :     // If there's no signed wrap, and all the operands have the same sign or
    5554             :     // zero, the value won't ever change sign.
    5555      216785 :     if (AddRec->hasNoSignedWrap()) {
    5556             :       bool AllNonNeg = true;
    5557             :       bool AllNonPos = true;
    5558      209295 :       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
    5559      279060 :         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
    5560      279060 :         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
    5561             :       }
    5562       69765 :       if (AllNonNeg)
    5563       56680 :         ConservativeResult = ConservativeResult.intersectWith(
    5564      170040 :           ConstantRange(APInt(BitWidth, 0),
    5565      113360 :                         APInt::getSignedMinValue(BitWidth)));
    5566       13085 :       else if (AllNonPos)
    5567         257 :         ConservativeResult = ConservativeResult.intersectWith(
    5568         771 :           ConstantRange(APInt::getSignedMinValue(BitWidth),
    5569         257 :                         APInt(BitWidth, 1)));
    5570             :     }
    5571             : 
    5572             :     // TODO: non-affine addrec
    5573      216785 :     if (AddRec->isAffine()) {
    5574      214927 :       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
    5575      372367 :       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
    5576      157440 :           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
    5577             :         auto RangeFromAffine = getRangeForAffineAR(
    5578             :             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
    5579      462135 :             BitWidth);
    5580      154045 :         if (!RangeFromAffine.isFullSet())
    5581      109489 :           ConservativeResult =
    5582      218978 :               ConservativeResult.intersectWith(RangeFromAffine);
    5583             : 
    5584             :         auto RangeFromFactoring = getRangeViaFactoring(
    5585             :             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
    5586      462135 :             BitWidth);
    5587      154045 :         if (!RangeFromFactoring.isFullSet())
    5588          62 :           ConservativeResult =
    5589         124 :               ConservativeResult.intersectWith(RangeFromFactoring);
    5590             :       }
    5591             :     }
    5592             : 
    5593      216785 :     return setRange(AddRec, SignHint, std::move(ConservativeResult));
    5594             :   }
    5595             : 
    5596      265082 :   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
    5597             :     // Check if the IR explicitly contains !range metadata.
    5598      265082 :     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
    5599      265082 :     if (MDRange.hasValue())
    5600       12481 :       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
    5601             : 
    5602             :     // Split here to avoid paying the compile-time cost of calling both
    5603             :     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
    5604             :     // if needed.
    5605      265082 :     const DataLayout &DL = getDataLayout();
    5606      265082 :     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
    5607             :       // For a SCEVUnknown, ask ValueTracking.
    5608      383877 :       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
    5609      383877 :       if (Known.One != ~Known.Zero + 1)
    5610       64041 :         ConservativeResult =
    5611      192123 :             ConservativeResult.intersectWith(ConstantRange(Known.One,
    5612      192123 :                                                            ~Known.Zero + 1));
    5613             :     } else {
    5614             :       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
    5615             :              "generalize as needed!");
    5616      274246 :       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
    5617      137123 :       if (NS > 1)
    5618       21034 :         ConservativeResult = ConservativeResult.intersectWith(
    5619       84136 :             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
    5620       84136 :                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
    5621             :     }
    5622             : 
    5623             :     // A range of Phi is a subset of union of all ranges of its input.
    5624             :     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
    5625             :       // Make sure that we do not run over cycled Phis.
    5626       28587 :       if (PendingPhiRanges.insert(Phi).second) {
    5627       38486 :         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
    5628       56454 :         for (auto &Op : Phi->operands()) {
    5629       34328 :           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
    5630       25344 :           RangeFromOps = RangeFromOps.unionWith(OpRange);
    5631             :           // No point to continue if we already have a full set.
    5632       25344 :           if (RangeFromOps.isFullSet())
    5633             :             break;
    5634             :         }
    5635       19243 :         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
    5636             :         bool Erased = PendingPhiRanges.erase(Phi);
    5637             :         assert(Erased && "Failed to erase Phi properly?");
    5638             :         (void) Erased;
    5639             :       }
    5640             :     }
    5641             : 
    5642      265082 :     return setRange(U, SignHint, std::move(ConservativeResult));
    5643             :   }
    5644             : 
    5645           0 :   return setRange(S, SignHint, std::move(ConservativeResult));
    5646             : }
    5647             : 
    5648             : // Given a StartRange, Step and MaxBECount for an expression compute a range of
    5649             : // values that the expression can take. Initially, the expression has a value
    5650             : // from StartRange and then is changed by Step up to MaxBECount times. Signed
    5651             : // argument defines if we treat Step as signed or unsigned.
    5652      462507 : static ConstantRange getRangeForAffineARHelper(APInt Step,
    5653             :                                                const ConstantRange &StartRange,
    5654             :                                                const APInt &MaxBECount,
    5655             :                                                unsigned BitWidth, bool Signed) {
    5656             :   // If either Step or MaxBECount is 0, then the expression won't change, and we
    5657             :   // just need to return the initial range.
    5658      462507 :   if (Step == 0 || MaxBECount == 0)
    5659       10980 :     return StartRange;
    5660             : 
    5661             :   // If we don't know anything about the initial value (i.e. StartRange is
    5662             :   // FullRange), then we don't know anything about the final range either.
    5663             :   // Return FullRange.
    5664      451527 :   if (StartRange.isFullSet())
    5665       74706 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5666             : 
    5667             :   // If Step is signed and negative, then we use its absolute value, but we also
    5668             :   // note that we're moving in the opposite direction.
    5669      628371 :   bool Descending = Signed && Step.isNegative();
    5670             : 
    5671      376821 :   if (Signed)
    5672             :     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
    5673             :     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
    5674             :     // This equations hold true due to the well-defined wrap-around behavior of
    5675             :     // APInt.
    5676      503100 :     Step = Step.abs();
    5677             : 
    5678             :   // Check if Offset is more than full span of BitWidth. If it is, the
    5679             :   // expression is guaranteed to overflow.
    5680     1130463 :   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
    5681       60765 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5682             : 
    5683             :   // Offset is by how much the expression can change. Checks above guarantee no
    5684             :   // overflow here.
    5685      316056 :   APInt Offset = Step * MaxBECount;
    5686             : 
    5687             :   // Minimum value of the final range will match the minimal value of StartRange
    5688             :   // if the expression is increasing and will be decreased by Offset otherwise.
    5689             :   // Maximum value of the final range will match the maximal value of StartRange
    5690             :   // if the expression is decreasing and will be increased by Offset otherwise.
    5691             :   APInt StartLower = StartRange.getLower();
    5692      316056 :   APInt StartUpper = StartRange.getUpper() - 1;
    5693             :   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
    5694      316056 :                                    : (StartUpper + std::move(Offset));
    5695             : 
    5696             :   // It's possible that the new minimum/maximum value will fall into the initial
    5697             :   // range (due to wrap around). This means that the expression can take any
    5698             :   // value in this bitwidth, and we have to return full range.
    5699      316056 :   if (StartRange.contains(MovedBoundary))
    5700       11493 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5701             : 
    5702             :   APInt NewLower =
    5703      304563 :       Descending ? std::move(MovedBoundary) : std::move(StartLower);
    5704             :   APInt NewUpper =
    5705      304563 :       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
    5706      304563 :   NewUpper += 1;
    5707             : 
    5708             :   // If we end up with full range, return a proper full range.
    5709      304563 :   if (NewLower == NewUpper)
    5710       13033 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5711             : 
    5712             :   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
    5713      874590 :   return ConstantRange(std::move(NewLower), std::move(NewUpper));
    5714             : }
    5715             : 
    5716      154169 : ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
    5717             :                                                    const SCEV *Step,
    5718             :                                                    const SCEV *MaxBECount,
    5719             :                                                    unsigned BitWidth) {
    5720             :   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
    5721             :          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
    5722             :          "Precondition!");
    5723             : 
    5724      154169 :   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
    5725             :   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
    5726             : 
    5727             :   // First, consider step signed.
    5728      154169 :   ConstantRange StartSRange = getSignedRange(Start);
    5729      154169 :   ConstantRange StepSRange = getSignedRange(Step);
    5730             : 
    5731             :   // If Step can be both positive and negative, we need to find ranges for the
    5732             :   // maximum absolute step values in both directions and union them.
    5733             :   ConstantRange SR =
    5734      308338 :       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
    5735      308338 :                                 MaxBECountValue, BitWidth, /* Signed = */ true);
    5736      308338 :   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
    5737             :                                               StartSRange, MaxBECountValue,
    5738             :                                               BitWidth, /* Signed = */ true));
    5739             : 
    5740             :   // Next, consider step unsigned.
    5741             :   ConstantRange UR = getRangeForAffineARHelper(
    5742      154169 :       getUnsignedRangeMax(Step), getUnsignedRange(Start),
    5743      308338 :       MaxBECountValue, BitWidth, /* Signed = */ false);
    5744             : 
    5745             :   // Finally, intersect signed and unsigned ranges.
    5746      308338 :   return SR.intersectWith(UR);
    5747             : }
    5748             : 
    5749      154045 : ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
    5750             :                                                     const SCEV *Step,
    5751             :                                                     const SCEV *MaxBECount,
    5752             :                                                     unsigned BitWidth) {
    5753             :   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
    5754             :   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
    5755             : 
    5756      308224 :   struct SelectPattern {
    5757             :     Value *Condition = nullptr;
    5758             :     APInt TrueValue;
    5759             :     APInt FalseValue;
    5760             : 
    5761      154112 :     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
    5762      308224 :                            const SCEV *S) {
    5763             :       Optional<unsigned> CastOp;
    5764             :       APInt Offset(BitWidth, 0);
    5765             : 
    5766             :       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
    5767             :              "Should be!");
    5768             : 
    5769             :       // Peel off a constant offset:
    5770             :       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
    5771             :         // In the future we could consider being smarter here and handle
    5772             :         // {Start+Step,+,Step} too.
    5773       33065 :         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
    5774             :           return;
    5775             : 
    5776       13890 :         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
    5777       13890 :         S = SA->getOperand(1);
    5778             :       }
    5779             : 
    5780             :       // Peel off a cast operation
    5781             :       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
    5782             :         CastOp = SCast->getSCEVType();
    5783        2377 :         S = SCast->getOperand();
    5784             :       }
    5785             : 
    5786             :       using namespace llvm::PatternMatch;
    5787             : 
    5788             :       auto *SU = dyn_cast<SCEVUnknown>(S);
    5789             :       const APInt *TrueVal, *FalseVal;
    5790       44324 :       if (!SU ||
    5791      172868 :           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
    5792             :                                           m_APInt(FalseVal)))) {
    5793      150577 :         Condition = nullptr;
    5794             :         return;
    5795             :       }
    5796             : 
    5797         129 :       TrueValue = *TrueVal;
    5798         129 :       FalseValue = *FalseVal;
    5799             : 
    5800             :       // Re-apply the cast we peeled off earlier
    5801         129 :       if (CastOp.hasValue())
    5802          32 :         switch (*CastOp) {
    5803           0 :         default:
    5804           0 :           llvm_unreachable("Unknown SCEV cast type!");
    5805             : 
    5806          16 :         case scTruncate:
    5807          32 :           TrueValue = TrueValue.trunc(BitWidth);
    5808          32 :           FalseValue = FalseValue.trunc(BitWidth);
    5809             :           break;
    5810           4 :         case scZeroExtend:
    5811           8 :           TrueValue = TrueValue.zext(BitWidth);
    5812           8 :           FalseValue = FalseValue.zext(BitWidth);
    5813             :           break;
    5814          12 :         case scSignExtend:
    5815          24 :           TrueValue = TrueValue.sext(BitWidth);
    5816          24 :           FalseValue = FalseValue.sext(BitWidth);
    5817             :           break;
    5818             :         }
    5819             : 
    5820             :       // Re-apply the constant offset we peeled off earlier
    5821         129 :       TrueValue += Offset;
    5822         129 :       FalseValue += Offset;
    5823             :     }
    5824             : 
    5825             :     bool isRecognized() { return Condition != nullptr; }
    5826             :   };
    5827             : 
    5828      308090 :   SelectPattern StartPattern(*this, BitWidth, Start);
    5829      154045 :   if (!StartPattern.isRecognized())
    5830      153978 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5831             : 
    5832         134 :   SelectPattern StepPattern(*this, BitWidth, Step);
    5833          67 :   if (!StepPattern.isRecognized())
    5834           5 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5835             : 
    5836          62 :   if (StartPattern.Condition != StepPattern.Condition) {
    5837             :     // We don't handle this case today; but we could, by considering four
    5838             :     // possibilities below instead of two. I'm not sure if there are cases where
    5839             :     // that will help over what getRange already does, though.
    5840           0 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5841             :   }
    5842             : 
    5843             :   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
    5844             :   // construct arbitrary general SCEV expressions here.  This function is called
    5845             :   // from deep in the call stack, and calling getSCEV (on a sext instruction,
    5846             :   // say) can end up caching a suboptimal value.
    5847             : 
    5848             :   // FIXME: without the explicit `this` receiver below, MSVC errors out with
    5849             :   // C2352 and C2512 (otherwise it isn't needed).
    5850             : 
    5851          62 :   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
    5852          62 :   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
    5853          62 :   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
    5854          62 :   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
    5855             : 
    5856             :   ConstantRange TrueRange =
    5857         124 :       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
    5858             :   ConstantRange FalseRange =
    5859         124 :       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
    5860             : 
    5861          62 :   return TrueRange.unionWith(FalseRange);
    5862             : }
    5863             : 
    5864       74645 : SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
    5865       74645 :   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
    5866             :   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
    5867             : 
    5868             :   // Return early if there are no flags to propagate to the SCEV.
    5869             :   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    5870       74639 :   if (BinOp->hasNoUnsignedWrap())
    5871             :     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
    5872       74639 :   if (BinOp->hasNoSignedWrap())
    5873             :     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
    5874       74639 :   if (Flags == SCEV::FlagAnyWrap)
    5875             :     return SCEV::FlagAnyWrap;
    5876             : 
    5877       40787 :   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
    5878             : }
    5879             : 
    5880       82560 : bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
    5881             :   // Here we check that I is in the header of the innermost loop containing I,
    5882             :   // since we only deal with instructions in the loop header. The actual loop we
    5883             :   // need to check later will come from an add recurrence, but getting that
    5884             :   // requires computing the SCEV of the operands, which can be expensive. This
    5885             :   // check we can do cheaply to rule out some cases early.
    5886       82560 :   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
    5887      161132 :   if (InnermostContainingLoop == nullptr ||
    5888       80566 :       InnermostContainingLoop->getHeader() != I->getParent())
    5889             :     return false;
    5890             : 
    5891             :   // Only proceed if we can prove that I does not yield poison.
    5892       44619 :   if (!programUndefinedIfFullPoison(I))
    5893             :     return false;
    5894             : 
    5895             :   // At this point we know that if I is executed, then it does not wrap
    5896             :   // according to at least one of NSW or NUW. If I is not executed, then we do
    5897             :   // not know if the calculation that I represents would wrap. Multiple
    5898             :   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
    5899             :   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
    5900             :   // derived from other instructions that map to the same SCEV. We cannot make
    5901             :   // that guarantee for cases where I is not executed. So we need to find the
    5902             :   // loop that I is considered in relation to and prove that I is executed for
    5903             :   // every iteration of that loop. That implies that the value that I
    5904             :   // calculates does not wrap anywhere in the loop, so then we can apply the
    5905             :   // flags to the SCEV.
    5906             :   //
    5907             :   // We check isLoopInvariant to disambiguate in case we are adding recurrences
    5908             :   // from different loops, so that we know which loop to prove that I is
    5909             :   // executed in.
    5910       22910 :   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
    5911             :     // I could be an extractvalue from a call to an overflow intrinsic.
    5912             :     // TODO: We can do better here in some cases.
    5913       24214 :     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
    5914             :       return false;
    5915       12106 :     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
    5916             :     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
    5917             :       bool AllOtherOpsLoopInvariant = true;
    5918       26603 :       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
    5919             :            ++OtherOpIndex) {
    5920       10836 :         if (OtherOpIndex != OpIndex) {
    5921        5451 :           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
    5922        5451 :           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
    5923             :             AllOtherOpsLoopInvariant = false;
    5924             :             break;
    5925             :           }
    5926             :         }
    5927             :       }
    5928       10642 :       if (AllOtherOpsLoopInvariant &&
    5929        5191 :           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
    5930             :         return true;
    5931             :     }
    5932             :   }
    5933             :   return false;
    5934             : }
    5935             : 
    5936       41773 : bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
    5937             :   // If we know that \c I can never be poison period, then that's enough.
    5938       41773 :   if (isSCEVExprNeverPoison(I))
    5939             :     return true;
    5940             : 
    5941             :   // For an add recurrence specifically, we assume that infinite loops without
    5942             :   // side effects are undefined behavior, and then reason as follows:
    5943             :   //
    5944             :   // If the add recurrence is poison in any iteration, it is poison on all
    5945             :   // future iterations (since incrementing poison yields poison). If the result
    5946             :   // of the add recurrence is fed into the loop latch condition and the loop
    5947             :   // does not contain any throws or exiting blocks other than the latch, we now
    5948             :   // have the ability to "choose" whether the backedge is taken or not (by
    5949             :   // choosing a sufficiently evil value for the poison feeding into the branch)
    5950             :   // for every iteration including and after the one in which \p I first became
    5951             :   // poison.  There are two possibilities (let's call the iteration in which \p
    5952             :   // I first became poison as K):
    5953             :   //
    5954             :   //  1. In the set of iterations including and after K, the loop body executes
    5955             :   //     no side effects.  In this case executing the backege an infinte number
    5956             :   //     of times will yield undefined behavior.
    5957             :   //
    5958             :   //  2. In the set of iterations including and after K, the loop body executes
    5959             :   //     at least one side effect.  In this case, that specific instance of side
    5960             :   //     effect is control dependent on poison, which also yields undefined
    5961             :   //     behavior.
    5962             : 
    5963       40727 :   auto *ExitingBB = L->getExitingBlock();
    5964       40727 :   auto *LatchBB = L->getLoopLatch();
    5965       40727 :   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
    5966             :     return false;
    5967             : 
    5968             :   SmallPtrSet<const Instruction *, 16> Pushed;
    5969             :   SmallVector<const Instruction *, 8> PoisonStack;
    5970             : 
    5971             :   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
    5972             :   // things that are known to be fully poison under that assumption go on the
    5973             :   // PoisonStack.
    5974       26222 :   Pushed.insert(I);
    5975       26222 :   PoisonStack.push_back(I);
    5976             : 
    5977             :   bool LatchControlDependentOnPoison = false;
    5978       76024 :   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
    5979             :     const Instruction *Poison = PoisonStack.pop_back_val();
    5980             : 
    5981      105246 :     for (auto *PoisonUser : Poison->users()) {
    5982       75045 :       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
    5983       23761 :         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
    5984       23759 :           PoisonStack.push_back(cast<Instruction>(PoisonUser));
    5985             :       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
    5986             :         assert(BI->isConditional() && "Only possibility!");
    5987       19665 :         if (BI->getParent() == LatchBB) {
    5988             :           LatchControlDependentOnPoison = true;
    5989             :           break;
    5990             :         }
    5991             :       }
    5992             :     }
    5993             :   }
    5994             : 
    5995       45823 :   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
    5996             : }
    5997             : 
    5998             : ScalarEvolution::LoopProperties
    5999       20967 : ScalarEvolution::getLoopProperties(const Loop *L) {
    6000             :   using LoopProperties = ScalarEvolution::LoopProperties;
    6001             : 
    6002       20967 :   auto Itr = LoopPropertiesCache.find(L);
    6003       20967 :   if (Itr == LoopPropertiesCache.end()) {
    6004      228223 :     auto HasSideEffects = [](Instruction *I) {
    6005             :       if (auto *SI = dyn_cast<StoreInst>(I))
    6006       23166 :         return !SI->isSimple();
    6007             : 
    6008      205057 :       return I->mayHaveSideEffects();
    6009             :     };
    6010             : 
    6011             :     LoopProperties LP = {/* HasNoAbnormalExits */ true,
    6012             :                          /*HasNoSideEffects*/ true};
    6013             : 
    6014       55209 :     for (auto *BB : L->getBlocks())
    6015      245171 :       for (auto &I : *BB) {
    6016      228223 :         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
    6017             :           LP.HasNoAbnormalExits = false;
    6018      228223 :         if (HasSideEffects(&I))
    6019             :           LP.HasNoSideEffects = false;
    6020      228223 :         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
    6021             :           break; // We're already as pessimistic as we can get.
    6022             :       }
    6023             : 
    6024       10671 :     auto InsertPair = LoopPropertiesCache.insert({L, LP});
    6025             :     assert(InsertPair.second && "We just checked!");
    6026       10671 :     Itr = InsertPair.first;
    6027             :   }
    6028             : 
    6029       20967 :   return Itr->second;
    6030             : }
    6031             : 
    6032      601070 : const SCEV *ScalarEvolution::createSCEV(Value *V) {
    6033      601070 :   if (!isSCEVable(V->getType()))
    6034           0 :     return getUnknown(V);
    6035             : 
    6036             :   if (Instruction *I = dyn_cast<Instruction>(V)) {
    6037             :     // Don't attempt to analyze instructions in blocks that aren't
    6038             :     // reachable. Such instructions don't matter, and they aren't required
    6039             :     // to obey basic rules for definitions dominating uses which this
    6040             :     // analysis depends on.
    6041      312732 :     if (!DT.isReachableFromEntry(I->getParent()))
    6042         324 :       return getUnknown(V);
    6043             :   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
    6044      115927 :     return getConstant(CI);
    6045      172411 :   else if (isa<ConstantPointerNull>(V))
    6046        1522 :     return getZero(V->getType());
    6047             :   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
    6048           0 :     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
    6049      171650 :   else if (!isa<ConstantExpr>(V))
    6050       83189 :     return getUnknown(V);
    6051             : 
    6052             :   Operator *U = cast<Operator>(V);
    6053      400869 :   if (auto BO = MatchBinaryOp(U, DT)) {
    6054       74455 :     switch (BO->Opcode) {
    6055             :     case Instruction::Add: {
    6056             :       // The simple thing to do would be to just call getSCEV on both operands
    6057             :       // and call getAddExpr with the result. However if we're looking at a
    6058             :       // bunch of things all added together, this can be quite inefficient,
    6059             :       // because it leads to N-1 getAddExpr calls for N ultimate operands.
    6060             :       // Instead, gather up all the operands and make a single getAddExpr call.
    6061             :       // LLVM IR canonical form means we need only traverse the left operands.
    6062             :       SmallVector<const SCEV *, 4> AddOps;
    6063             :       do {
    6064       64619 :         if (BO->Op) {
    6065       64532 :           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
    6066        4581 :             AddOps.push_back(OpSCEV);
    6067        4581 :             break;
    6068             :           }
    6069             : 
    6070             :           // If a NUW or NSW flag can be applied to the SCEV for this
    6071             :           // addition, then compute the SCEV for this addition by itself
    6072             :           // with a separate call to getAddExpr. We need to do that
    6073             :           // instead of pushing the operands of the addition onto AddOps,
    6074             :           // since the flags are only known to apply to this particular
    6075             :           // addition - they may not apply to other additions that can be
    6076             :           // formed with operands from AddOps.
    6077       59951 :           const SCEV *RHS = getSCEV(BO->RHS);
    6078       59951 :           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
    6079       59951 :           if (Flags != SCEV::FlagAnyWrap) {
    6080        3467 :             const SCEV *LHS = getSCEV(BO->LHS);
    6081        3467 :             if (BO->Opcode == Instruction::Sub)
    6082           2 :               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
    6083             :             else
    6084        3465 :               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
    6085             :             break;
    6086             :           }
    6087             :         }
    6088             : 
    6089       56571 :         if (BO->Opcode == Instruction::Sub)
    6090         246 :           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
    6091             :         else
    6092       56325 :           AddOps.push_back(getSCEV(BO->RHS));
    6093             : 
    6094       56571 :         auto NewBO = MatchBinaryOp(BO->LHS, DT);
    6095       56571 :         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
    6096             :                        NewBO->Opcode != Instruction::Sub)) {
    6097       42727 :           AddOps.push_back(getSCEV(BO->LHS));
    6098             :           break;
    6099             :         }
    6100             :         BO = NewBO;
    6101             :       } while (true);
    6102             : 
    6103       50775 :       return getAddExpr(AddOps);
    6104             :     }
    6105             : 
    6106             :     case Instruction::Mul: {
    6107             :       SmallVector<const SCEV *, 4> MulOps;
    6108             :       do {
    6109        7069 :         if (BO->Op) {
    6110        7065 :           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
    6111         404 :             MulOps.push_back(OpSCEV);
    6112         404 :             break;
    6113             :           }
    6114             : 
    6115        6661 :           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
    6116        6661 :           if (Flags != SCEV::FlagAnyWrap) {
    6117         131 :             MulOps.push_back(
    6118         262 :                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
    6119         131 :             break;
    6120             :           }
    6121             :         }
    6122             : 
    6123        6534 :         MulOps.push_back(getSCEV(BO->RHS));
    6124        6534 :         auto NewBO = MatchBinaryOp(BO->LHS, DT);
    6125        6534 :         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
    6126        5764 :           MulOps.push_back(getSCEV(BO->LHS));
    6127             :           break;
    6128             :         }
    6129             :         BO = NewBO;
    6130             :       } while (true);
    6131             : 
    6132        6299 :       return getMulExpr(MulOps);
    6133             :     }
    6134             :     case Instruction::UDiv:
    6135        3203 :       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
    6136             :     case Instruction::URem:
    6137         481 :       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
    6138        5900 :     case Instruction::Sub: {
    6139             :       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    6140        5900 :       if (BO->Op)
    6141        5868 :         Flags = getNoWrapFlagsFromUB(BO->Op);
    6142        5900 :       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
    6143             :     }
    6144             :     case Instruction::And:
    6145             :       // For an expression like x&255 that merely masks off the high bits,
    6146             :       // use zext(trunc(x)) as the SCEV expression.
    6147        2390 :       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
    6148        1946 :         if (CI->isZero())
    6149        1887 :           return getSCEV(BO->RHS);
    6150        1944 :         if (CI->isMinusOne())
    6151           0 :           return getSCEV(BO->LHS);
    6152             :         const APInt &A = CI->getValue();
    6153             : 
    6154             :         // Instcombine's ShrinkDemandedConstant may strip bits out of
    6155             :         // constants, obscuring what would otherwise be a low-bits mask.
    6156             :         // Use computeKnownBits to compute what ShrinkDemandedConstant
    6157             :         // knew about to reconstruct a low-bits mask value.
    6158        1944 :         unsigned LZ = A.countLeadingZeros();
    6159        1944 :         unsigned TZ = A.countTrailingZeros();
    6160             :         unsigned BitWidth = A.getBitWidth();
    6161        2005 :         KnownBits Known(BitWidth);
    6162        3888 :         computeKnownBits(BO->LHS, Known, getDataLayout(),
    6163        1944 :                          0, &AC, nullptr, &DT);
    6164             : 
    6165             :         APInt EffectiveMask =
    6166        3888 :             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
    6167       15552 :         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
    6168        3766 :           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
    6169        1883 :           const SCEV *LHS = getSCEV(BO->LHS);
    6170             :           const SCEV *ShiftedLHS = nullptr;
    6171             :           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
    6172          27 :             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
    6173             :               // For an expression like (x * 8) & 8, simplify the multiply.
    6174          26 :               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
    6175          26 :               unsigned GCD = std::min(MulZeros, TZ);
    6176          26 :               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
    6177             :               SmallVector<const SCEV*, 4> MulOps;
    6178          52 :               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
    6179          52 :               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
    6180          52 :               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
    6181          26 :               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
    6182             :             }
    6183             :           }
    6184          26 :           if (!ShiftedLHS)
    6185        1857 :             ShiftedLHS = getUDivExpr(LHS, MulCount);
    6186        3766 :           return getMulExpr(
    6187             :               getZeroExtendExpr(
    6188             :                   getTruncateExpr(ShiftedLHS,
    6189        3766 :                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
    6190        1883 :                   BO->LHS->getType()),
    6191        1883 :               MulCount);
    6192             :         }
    6193             :       }
    6194             :       break;
    6195             : 
    6196             :     case Instruction::Or:
    6197             :       // If the RHS of the Or is a constant, we may have something like:
    6198             :       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
    6199             :       // optimizations will transparently handle this case.
    6200             :       //
    6201             :       // In order for this transformation to be safe, the LHS must be of the
    6202             :       // form X*(2^n) and the Or constant must be less than 2^n.
    6203        1138 :       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
    6204         770 :         const SCEV *LHS = getSCEV(BO->LHS);
    6205             :         const APInt &CIVal = CI->getValue();
    6206        1540 :         if (GetMinTrailingZeros(LHS) >=
    6207         770 :             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
    6208             :           // Build a plain add SCEV.
    6209         728 :           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
    6210             :           // If the LHS of the add was an addrec and it has no-wrap flags,
    6211             :           // transfer the no-wrap flags, since an or won't introduce a wrap.
    6212             :           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
    6213             :             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
    6214         493 :             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
    6215             :                 OldAR->getNoWrapFlags());
    6216             :           }
    6217             :           return S;
    6218             :         }
    6219             :       }
    6220             :       break;
    6221             : 
    6222             :     case Instruction::Xor:
    6223         316 :       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
    6224             :         // If the RHS of xor is -1, then this is a not operation.
    6225         105 :         if (CI->isMinusOne())
    6226          59 :           return getNotSCEV(getSCEV(BO->LHS));
    6227             : 
    6228             :         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
    6229             :         // This is a variant of the check for xor with -1, and it handles
    6230             :         // the case where instcombine has trimmed non-demanded bits out
    6231             :         // of an xor with -1.
    6232          46 :         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
    6233             :           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
    6234          10 :             if (LBO->getOpcode() == Instruction::And &&
    6235             :                 LCI->getValue() == CI->getValue())
    6236             :               if (const SCEVZeroExtendExpr *Z =
    6237           4 :                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
    6238           2 :                 Type *UTy = BO->LHS->getType();
    6239           2 :                 const SCEV *Z0 = Z->getOperand();
    6240           2 :                 Type *Z0Ty = Z0->getType();
    6241           2 :                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
    6242             : 
    6243             :                 // If C is a low-bits mask, the zero extend is serving to
    6244             :                 // mask off the high bits. Complement the operand and
    6245             :                 // re-apply the zext.
    6246           2 :                 if (CI->getValue().isMask(Z0TySize))
    6247           4 :                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
    6248             : 
    6249             :                 // If C is a single bit, it may be in the sign-bit position
    6250             :                 // before the zero-extend. In this case, represent the xor
    6251             :                 // using an add, which is equivalent, and re-apply the zext.
    6252           0 :                 APInt Trunc = CI->getValue().trunc(Z0TySize);
    6253           0 :                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
    6254             :                     Trunc.isSignMask())
    6255           0 :                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
    6256           0 :                                            UTy);
    6257             :               }
    6258             :       }
    6259             :       break;
    6260             : 
    6261             :     case Instruction::Shl:
    6262             :       // Turn shift left of a constant amount into a multiply.
    6263        2522 :       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
    6264             :         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
    6265             : 
    6266             :         // If the shift count is not less than the bitwidth, the result of
    6267             :         // the shift is undefined. Don't try to analyze it, because the
    6268             :         // resolution chosen here may differ from the resolution chosen in
    6269             :         // other parts of the compiler.
    6270        4340 :         if (SA->getValue().uge(BitWidth))
    6271             :           break;
    6272             : 
    6273             :         // It is currently not resolved how to interpret NSW for left
    6274             :         // shift by BitWidth - 1, so we avoid applying flags in that
    6275             :         // case. Remove this check (or this comment) once the situation
    6276             :         // is resolved. See
    6277             :         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
    6278             :         // and http://reviews.llvm.org/D8890 .
    6279             :         auto Flags = SCEV::FlagAnyWrap;
    6280        2166 :         if (BO->Op && SA->getValue().ult(BitWidth - 1))
    6281        2165 :           Flags = getNoWrapFlagsFromUB(BO->Op);
    6282             : 
    6283        2166 :         Constant *X = ConstantInt::get(
    6284        6498 :             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
    6285        2166 :         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
    6286             :       }
    6287             :       break;
    6288             : 
    6289             :     case Instruction::AShr: {
    6290             :       // AShr X, C, where C is a constant.
    6291        1118 :       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
    6292             :       if (!CI)
    6293             :         break;
    6294             : 
    6295        1114 :       Type *OuterTy = BO->LHS->getType();
    6296        1114 :       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
    6297             :       // If the shift count is not less than the bitwidth, the result of
    6298             :       // the shift is undefined. Don't try to analyze it, because the
    6299             :       // resolution chosen here may differ from the resolution chosen in
    6300             :       // other parts of the compiler.
    6301        1114 :       if (CI->getValue().uge(BitWidth))
    6302             :         break;
    6303             : 
    6304        1110 :       if (CI->isZero())
    6305           1 :         return getSCEV(BO->LHS); // shift by zero --> noop
    6306             : 
    6307             :       uint64_t AShrAmt = CI->getZExtValue();
    6308        2218 :       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
    6309             : 
    6310        1109 :       Operator *L = dyn_cast<Operator>(BO->LHS);
    6311        1046 :       if (L && L->getOpcode() == Instruction::Shl) {
    6312             :         // X = Shl A, n
    6313             :         // Y = AShr X, m
    6314             :         // Both n and m are constant.
    6315             : 
    6316         530 :         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
    6317         265 :         if (L->getOperand(1) == BO->RHS)
    6318             :           // For a two-shift sext-inreg, i.e. n = m,
    6319             :           // use sext(trunc(x)) as the SCEV expression.
    6320         233 :           return getSignExtendExpr(
    6321         233 :               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
    6322             : 
    6323             :         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
    6324          32 :         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
    6325             :           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
    6326          32 :           if (ShlAmt > AShrAmt) {
    6327             :             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
    6328             :             // expression. We already checked that ShlAmt < BitWidth, so
    6329             :             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
    6330             :             // ShlAmt - AShrAmt < Amt.
    6331             :             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
    6332           2 :                                             ShlAmt - AShrAmt);
    6333           2 :             return getSignExtendExpr(
    6334             :                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
    6335           2 :                 getConstant(Mul)), OuterTy);
    6336             :           }
    6337             :         }
    6338             :       }
    6339             :       break;
    6340             :     }
    6341             :     }
    6342             :   }
    6343             : 
    6344      329135 :   switch (U->getOpcode()) {
    6345        2901 :   case Instruction::Trunc:
    6346        5802 :     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
    6347             : 
    6348        2901 :   case Instruction::ZExt:
    6349        5802 :     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
    6350             : 
    6351        9932 :   case Instruction::SExt:
    6352       19864 :     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
    6353             :       // The NSW flag of a subtract does not always survive the conversion to
    6354             :       // A + (-1)*B.  By pushing sign extension onto its operands we are much
    6355             :       // more likely to preserve NSW and allow later AddRec optimisations.
    6356             :       //
    6357             :       // NOTE: This is effectively duplicating this logic from getSignExtend:
    6358             :       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
    6359             :       // but by that point the NSW information has potentially been lost.
    6360         709 :       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
    6361          11 :         Type *Ty = U->getType();
    6362          11 :         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
    6363          11 :         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
    6364          11 :         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
    6365             :       }
    6366          11 :     }
    6367       19842 :     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
    6368             : 
    6369       10845 :   case Instruction::BitCast:
    6370             :     // BitCasts are no-op casts so we just eliminate the cast.
    6371       21690 :     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
    6372       10668 :       return getSCEV(U->getOperand(0));
    6373             :     break;
    6374             : 
    6375             :   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
    6376             :   // lead to pointer expressions which cannot safely be expanded to GEPs,
    6377             :   // because ScalarEvolution doesn't respect the GEP aliasing rules when
    6378             :   // simplifying integer expressions.
    6379             : 
    6380      170225 :   case Instruction::GetElementPtr:
    6381      170225 :     return createNodeForGEP(cast<GEPOperator>(U));
    6382             : 
    6383       54883 :   case Instruction::PHI:
    6384       54883 :     return createNodeForPHI(cast<PHINode>(U));
    6385             : 
    6386       13776 :   case Instruction::Select:
    6387             :     // U can also be a select constant expr, which let fall through.  Since
    6388             :     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
    6389             :     // constant expressions cannot have instructions as operands, we'd have
    6390             :     // returned getUnknown for a select constant expressions anyway.
    6391       13776 :     if (isa<Instruction>(U))
    6392       13774 :       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
    6393       13774 :                                       U->getOperand(1), U->getOperand(2));
    6394             :     break;
    6395             : 
    6396       10889 :   case Instruction::Call:
    6397             :   case Instruction::Invoke:
    6398       10889 :     if (Value *RV = CallSite(U).getReturnedArgOperand())
    6399           7 :       return getSCEV(RV);
    6400             :     break;
    6401             :   }
    6402             : 
    6403       63844 :   return getUnknown(V);
    6404             : }
    6405             : 
    6406             : //===----------------------------------------------------------------------===//
    6407             : //                   Iteration Count Computation Code
    6408             : //
    6409             : 
    6410       12761 : static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
    6411       12761 :   if (!ExitCount)
    6412             :     return 0;
    6413             : 
    6414        5440 :   ConstantInt *ExitConst = ExitCount->getValue();
    6415             : 
    6416             :   // Guard against huge trip counts.
    6417        5440 :   if (ExitConst->getValue().getActiveBits() > 32)
    6418             :     return 0;
    6419             : 
    6420             :   // In case of integer overflow, this returns 0, which is correct.
    6421        4162 :   return ((unsigned)ExitConst->getZExtValue()) + 1;
    6422             : }
    6423             : 
    6424        2027 : unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
    6425        2027 :   if (BasicBlock *ExitingBB = L->getExitingBlock())
    6426        1963 :     return getSmallConstantTripCount(L, ExitingBB);
    6427             : 
    6428             :   // No trip count information for multiple exits.
    6429             :   return 0;
    6430             : }
    6431             : 
    6432        7865 : unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
    6433             :                                                     BasicBlock *ExitingBlock) {
    6434             :   assert(ExitingBlock && "Must pass a non-null exiting block!");
    6435             :   assert(L->isLoopExiting(ExitingBlock) &&
    6436             :          "Exiting block must actually branch out of the loop!");
    6437             :   const SCEVConstant *ExitCount =
    6438        7865 :       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
    6439        7865 :   return getConstantTripCount(ExitCount);
    6440             : }
    6441             : 
    6442        4896 : unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
    6443             :   const auto *MaxExitCount =
    6444        4896 :       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
    6445        4896 :   return getConstantTripCount(MaxExitCount);
    6446             : }
    6447             : 
    6448         252 : unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
    6449         252 :   if (BasicBlock *ExitingBB = L->getExitingBlock())
    6450         242 :     return getSmallConstantTripMultiple(L, ExitingBB);
    6451             : 
    6452             :   // No trip multiple information for multiple exits.
    6453             :   return 0;
    6454             : }
    6455             : 
    6456             : /// Returns the largest constant divisor of the trip count of this loop as a
    6457             : /// normal unsigned value, if possible. This means that the actual trip count is
    6458             : /// always a multiple of the returned value (don't forget the trip count could
    6459             : /// very well be zero as well!).
    6460             : ///
    6461             : /// Returns 1 if the trip count is unknown or not guaranteed to be the
    6462             : /// multiple of a constant (which is also the case if the trip count is simply
    6463             : /// constant, use getSmallConstantTripCount for that case), Will also return 1
    6464             : /// if the trip count is very large (>= 2^32).
    6465             : ///
    6466             : /// As explained in the comments for getSmallConstantTripCount, this assumes
    6467             : /// that control exits the loop via ExitingBlock.
    6468             : unsigned
    6469        6139 : ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
    6470             :                                               BasicBlock *ExitingBlock) {
    6471             :   assert(ExitingBlock && "Must pass a non-null exiting block!");
    6472             :   assert(L->isLoopExiting(ExitingBlock) &&
    6473             :          "Exiting block must actually branch out of the loop!");
    6474        6139 :   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
    6475        6139 :   if (ExitCount == getCouldNotCompute())
    6476             :     return 1;
    6477             : 
    6478             :   // Get the trip count from the BE count by adding 1.
    6479        7558 :   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
    6480             : 
    6481             :   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
    6482             :   if (!TC)
    6483             :     // Attempt to factor more general cases. Returns the greatest power of
    6484             :     // two divisor. If overflow happens, the trip count expression is still
    6485             :     // divisible by the greatest power of 2 divisor returned.
    6486        3294 :     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
    6487             : 
    6488        2132 :   ConstantInt *Result = TC->getValue();
    6489             : 
    6490             :   // Guard against huge trip counts (this requires checking
    6491             :   // for zero to handle the case where the trip count == -1 and the
    6492             :   // addition wraps).
    6493        4264 :   if (!Result || Result->getValue().getActiveBits() > 32 ||
    6494             :       Result->getValue().getActiveBits() == 0)
    6495             :     return 1;
    6496             : 
    6497        2130 :   return (unsigned)Result->getZExtValue();
    6498             : }
    6499             : 
    6500             : /// Get the expression for the number of loop iterations for which this loop is
    6501             : /// guaranteed not to exit via ExitingBlock. Otherwise return
    6502             : /// SCEVCouldNotCompute.
    6503       14880 : const SCEV *ScalarEvolution::getExitCount(const Loop *L,
    6504             :                                           BasicBlock *ExitingBlock) {
    6505       14880 :   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
    6506             : }
    6507             : 
    6508             : const SCEV *
    6509        3609 : ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
    6510             :                                                  SCEVUnionPredicate &Preds) {
    6511        3609 :   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
    6512             : }
    6513             : 
    6514       37983 : const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
    6515       37983 :   return getBackedgeTakenInfo(L).getExact(L, this);
    6516             : }
    6517             : 
    6518             : /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
    6519             : /// known never to be less than the actual backedge taken count.
    6520      248505 : const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
    6521      248505 :   return getBackedgeTakenInfo(L).getMax(this);
    6522             : }
    6523             : 
    6524        4673 : bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
    6525        4673 :   return getBackedgeTakenInfo(L).isMaxOrZero(this);
    6526             : }
    6527             : 
    6528             : /// Push PHI nodes in the header of the given loop onto the given Worklist.
    6529             : static void
    6530       23923 : PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
    6531             :   BasicBlock *Header = L->getHeader();
    6532             : 
    6533             :   // Push all Loop-header PHIs onto the Worklist stack.
    6534       23923 :   for (PHINode &PN : Header->phis())
    6535       32470 :     Worklist.push_back(&PN);
    6536       23923 : }
    6537             : 
    6538             : const ScalarEvolution::BackedgeTakenInfo &
    6539        3609 : ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
    6540        3609 :   auto &BTI = getBackedgeTakenInfo(L);
    6541        3609 :   if (BTI.hasFullInfo())
    6542             :     return BTI;
    6543             : 
    6544        1728 :   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
    6545             : 
    6546         576 :   if (!Pair.second)
    6547          12 :     return Pair.first->second;
    6548             : 
    6549             :   BackedgeTakenInfo Result =
    6550         564 :       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
    6551             : 
    6552        1128 :   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
    6553             : }
    6554             : 
    6555             : const ScalarEvolution::BackedgeTakenInfo &
    6556      325621 : ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
    6557             :   // Initially insert an invalid entry for this loop. If the insertion
    6558             :   // succeeds, proceed to actually compute a backedge-taken count and
    6559             :   // update the value. The temporary CouldNotCompute value tells SCEV
    6560             :   // code elsewhere that it shouldn't attempt to request a new
    6561             :   // backedge-taken count, which could result in infinite recursion.
    6562             :   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
    6563      976863 :       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
    6564      325621 :   if (!Pair.second)
    6565      304448 :     return Pair.first->second;
    6566             : 
    6567             :   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
    6568             :   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
    6569             :   // must be cleared in this scope.
    6570       21173 :   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
    6571             : 
    6572             :   // In product build, there are no usage of statistic.
    6573             :   (void)NumTripCountsComputed;
    6574             :   (void)NumTripCountsNotComputed;
    6575             : #if LLVM_ENABLE_STATS || !defined(NDEBUG)
    6576             :   const SCEV *BEExact = Result.getExact(L, this);
    6577             :   if (BEExact != getCouldNotCompute()) {
    6578             :     assert(isLoopInvariant(BEExact, L) &&
    6579             :            isLoopInvariant(Result.getMax(this), L) &&
    6580             :            "Computed backedge-taken count isn't loop invariant for loop!");
    6581             :     ++NumTripCountsComputed;
    6582             :   }
    6583             :   else if (Result.getMax(this) == getCouldNotCompute() &&
    6584             :            isa<PHINode>(L->getHeader()->begin())) {
    6585             :     // Only count loops that have phi nodes as not being computable.
    6586             :     ++NumTripCountsNotComputed;
    6587             :   }
    6588             : #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
    6589             : 
    6590             :   // Now that we know more about the trip count for this loop, forget any
    6591             :   // existing SCEV values for PHI nodes in this loop since they are only
    6592             :   // conservative estimates made without the benefit of trip count
    6593             :   // information. This is similar to the code in forgetLoop, except that
    6594             :   // it handles SCEVUnknown PHI nodes specially.
    6595             :   if (Result.hasAnyInfo()) {
    6596             :     SmallVector<Instruction *, 16> Worklist;
    6597       16489 :     PushLoopPHIs(L, Worklist);
    6598             : 
    6599             :     SmallPtrSet<Instruction *, 8> Discovered;
    6600      618511 :     while (!Worklist.empty()) {
    6601             :       Instruction *I = Worklist.pop_back_val();
    6602             : 
    6603             :       ValueExprMapType::iterator It =
    6604      301011 :         ValueExprMap.find_as(static_cast<Value *>(I));
    6605      301011 :       if (It != ValueExprMap.end()) {
    6606       39473 :         const SCEV *Old = It->second;
    6607             : 
    6608             :         // SCEVUnknown for a PHI either means that it has an unrecognized
    6609             :         // structure, or it's a PHI that's in the progress of being computed
    6610             :         // by createNodeForPHI.  In the former case, additional loop trip
    6611             :         // count information isn't going to change anything. In the later
    6612             :         // case, createNodeForPHI will perform the necessary updates on its
    6613             :         // own when it gets to that point.
    6614       58491 :         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
    6615       37506 :           eraseValueFromMap(It->first);
    6616       37506 :           forgetMemoizedResults(Old);
    6617             :         }
    6618       39473 :         if (PHINode *PN = dyn_cast<PHINode>(I))
    6619       19018 :           ConstantEvolutionLoopExitValue.erase(PN);
    6620             :       }
    6621             : 
    6622             :       // Since we don't need to invalidate anything for correctness and we're
    6623             :       // only invalidating to make SCEV's results more precise, we get to stop
    6624             :       // early to avoid invalidating too much.  This is especially important in
    6625             :       // cases like:
    6626             :       //
    6627             :       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
    6628             :       // loop0:
    6629             :       //   %pn0 = phi
    6630             :       //   ...
    6631             :       // loop1:
    6632             :       //   %pn1 = phi
    6633             :       //   ...
    6634             :       //
    6635             :       // where both loop0 and loop1's backedge taken count uses the SCEV
    6636             :       // expression for %v.  If we don't have the early stop below then in cases
    6637             :       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
    6638             :       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
    6639             :       // count for loop1, effectively nullifying SCEV's trip count cache.
    6640      685455 :       for (auto *U : I->users())
    6641      384444 :         if (auto *I = dyn_cast<Instruction>(U)) {
    6642      384444 :           auto *LoopForUser = LI.getLoopFor(I->getParent());
    6643     1130843 :           if (LoopForUser && L->contains(LoopForUser) &&
    6644      482437 :               Discovered.insert(I).second)
    6645      278044 :             Worklist.push_back(I);
    6646             :         }
    6647             :     }
    6648             :   }
    6649             : 
    6650             :   // Re-lookup the insert position, since the call to
    6651             :   // computeBackedgeTakenCount above could result in a
    6652             :   // recusive call to getBackedgeTakenInfo (on a different
    6653             :   // loop), which would invalidate the iterator computed
    6654             :   // earlier.
    6655       42346 :   return BackedgeTakenCounts.find(L)->second = std::move(Result);
    6656             : }
    6657             : 
    6658        5106 : void ScalarEvolution::forgetLoop(const Loop *L) {
    6659             :   // Drop any stored trip count value.
    6660             :   auto RemoveLoopFromBackedgeMap =
    6661       14868 :       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
    6662       14868 :         auto BTCPos = Map.find(L);
    6663       14868 :         if (BTCPos != Map.end()) {
    6664        1877 :           BTCPos->second.clear();
    6665             :           Map.erase(BTCPos);
    6666             :         }
    6667       14868 :       };
    6668             : 
    6669             :   SmallVector<const Loop *, 16> LoopWorklist(1, L);
    6670             :   SmallVector<Instruction *, 32> Worklist;
    6671             :   SmallPtrSet<Instruction *, 16> Visited;
    6672             : 
    6673             :   // Iterate over all the loops and sub-loops to drop SCEV information.
    6674       19974 :   while (!LoopWorklist.empty()) {
    6675        7434 :     auto *CurrL = LoopWorklist.pop_back_val();
    6676             : 
    6677        7434 :     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
    6678        7434 :     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
    6679             : 
    6680             :     // Drop information about predicated SCEV rewrites for this loop.
    6681        7509 :     for (auto I = PredicatedSCEVRewrites.begin();
    6682        7509 :          I != PredicatedSCEVRewrites.end();) {
    6683             :       std::pair<const SCEV *, const Loop *> Entry = I->first;
    6684          75 :       if (Entry.second == CurrL)
    6685             :         PredicatedSCEVRewrites.erase(I++);
    6686             :       else
    6687           7 :         ++I;
    6688             :     }
    6689             : 
    6690        7434 :     auto LoopUsersItr = LoopUsers.find(CurrL);
    6691        7434 :     if (LoopUsersItr != LoopUsers.end()) {
    6692       22221 :       for (auto *S : LoopUsersItr->second)
    6693       10246 :         forgetMemoizedResults(S);
    6694             :       LoopUsers.erase(LoopUsersItr);
    6695             :     }
    6696             : 
    6697             :     // Drop information about expressions based on loop-header PHIs.
    6698        7434 :     PushLoopPHIs(CurrL, Worklist);
    6699             : 
    6700      157714 :     while (!Worklist.empty()) {
    6701             :       Instruction *I = Worklist.pop_back_val();
    6702      150280 :       if (!Visited.insert(I).second)
    6703       27314 :         continue;
    6704             : 
    6705             :       ValueExprMapType::iterator It =
    6706      122966 :           ValueExprMap.find_as(static_cast<Value *>(I));
    6707      122966 :       if (It != ValueExprMap.end()) {
    6708        4678 :         eraseValueFromMap(It->first);
    6709        4678 :         forgetMemoizedResults(It->second);
    6710        4678 :         if (PHINode *PN = dyn_cast<PHINode>(I))
    6711        1617 :           ConstantEvolutionLoopExitValue.erase(PN);
    6712             :       }
    6713             : 
    6714      122966 :       PushDefUseChildren(I, Worklist);
    6715             :     }
    6716             : 
    6717        7434 :     LoopPropertiesCache.erase(CurrL);
    6718             :     // Forget all contained loops too, to avoid dangling entries in the
    6719             :     // ValuesAtScopes map.
    6720       14868 :     LoopWorklist.append(CurrL->begin(), CurrL->end());
    6721             :   }
    6722        5106 : }
    6723             : 
    6724        3660 : void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
    6725        4321 :   while (Loop *Parent = L->getParentLoop())
    6726             :     L = Parent;
    6727        3660 :   forgetLoop(L);
    6728        3660 : }
    6729             : 
    6730       11261 : void ScalarEvolution::forgetValue(Value *V) {
    6731       11261 :   Instruction *I = dyn_cast<Instruction>(V);
    6732       11261 :   if (!I) return;
    6733             : 
    6734             :   // Drop information about expressions based on loop-header PHIs.
    6735             :   SmallVector<Instruction *, 16> Worklist;
    6736       11261 :   Worklist.push_back(I);
    6737             : 
    6738             :   SmallPtrSet<Instruction *, 8> Visited;
    6739      139685 :   while (!Worklist.empty()) {
    6740      128424 :     I = Worklist.pop_back_val();
    6741      128424 :     if (!Visited.insert(I).second)
    6742       17706 :       continue;
    6743             : 
    6744             :     ValueExprMapType::iterator It =
    6745      110718 :       ValueExprMap.find_as(static_cast<Value *>(I));
    6746      110718 :     if (It != ValueExprMap.end()) {
    6747       15247 :       eraseValueFromMap(It->first);
    6748       15247 :       forgetMemoizedResults(It->second);
    6749       30494 :       if (PHINode *PN = dyn_cast<PHINode>(I))
    6750        3565 :         ConstantEvolutionLoopExitValue.erase(PN);
    6751             :     }
    6752             : 
    6753      110718 :     PushDefUseChildren(I, Worklist);
    6754             :   }
    6755             : }
    6756             : 
    6757             : /// Get the exact loop backedge taken count considering all loop exits. A
    6758             : /// computable result can only be returned for loops with all exiting blocks
    6759             : /// dominating the latch. howFarToZero assumes that the limit of each loop test
    6760             : /// is never skipped. This is a valid assumption as long as the loop exits via
    6761             : /// that test. For precise results, it is the caller's responsibility to specify
    6762             : /// the relevant loop exiting block using getExact(ExitingBlock, SE).
    6763             : const SCEV *
    6764       41592 : ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
    6765             :                                              SCEVUnionPredicate *Preds) const {
    6766             :   // If any exits were not computable, the loop is not computable.
    6767       41592 :   if (!isComplete() || ExitNotTaken.empty())
    6768       11695 :     return SE->getCouldNotCompute();
    6769             : 
    6770       29897 :   const BasicBlock *Latch = L->getLoopLatch();
    6771             :   // All exiting blocks we have collected must dominate the only backedge.
    6772       29897 :   if (!Latch)
    6773           0 :     return SE->getCouldNotCompute();
    6774             : 
    6775             :   // All exiting blocks we have gathered dominate loop's latch, so exact trip
    6776             :   // count is simply a minimum out of all these calculated exit counts.
    6777             :   SmallVector<const SCEV *, 2> Ops;
    6778       90333 :   for (auto &ENT : ExitNotTaken) {
    6779       30218 :     const SCEV *BECount = ENT.ExactNotTaken;
    6780             :     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
    6781             :     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
    6782             :            "We should only have known counts for exiting blocks that dominate "
    6783             :            "latch!");
    6784             : 
    6785       30218 :     Ops.push_back(BECount);
    6786             : 
    6787       30218 :     if (Preds && !ENT.hasAlwaysTruePredicate())
    6788          22 :       Preds->add(ENT.Predicate.get());
    6789             : 
    6790             :     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
    6791             :            "Predicate should be always true!");
    6792             :   }
    6793             : 
    6794       29897 :   return SE->getUMinFromMismatchedTypes(Ops);
    6795             : }
    6796             : 
    6797             : /// Get the exact not taken count for this loop exit.
    6798             : const SCEV *
    6799       30851 : ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
    6800             :                                              ScalarEvolution *SE) const {
    6801       34227 :   for (auto &ENT : ExitNotTaken)
    6802       25189 :     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
    6803       23501 :       return ENT.ExactNotTaken;
    6804             : 
    6805        7350 :   return SE->getCouldNotCompute();
    6806             : }
    6807             : 
    6808             : /// getMax - Get the max backedge taken count for the loop.
    6809             : const SCEV *
    6810      248505 : ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
    6811             :   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
    6812             :     return !ENT.hasAlwaysTruePredicate();
    6813             :   };
    6814             : 
    6815      497010 :   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
    6816       33389 :     return SE->getCouldNotCompute();
    6817             : 
    6818             :   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
    6819             :          "No point in having a non-constant max backedge taken count!");
    6820             :   return getMax();
    6821             : }
    6822             : 
    6823        4673 : bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
    6824             :   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
    6825             :     return !ENT.hasAlwaysTruePredicate();
    6826             :   };
    6827        4691 :   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
    6828             : }
    6829             : 
    6830      127298 : bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
    6831             :                                                     ScalarEvolution *SE) const {
    6832      191936 :   if (getMax() && getMax() != SE->getCouldNotCompute() &&
    6833       64638 :       SE->hasOperand(getMax(), S))
    6834             :     return true;
    6835             : 
    6836      251340 :   for (auto &ENT : ExitNotTaken)
    6837      124192 :     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
    6838       62096 :         SE->hasOperand(ENT.ExactNotTaken, S))
    6839             :       return true;
    6840             : 
    6841             :   return false;
    6842             : }
    6843             : 
    6844       49599 : ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
    6845       49599 :     : ExactNotTaken(E), MaxNotTaken(E) {
    6846             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6847             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6848             :          "No point in having a non-constant max backedge taken count!");
    6849       49599 : }
    6850             : 
    6851        9965 : ScalarEvolution::ExitLimit::ExitLimit(
    6852             :     const SCEV *E, const SCEV *M, bool MaxOrZero,
    6853        9965 :     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
    6854        9965 :     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
    6855             :   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
    6856             :           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
    6857             :          "Exact is not allowed to be less precise than Max");
    6858             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6859             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6860             :          "No point in having a non-constant max backedge taken count!");
    6861       30337 :   for (auto *PredSet : PredSetList)
    6862       10186 :     for (auto *P : *PredSet)
    6863             :       addPredicate(P);
    6864        9965 : }
    6865             : 
    6866        9666 : ScalarEvolution::ExitLimit::ExitLimit(
    6867             :     const SCEV *E, const SCEV *M, bool MaxOrZero,
    6868        9666 :     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
    6869       19332 :     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
    6870             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6871             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6872             :          "No point in having a non-constant max backedge taken count!");
    6873        9666 : }
    6874             : 
    6875          39 : ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
    6876          39 :                                       bool MaxOrZero)
    6877          39 :     : ExitLimit(E, M, MaxOrZero, None) {
    6878             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6879             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6880             :          "No point in having a non-constant max backedge taken count!");
    6881          39 : }
    6882             : 
    6883             : /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
    6884             : /// computable exit into a persistent ExitNotTakenInfo array.
    6885       21737 : ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
    6886             :     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
    6887             :         &&ExitCounts,
    6888       21737 :     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
    6889       43474 :     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
    6890             :   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
    6891             : 
    6892             :   ExitNotTaken.reserve(ExitCounts.size());
    6893       21737 :   std::transform(
    6894             :       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
    6895       16058 :       [&](const EdgeExitInfo &EEI) {
    6896       16058 :         BasicBlock *ExitBB = EEI.first;
    6897             :         const ExitLimit &EL = EEI.second;
    6898       16058 :         if (EL.Predicates.empty())
    6899       32094 :           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
    6900             : 
    6901          22 :         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
    6902          11 :         for (auto *Pred : EL.Predicates)
    6903          11 :           Predicate->add(Pred);
    6904             : 
    6905          22 :         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
    6906             :       });
    6907             :   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
    6908             :          "No point in having a non-constant max backedge taken count!");
    6909       21737 : }
    6910             : 
    6911             : /// Invalidate this result and free the ExitNotTakenInfo array.
    6912       21641 : void ScalarEvolution::BackedgeTakenInfo::clear() {
    6913             :   ExitNotTaken.clear();
    6914       21641 : }
    6915             : 
    6916             : /// Compute the number of times the backedge of the specified loop will execute.
    6917             : ScalarEvolution::BackedgeTakenInfo
    6918       21737 : ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
    6919             :                                            bool AllowPredicates) {
    6920             :   SmallVector<BasicBlock *, 8> ExitingBlocks;
    6921       21737 :   L->getExitingBlocks(ExitingBlocks);
    6922             : 
    6923             :   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
    6924             : 
    6925       21737 :   SmallVector<EdgeExitInfo, 4> ExitCounts;
    6926             :   bool CouldComputeBECount = true;
    6927       21737 :   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
    6928             :   const SCEV *MustExitMaxBECount = nullptr;
    6929             :   const SCEV *MayExitMaxBECount = nullptr;
    6930             :   bool MustExitMaxOrZero = false;
    6931             : 
    6932             :   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
    6933             :   // and compute maxBECount.
    6934             :   // Do a union of all the predicates here.
    6935       71229 :   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
    6936       98984 :     BasicBlock *ExitBB = ExitingBlocks[i];
    6937       49492 :     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
    6938             : 
    6939             :     assert((AllowPredicates || EL.Predicates.empty()) &&
    6940             :            "Predicated exit limit when predicates are not allowed!");
    6941             : 
    6942             :     // 1. For each exit that can be computed, add an entry to ExitCounts.
    6943             :     // CouldComputeBECount is true only if all exits can be computed.
    6944       49492 :     if (EL.ExactNotTaken == getCouldNotCompute())
    6945             :       // We couldn't compute an exact value for this exit, so
    6946             :       // we won't be able to compute an exact value for the loop.
    6947             :       CouldComputeBECount = false;
    6948             :     else
    6949       16058 :       ExitCounts.emplace_back(ExitBB, EL);
    6950             : 
    6951             :     // 2. Derive the loop's MaxBECount from each exit's max number of
    6952             :     // non-exiting iterations. Partition the loop exits into two kinds:
    6953             :     // LoopMustExits and LoopMayExits.
    6954             :     //
    6955             :     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
    6956             :     // is a LoopMayExit.  If any computable LoopMustExit is found, then
    6957             :     // MaxBECount is the minimum EL.MaxNotTaken of computable
    6958             :     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
    6959             :     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
    6960             :     // computable EL.MaxNotTaken.
    6961       66430 :     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
    6962       16938 :         DT.dominates(ExitBB, Latch)) {
    6963       16938 :       if (!MustExitMaxBECount) {
    6964       16570 :         MustExitMaxBECount = EL.MaxNotTaken;
    6965       16570 :         MustExitMaxOrZero = EL.MaxOrZero;
    6966             :       } else {
    6967         368 :         MustExitMaxBECount =
    6968         368 :             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
    6969             :       }
    6970       32554 :     } else if (MayExitMaxBECount != getCouldNotCompute()) {
    6971        8491 :       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
    6972        8491 :         MayExitMaxBECount = EL.MaxNotTaken;
    6973             :       else {
    6974           0 :         MayExitMaxBECount =
    6975           0 :             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
    6976             :       }
    6977             :     }
    6978             :   }
    6979       21737 :   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
    6980        5167 :     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
    6981             :   // The loop backedge will be taken the maximum or zero times if there's
    6982             :   // a single exit that must be taken the maximum or zero times.
    6983       21758 :   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
    6984             :   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
    6985       43474 :                            MaxBECount, MaxOrZero);
    6986             : }
    6987             : 
    6988             : ScalarEvolution::ExitLimit
    6989       49492 : ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
    6990             :                                       bool AllowPredicates) {
    6991             :   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
    6992             :   // If our exiting block does not dominate the latch, then its connection with
    6993             :   // loop's exit limit may be far from trivial.
    6994       49492 :   const BasicBlock *Latch = L->getLoopLatch();
    6995       49492 :   if (!Latch || !DT.dominates(ExitingBlock, Latch))
    6996       17942 :     return getCouldNotCompute();
    6997             : 
    6998       31550 :   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
    6999             :   TerminatorInst *Term = ExitingBlock->getTerminator();
    7000             :   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
    7001             :     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
    7002       24846 :     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
    7003             :     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
    7004             :            "It should have one successor in loop and one exit block!");
    7005             :     // Proceed to the next level to examine the exit condition expression.
    7006             :     return computeExitLimitFromCond(
    7007             :         L, BI->getCondition(), ExitIfTrue,
    7008       49692 :         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
    7009             :   }
    7010             : 
    7011             :   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
    7012             :     // For switch, make sure that there is a single exit from the loop.
    7013             :     BasicBlock *Exit = nullptr;
    7014          58 :     for (auto *SBB : successors(ExitingBlock))
    7015         187 :       if (!L->contains(SBB)) {
    7016          83 :         if (Exit) // Multiple exit successors.
    7017          25 :           return getCouldNotCompute();
    7018             :         Exit = SBB;
    7019             :       }
    7020             :     assert(Exit && "Exiting block must have at least one exit");
    7021             :     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
    7022          33 :                                                 /*ControlsExit=*/IsOnlyExit);
    7023             :   }
    7024             : 
    7025        6646 :   return getCouldNotCompute();
    7026             : }
    7027             : 
    7028       24846 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
    7029             :     const Loop *L, Value *ExitCond, bool ExitIfTrue,
    7030             :     bool ControlsExit, bool AllowPredicates) {
    7031       24846 :   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
    7032             :   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
    7033       49692 :                                         ControlsExit, AllowPredicates);
    7034             : }
    7035             : 
    7036             : Optional<ScalarEvolution::ExitLimit>
    7037       25366 : ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
    7038             :                                       bool ExitIfTrue, bool ControlsExit,
    7039             :                                       bool AllowPredicates) {
    7040             :   (void)this->L;
    7041             :   (void)this->ExitIfTrue;
    7042             :   (void)this->AllowPredicates;
    7043             : 
    7044             :   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
    7045             :          this->AllowPredicates == AllowPredicates &&
    7046             :          "Variance in assumed invariant key components!");
    7047       50732 :   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
    7048       25366 :   if (Itr == TripCountMap.end())
    7049             :     return None;
    7050             :   return Itr->second;
    7051             : }
    7052             : 
    7053       25306 : void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
    7054             :                                              bool ExitIfTrue,
    7055             :                                              bool ControlsExit,
    7056             :                                              bool AllowPredicates,
    7057             :                                              const ExitLimit &EL) {
    7058             :   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
    7059             :          this->AllowPredicates == AllowPredicates &&
    7060             :          "Variance in assumed invariant key components!");
    7061             : 
    7062       50612 :   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
    7063             :   assert(InsertResult.second && "Expected successful insertion!");
    7064             :   (void)InsertResult;
    7065             :   (void)ExitIfTrue;
    7066       25306 : }
    7067             : 
    7068       25366 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
    7069             :     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
    7070             :     bool ControlsExit, bool AllowPredicates) {
    7071             : 
    7072       25366 :   if (auto MaybeEL =
    7073       25366 :           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
    7074             :     return *MaybeEL;
    7075             : 
    7076             :   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
    7077       25306 :                                               ControlsExit, AllowPredicates);
    7078       25306 :   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
    7079             :   return EL;
    7080             : }
    7081             : 
    7082       25306 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
    7083             :     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
    7084             :     bool ControlsExit, bool AllowPredicates) {
    7085             :   // Check if the controlling expression for this loop is an And or Or.
    7086             :   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
    7087         269 :     if (BO->getOpcode() == Instruction::And) {
    7088             :       // Recurse on the operands of the and.
    7089             :       bool EitherMayExit = !ExitIfTrue;
    7090             :       ExitLimit EL0 = computeExitLimitFromCondCached(
    7091             :           Cache, L, BO->getOperand(0), ExitIfTrue,
    7092         408 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7093             :       ExitLimit EL1 = computeExitLimitFromCondCached(
    7094             :           Cache, L, BO->getOperand(1), ExitIfTrue,
    7095         204 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7096         204 :       const SCEV *BECount = getCouldNotCompute();
    7097         204 :       const SCEV *MaxBECount = getCouldNotCompute();
    7098         204 :       if (EitherMayExit) {
    7099             :         // Both conditions must be true for the loop to continue executing.
    7100             :         // Choose the less conservative count.
    7101         183 :         if (EL0.ExactNotTaken == getCouldNotCompute() ||
    7102          49 :             EL1.ExactNotTaken == getCouldNotCompute())
    7103         123 :           BECount = getCouldNotCompute();
    7104             :         else
    7105             :           BECount =
    7106          11 :               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
    7107         134 :         if (EL0.MaxNotTaken == getCouldNotCompute())
    7108          85 :           MaxBECount = EL1.MaxNotTaken;
    7109          49 :         else if (EL1.MaxNotTaken == getCouldNotCompute())
    7110          38 :           MaxBECount = EL0.MaxNotTaken;
    7111             :         else
    7112             :           MaxBECount =
    7113          11 :               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
    7114             :       } else {
    7115             :         // Both conditions must be true at the same time for the loop to exit.
    7116             :         // For now, be conservative.
    7117          70 :         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
    7118             :           MaxBECount = EL0.MaxNotTaken;
    7119          70 :         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
    7120             :           BECount = EL0.ExactNotTaken;
    7121             :       }
    7122             : 
    7123             :       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
    7124             :       // to be more aggressive when computing BECount than when computing
    7125             :       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
    7126             :       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
    7127             :       // to not.
    7128         265 :       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
    7129             :           !isa<SCEVCouldNotCompute>(BECount))
    7130           2 :         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
    7131             : 
    7132             :       return ExitLimit(BECount, MaxBECount, false,
    7133         408 :                        {&EL0.Predicates, &EL1.Predicates});
    7134             :     }
    7135          65 :     if (BO->getOpcode() == Instruction::Or) {
    7136             :       // Recurse on the operands of the or.
    7137             :       bool EitherMayExit = ExitIfTrue;
    7138             :       ExitLimit EL0 = computeExitLimitFromCondCached(
    7139             :           Cache, L, BO->getOperand(0), ExitIfTrue,
    7140         112 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7141             :       ExitLimit EL1 = computeExitLimitFromCondCached(
    7142             :           Cache, L, BO->getOperand(1), ExitIfTrue,
    7143          56 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7144          56 :       const SCEV *BECount = getCouldNotCompute();
    7145          56 :       const SCEV *MaxBECount = getCouldNotCompute();
    7146          56 :       if (EitherMayExit) {
    7147             :         // Both conditions must be false for the loop to continue executing.
    7148             :         // Choose the less conservative count.
    7149          25 :         if (EL0.ExactNotTaken == getCouldNotCompute() ||
    7150           7 :             EL1.ExactNotTaken == getCouldNotCompute())
    7151          15 :           BECount = getCouldNotCompute();
    7152             :         else
    7153           3 :           BECount =
    7154           3 :               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
    7155          18 :         if (EL0.MaxNotTaken == getCouldNotCompute())
    7156          11 :           MaxBECount = EL1.MaxNotTaken;
    7157           7 :         else if (EL1.MaxNotTaken == getCouldNotCompute())
    7158           4 :           MaxBECount = EL0.MaxNotTaken;
    7159             :         else
    7160           3 :           MaxBECount =
    7161           3 :               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
    7162             :       } else {
    7163             :         // Both conditions must be false at the same time for the loop to exit.
    7164             :         // For now, be conservative.
    7165          38 :         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
    7166             :           MaxBECount = EL0.MaxNotTaken;
    7167          38 :         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
    7168             :           BECount = EL0.ExactNotTaken;
    7169             :       }
    7170             : 
    7171             :       return ExitLimit(BECount, MaxBECount, false,
    7172         112 :                        {&EL0.Predicates, &EL1.Predicates});
    7173             :     }
    7174             :   }
    7175             : 
    7176             :   // With an icmp, it may be feasible to compute an exact backedge-taken count.
    7177             :   // Proceed to the next level to examine the icmp.
    7178             :   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
    7179             :     ExitLimit EL =
    7180       23652 :         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
    7181       23652 :     if (EL.hasFullInfo() || !AllowPredicates)
    7182             :       return EL;
    7183             : 
    7184             :     // Try again, but use SCEV predicates this time.
    7185             :     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
    7186         513 :                                     /*AllowPredicates=*/true);
    7187             :   }
    7188             : 
    7189             :   // Check for a constant condition. These are normally stripped out by
    7190             :   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
    7191             :   // preserve the CFG and is temporarily leaving constant conditions
    7192             :   // in place.
    7193             :   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
    7194         653 :     if (ExitIfTrue == !CI->getZExtValue())
    7195             :       // The backedge is always taken.
    7196         136 :       return getCouldNotCompute();
    7197             :     else
    7198             :       // The backedge is never taken.
    7199         517 :       return getZero(CI->getType());
    7200             :   }
    7201             : 
    7202             :   // If it's not an integer or pointer comparison then compute it the hard way.
    7203         741 :   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
    7204             : }
    7205             : 
    7206             : ScalarEvolution::ExitLimit
    7207       24165 : ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
    7208             :                                           ICmpInst *ExitCond,
    7209             :                                           bool ExitIfTrue,
    7210             :                                           bool ControlsExit,
    7211             :                                           bool AllowPredicates) {
    7212             :   // If the condition was exit on true, convert the condition to exit on false
    7213             :   ICmpInst::Predicate Pred;
    7214       24165 :   if (!ExitIfTrue)
    7215       14206 :     Pred = ExitCond->getPredicate();
    7216             :   else
    7217        9959 :     Pred = ExitCond->getInversePredicate();
    7218       24165 :   const ICmpInst::Predicate OriginalPred = Pred;
    7219             : 
    7220             :   // Handle common loops like: for (X = "string"; *X; ++X)
    7221             :   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
    7222             :     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
    7223             :       ExitLimit ItCnt =
    7224        1835 :         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
    7225        1835 :       if (ItCnt.hasAnyInfo())
    7226             :         return ItCnt;
    7227             :     }
    7228             : 
    7229       24165 :   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
    7230       24165 :   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
    7231             : 
    7232             :   // Try to evaluate any dependencies out of the loop.
    7233       24165 :   LHS = getSCEVAtScope(LHS, L);
    7234       24165 :   RHS = getSCEVAtScope(RHS, L);
    7235             : 
    7236             :   // At this point, we would like to compute how many iterations of the
    7237             :   // loop the predicate will return true for these inputs.
    7238       24165 :   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
    7239             :     // If there is a loop-invariant, force it into the RHS.
    7240             :     std::swap(LHS, RHS);
    7241         226 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    7242             :   }
    7243             : 
    7244             :   // Simplify the operands before analyzing them.
    7245       24165 :   (void)SimplifyICmpOperands(Pred, LHS, RHS);
    7246             : 
    7247             :   // If we have a comparison of a chrec against a constant, try to use value
    7248             :   // ranges to answer this query.
    7249       24165 :   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
    7250       13698 :     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
    7251       10204 :       if (AddRec->getLoop() == L) {
    7252             :         // Form the constant range.
    7253             :         ConstantRange CompRange =
    7254       12155 :             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
    7255             : 
    7256       10190 :         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
    7257       10190 :         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
    7258             :       }
    7259             : 
    7260       15940 :   switch (Pred) {
    7261        8039 :   case ICmpInst::ICMP_NE: {                     // while (X != Y)
    7262             :     // Convert to: while (X-Y != 0)
    7263             :     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
    7264        8039 :                                 AllowPredicates);
    7265        8039 :     if (EL.hasAnyInfo()) return EL;
    7266             :     break;
    7267             :   }
    7268        1197 :   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
    7269             :     // Convert to: while (X-Y == 0)
    7270        1197 :     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
    7271        1197 :     if (EL.hasAnyInfo()) return EL;
    7272             :     break;
    7273             :   }
    7274        4884 :   case ICmpInst::ICMP_SLT:
    7275             :   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
    7276        4884 :     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
    7277             :     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
    7278        4884 :                                     AllowPredicates);
    7279        4884 :     if (EL.hasAnyInfo()) return EL;
    7280             :     break;
    7281             :   }
    7282        1308 :   case ICmpInst::ICMP_SGT:
    7283             :   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
    7284        1308 :     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
    7285             :     ExitLimit EL =
    7286             :         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
    7287        1308 :                             AllowPredicates);
    7288        1308 :     if (EL.hasAnyInfo()) return EL;
    7289             :     break;
    7290             :   }
    7291             :   default:
    7292             :     break;
    7293             :   }
    7294             : 
    7295             :   auto *ExhaustiveCount =
    7296        7771 :       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
    7297             : 
    7298        7771 :   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
    7299          39 :     return ExhaustiveCount;
    7300             : 
    7301             :   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
    7302        7732 :                                       ExitCond->getOperand(1), L, OriginalPred);
    7303             : }
    7304             : 
    7305             : ScalarEvolution::ExitLimit
    7306          33 : ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
    7307             :                                                       SwitchInst *Switch,
    7308             :                                                       BasicBlock *ExitingBlock,
    7309             :                                                       bool ControlsExit) {
    7310             :   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
    7311             : 
    7312             :   // Give up if the exit is the default dest of a switch.
    7313          33 :   if (Switch->getDefaultDest() == ExitingBlock)
    7314          27 :     return getCouldNotCompute();
    7315             : 
    7316             :   assert(L->contains(Switch->getDefaultDest()) &&
    7317             :          "Default case must not exit the loop!");
    7318           6 :   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
    7319           6 :   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
    7320             : 
    7321             :   // while (X != Y) --> while (X-Y != 0)
    7322           6 :   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
    7323           6 :   if (EL.hasAnyInfo())
    7324             :     return EL;
    7325             : 
    7326           5 :   return getCouldNotCompute();
    7327             : }
    7328             : 
    7329             : static ConstantInt *
    7330        8414 : EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
    7331             :                                 ScalarEvolution &SE) {
    7332        8414 :   const SCEV *InVal = SE.getConstant(C);
    7333        8414 :   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
    7334             :   assert(isa<SCEVConstant>(Val) &&
    7335             :          "Evaluation of SCEV at constant didn't fold correctly?");
    7336        8414 :   return cast<SCEVConstant>(Val)->getValue();
    7337             : }
    7338             : 
    7339             : /// Given an exit condition of 'icmp op load X, cst', try to see if we can
    7340             : /// compute the backedge execution count.
    7341             : ScalarEvolution::ExitLimit
    7342        1835 : ScalarEvolution::computeLoadConstantCompareExitLimit(
    7343             :   LoadInst *LI,
    7344             :   Constant *RHS,
    7345             :   const Loop *L,
    7346             :   ICmpInst::Predicate predicate) {
    7347        1835 :   if (LI->isVolatile()) return getCouldNotCompute();
    7348             : 
    7349             :   // Check to see if the loaded pointer is a getelementptr of a global.
    7350             :   // TODO: Use SCEV instead of manually grubbing with GEPs.
    7351             :   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
    7352         693 :   if (!GEP) return getCouldNotCompute();
    7353             : 
    7354             :   // Make sure that it is really a constant global we are gepping, with an
    7355             :   // initializer, and make sure the first IDX is really 0.
    7356             :   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
    7357          18 :   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
    7358           0 :       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
    7359           0 :       !cast<Constant>(GEP->getOperand(1))->isNullValue())
    7360        1092 :     return getCouldNotCompute();
    7361             : 
    7362             :   // Okay, we allow one non-constant index into the GEP instruction.
    7363             :   Value *VarIdx = nullptr;
    7364             :   std::vector<Constant*> Indexes;
    7365             :   unsigned VarIdxNum = 0;
    7366           0 :   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
    7367             :     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
    7368           0 :       Indexes.push_back(CI);
    7369           0 :     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
    7370           0 :       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
    7371             :       VarIdx = GEP->getOperand(i);
    7372           0 :       VarIdxNum = i-2;
    7373           0 :       Indexes.push_back(nullptr);
    7374             :     }
    7375             : 
    7376             :   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
    7377           0 :   if (!VarIdx)
    7378           0 :     return getCouldNotCompute();
    7379             : 
    7380             :   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
    7381             :   // Check to see if X is a loop variant variable value now.
    7382           0 :   const SCEV *Idx = getSCEV(VarIdx);
    7383           0 :   Idx = getSCEVAtScope(Idx, L);
    7384             : 
    7385             :   // We can only recognize very limited forms of loop index expressions, in
    7386             :   // particular, only affine AddRec's like {C1,+,C2}.
    7387             :   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
    7388           0 :   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
    7389           0 :       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
    7390             :       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
    7391           0 :     return getCouldNotCompute();
    7392             : 
    7393             :   unsigned MaxSteps = MaxBruteForceIterations;
    7394           0 :   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
    7395           0 :     ConstantInt *ItCst = ConstantInt::get(
    7396           0 :                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
    7397           0 :     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
    7398             : 
    7399             :     // Form the GEP offset.
    7400           0 :     Indexes[VarIdxNum] = Val;
    7401             : 
    7402           0 :     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
    7403             :                                                          Indexes);
    7404           0 :     if (!Result) break;  // Cannot compute!
    7405             : 
    7406             :     // Evaluate the condition for this iteration.
    7407           0 :     Result = ConstantExpr::getICmp(predicate, Result, RHS);
    7408           0 :     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
    7409           0 :     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
    7410             :       ++NumArrayLenItCounts;
    7411           0 :       return getConstant(ItCst);   // Found terminating iteration!
    7412             :     }
    7413             :   }
    7414           0 :   return getCouldNotCompute();
    7415             : }
    7416             : 
    7417        7732 : ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
    7418             :     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
    7419             :   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
    7420             :   if (!RHS)
    7421        4595 :     return getCouldNotCompute();
    7422             : 
    7423        3137 :   const BasicBlock *Latch = L->getLoopLatch();
    7424        3137 :   if (!Latch)
    7425           0 :     return getCouldNotCompute();
    7426             : 
    7427        3137 :   const BasicBlock *Predecessor = L->getLoopPredecessor();
    7428        3137 :   if (!Predecessor)
    7429           3 :     return getCouldNotCompute();
    7430             : 
    7431             :   // Return true if V is of the form "LHS `shift_op` <positive constant>".
    7432             :   // Return LHS in OutLHS and shift_opt in OutOpCode.
    7433             :   auto MatchPositiveShift =
    7434        3333 :       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
    7435             : 
    7436             :     using namespace PatternMatch;
    7437             : 
    7438             :     ConstantInt *ShiftAmt;
    7439        6666 :     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
    7440          34 :       OutOpCode = Instruction::LShr;
    7441        6598 :     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
    7442          62 :       OutOpCode = Instruction::AShr;
    7443        6474 :     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
    7444           3 :       OutOpCode = Instruction::Shl;
    7445             :     else
    7446             :       return false;
    7447             : 
    7448         198 :     return ShiftAmt->getValue().isStrictlyPositive();
    7449             :   };
    7450             : 
    7451             :   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
    7452             :   //
    7453             :   // loop:
    7454             :   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
    7455             :   //   %iv.shifted = lshr i32 %iv, <positive constant>
    7456             :   //
    7457             :   // Return true on a successful match.  Return the corresponding PHI node (%iv
    7458             :   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
    7459             :   auto MatchShiftRecurrence =
    7460        3134 :       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
    7461             :     Optional<Instruction::BinaryOps> PostShiftOpCode;
    7462             : 
    7463             :     {
    7464             :       Instruction::BinaryOps OpC;
    7465             :       Value *V;
    7466             : 
    7467             :       // If we encounter a shift instruction, "peel off" the shift operation,
    7468             :       // and remember that we did so.  Later when we inspect %iv's backedge
    7469             :       // value, we will make sure that the backedge value uses the same
    7470             :       // operation.
    7471             :       //
    7472             :       // Note: the peeled shift operation does not have to be the same
    7473             :       // instruction as the one feeding into the PHI's backedge value.  We only
    7474             :       // really care about it being the same *kind* of shift instruction --
    7475             :       // that's all that is required for our later inferences to hold.
    7476        6314 :       if (MatchPositiveShift(LHS, V, OpC)) {
    7477          46 :         PostShiftOpCode = OpC;
    7478          46 :         LHS = V;
    7479             :       }
    7480             :     }
    7481             : 
    7482        6268 :     PNOut = dyn_cast<PHINode>(LHS);
    7483        3556 :     if (!PNOut || PNOut->getParent() != L->getHeader())
    7484             :       return false;
    7485             : 
    7486         199 :     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
    7487             :     Value *OpLHS;
    7488             : 
    7489             :     return
    7490             :         // The backedge value for the PHI node must be a shift by a positive
    7491             :         // amount
    7492         252 :         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
    7493             : 
    7494             :         // of the PHI node itself
    7495         252 :         OpLHS == PNOut &&
    7496             : 
    7497             :         // and the kind of shift should be match the kind of shift we peeled
    7498             :         // off, if any.
    7499          84 :         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
    7500        3134 :   };
    7501             : 
    7502             :   PHINode *PN;
    7503             :   Instruction::BinaryOps OpCode;
    7504        3134 :   if (!MatchShiftRecurrence(LHS, PN, OpCode))
    7505        3084 :     return getCouldNotCompute();
    7506             : 
    7507          50 :   const DataLayout &DL = getDataLayout();
    7508             : 
    7509             :   // The key rationale for this optimization is that for some kinds of shift
    7510             :   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
    7511             :   // within a finite number of iterations.  If the condition guarding the
    7512             :   // backedge (in the sense that the backedge is taken if the condition is true)
    7513             :   // is false for the value the shift recurrence stabilizes to, then we know
    7514             :   // that the backedge is taken only a finite number of times.
    7515             : 
    7516             :   ConstantInt *StableValue = nullptr;
    7517          50 :   switch (OpCode) {
    7518           0 :   default:
    7519           0 :     llvm_unreachable("Impossible case!");
    7520             : 
    7521          37 :   case Instruction::AShr: {
    7522             :     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
    7523             :     // bitwidth(K) iterations.
    7524          37 :     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
    7525             :     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
    7526          37 :                                        Predecessor->getTerminator(), &DT);
    7527             :     auto *Ty = cast<IntegerType>(RHS->getType());
    7528          37 :     if (Known.isNonNegative())
    7529          23 :       StableValue = ConstantInt::get(Ty, 0);
    7530          14 :     else if (Known.isNegative())
    7531           9 :       StableValue = ConstantInt::get(Ty, -1, true);
    7532             :     else
    7533           5 :       return getCouldNotCompute();
    7534             : 
    7535          32 :     break;
    7536             :   }
    7537             :   case Instruction::LShr:
    7538             :   case Instruction::Shl:
    7539             :     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
    7540             :     // stabilize to 0 in at most bitwidth(K) iterations.
    7541          13 :     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
    7542          13 :     break;
    7543             :   }
    7544             : 
    7545             :   auto *Result =
    7546          45 :       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
    7547             :   assert(Result->getType()->isIntegerTy(1) &&
    7548             :          "Otherwise cannot be an operand to a branch instruction");
    7549             : 
    7550          45 :   if (Result->isZeroValue()) {
    7551          39 :     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
    7552             :     const SCEV *UpperBound =
    7553          39 :         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
    7554          39 :     return ExitLimit(getCouldNotCompute(), UpperBound, false);
    7555             :   }
    7556             : 
    7557           6 :   return getCouldNotCompute();
    7558             : }
    7559             : 
    7560             : /// Return true if we can constant fold an instruction of the specified type,
    7561             : /// assuming that all operands were constants.
    7562       79292 : static bool CanConstantFold(const Instruction *I) {
    7563       36032 :   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
    7564      114735 :       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
    7565             :       isa<LoadInst>(I))
    7566             :     return true;
    7567             : 
    7568             :   if (const CallInst *CI = dyn_cast<CallInst>(I))
    7569             :     if (const Function *F = CI->getCalledFunction())
    7570        2200 :       return canConstantFoldCallTo(CI, F);
    7571             :   return false;
    7572             : }
    7573             : 
    7574             : /// Determine whether this instruction can constant evolve within this loop
    7575             : /// assuming its operands can all constant evolve.
    7576       55482 : static bool canConstantEvolve(Instruction *I, const Loop *L) {
    7577             :   // An instruction outside of the loop can't be derived from a loop PHI.
    7578       55482 :   if (!L->contains(I)) return false;
    7579             : 
    7580       52158 :   if (isa<PHINode>(I)) {
    7581             :     // We don't currently keep track of the control flow needed to evaluate
    7582             :     // PHIs, so we cannot handle PHIs inside of loops.
    7583        4852 :     return L->getHeader() == I->getParent();
    7584             :   }
    7585             : 
    7586             :   // If we won't be able to constant fold this expression even if the operands
    7587             :   // are constants, bail early.
    7588       47306 :   return CanConstantFold(I);
    7589             : }
    7590             : 
    7591             : /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
    7592             : /// recursing through each instruction operand until reaching a loop header phi.
    7593             : static PHINode *
    7594       19592 : getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
    7595             :                                DenseMap<Instruction *, PHINode *> &PHIMap,
    7596             :                                unsigned Depth) {
    7597       19592 :   if (Depth > MaxConstantEvolvingDepth)
    7598             :     return nullptr;
    7599             : 
    7600             :   // Otherwise, we can evaluate this instruction if all of its operands are
    7601             :   // constant or derived from a PHI node themselves.
    7602             :   PHINode *PHI = nullptr;
    7603       70250 :   for (Value *Op : UseInst->operands()) {
    7604       28400 :     if (isa<Constant>(Op)) continue;
    7605             : 
    7606       22594 :     Instruction *OpInst = dyn_cast<Instruction>(Op);
    7607       35453 :     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
    7608             : 
    7609       15998 :     PHINode *P = dyn_cast<PHINode>(OpInst);
    7610             :     if (!P)
    7611             :       // If this operand is already visited, reuse the prior result.
    7612             :       // We may have P != PHI if this is the deepest point at which the
    7613             :       // inconsistent paths meet.
    7614             :       P = PHIMap.lookup(OpInst);
    7615        4225 :     if (!P) {
    7616             :       // Recurse and memoize the results, whether a phi is found or not.
    7617             :       // This recursive call invalidates pointers into PHIMap.
    7618       11773 :       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
    7619       11773 :       PHIMap[OpInst] = P;
    7620             :     }
    7621       15998 :     if (!P)
    7622             :       return nullptr;  // Not evolving from PHI
    7623        9812 :     if (PHI && PHI != P)
    7624             :       return nullptr;  // Evolving from multiple different PHIs.
    7625             :     PHI = P;
    7626             :   }
    7627             :   // This is a expression evolving from a constant PHI!
    7628             :   return PHI;
    7629             : }
    7630             : 
    7631             : /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
    7632             : /// in the loop that V is derived from.  We allow arbitrary operations along the
    7633             : /// way, but the operands of an operation must either be constants or a value
    7634             : /// derived from a constant PHI.  If this expression does not fit with these
    7635             : /// constraints, return null.
    7636        8512 : static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
    7637             :   Instruction *I = dyn_cast<Instruction>(V);
    7638        8275 :   if (!I || !canConstantEvolve(I, L)) return nullptr;
    7639             : 
    7640             :   if (PHINode *PN = dyn_cast<PHINode>(I))
    7641             :     return PN;
    7642             : 
    7643             :   // Record non-constant instructions contained by the loop.
    7644             :   DenseMap<Instruction *, PHINode *> PHIMap;
    7645        7819 :   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
    7646             : }
    7647             : 
    7648             : /// EvaluateExpression - Given an expression that passes the
    7649             : /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
    7650             : /// in the loop has the value PHIVal.  If we can't fold this expression for some
    7651             : /// reason, return null.
    7652       49867 : static Constant *EvaluateExpression(Value *V, const Loop *L,
    7653             :                                     DenseMap<Instruction *, Constant *> &Vals,
    7654             :                                     const DataLayout &DL,
    7655             :                                     const TargetLibraryInfo *TLI) {
    7656             :   // Convenient constant check, but redundant for recursive calls.
    7657             :   if (Constant *C = dyn_cast<Constant>(V)) return C;
    7658             :   Instruction *I = dyn_cast<Instruction>(V);
    7659             :   if (!I) return nullptr;
    7660             : 
    7661       23800 :   if (Constant *C = Vals.lookup(I)) return C;
    7662             : 
    7663             :   // An instruction inside the loop depends on a value outside the loop that we
    7664             :   // weren't given a mapping for, or a value such as a call inside the loop.
    7665       25984 :   if (!canConstantEvolve(I, L)) return nullptr;
    7666             : 
    7667             :   // An unmapped PHI can be due to a branch or another loop inside this loop,
    7668             :   // or due to this not being the initial iteration through a loop where we
    7669             :   // couldn't compute the evolution of this particular PHI last time.
    7670       25956 :   if (isa<PHINode>(I)) return nullptr;
    7671             : 
    7672       25930 :   std::vector<Constant*> Operands(I->getNumOperands());
    7673             : 
    7674      127536 :   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
    7675      101884 :     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
    7676       65932 :     if (!Operand) {
    7677       29990 :       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
    7678       15134 :       if (!Operands[i]) return nullptr;
    7679       14990 :       continue;
    7680             :     }
    7681       35947 :     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
    7682       35947 :     Vals[Operand] = C;
    7683       35947 :     if (!C) return nullptr;
    7684       71626 :     Operands[i] = C;
    7685             :   }
    7686             : 
    7687             :   if (CmpInst *CI = dyn_cast<CmpInst>(I))
    7688        6055 :     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
    7689       12110 :                                            Operands[1], DL, TLI);
    7690             :   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
    7691         176 :     if (!LI->isVolatile())
    7692         176 :       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
    7693             :   }
    7694       19560 :   return ConstantFoldInstOperands(I, Operands, DL, TLI);
    7695             : }
    7696             : 
    7697             : 
    7698             : // If every incoming value to PN except the one for BB is a specific Constant,
    7699             : // return that, else return nullptr.
    7700        2235 : static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
    7701             :   Constant *IncomingVal = nullptr;
    7702             : 
    7703        6621 :   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    7704        3748 :     if (PN->getIncomingBlock(i) == BB)
    7705        1511 :       continue;
    7706             : 
    7707             :     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
    7708             :     if (!CurrentVal)
    7709             :       return nullptr;
    7710             : 
    7711         682 :     if (IncomingVal != CurrentVal) {
    7712         680 :       if (IncomingVal)
    7713             :         return nullptr;
    7714             :       IncomingVal = CurrentVal;
    7715             :     }
    7716             :   }
    7717             : 
    7718             :   return IncomingVal;
    7719             : }
    7720             : 
    7721             : /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
    7722             : /// in the header of its containing loop, we know the loop executes a
    7723             : /// constant number of times, and the PHI node is just a recurrence
    7724             : /// involving constants, fold it.
    7725             : Constant *
    7726         117 : ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
    7727             :                                                    const APInt &BEs,
    7728             :                                                    const Loop *L) {
    7729         117 :   auto I = ConstantEvolutionLoopExitValue.find(PN);
    7730         117 :   if (I != ConstantEvolutionLoopExitValue.end())
    7731           0 :     return I->second;
    7732             : 
    7733         117 :   if (BEs.ugt(MaxBruteForceIterations))
    7734           7 :     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
    7735             : 
    7736             :   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
    7737             : 
    7738             :   DenseMap<Instruction *, Constant *> CurrentIterVals;
    7739             :   BasicBlock *Header = L->getHeader();
    7740             :   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
    7741             : 
    7742         110 :   BasicBlock *Latch = L->getLoopLatch();
    7743         110 :   if (!Latch)
    7744             :     return nullptr;
    7745             : 
    7746         110 :   for (PHINode &PHI : Header->phis()) {
    7747         346 :     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
    7748         426 :       CurrentIterVals[&PHI] = StartCST;
    7749             :   }
    7750         110 :   if (!CurrentIterVals.count(PN))
    7751          19 :     return RetVal = nullptr;
    7752             : 
    7753          91 :   Value *BEValue = PN->getIncomingValueForBlock(Latch);
    7754             : 
    7755             :   // Execute the loop symbolically to determine the exit value.
    7756             :   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
    7757             :          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
    7758             : 
    7759          91 :   unsigned NumIterations = BEs.getZExtValue(); // must be in range
    7760             :   unsigned IterationNum = 0;
    7761          91 :   const DataLayout &DL = getDataLayout();
    7762         443 :   for (; ; ++IterationNum) {
    7763         534 :     if (IterationNum == NumIterations)
    7764         130 :       return RetVal = CurrentIterVals[PN];  // Got exit value!
    7765             : 
    7766             :     // Compute the value of the PHIs for the next iteration.
    7767             :     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
    7768             :     DenseMap<Instruction *, Constant *> NextIterVals;
    7769             :     Constant *NextPHI =
    7770         469 :         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
    7771         469 :     if (!NextPHI)
    7772             :       return nullptr;        // Couldn't evaluate!
    7773         886 :     NextIterVals[PN] = NextPHI;
    7774             : 
    7775         886 :     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
    7776             : 
    7777             :     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
    7778             :     // cease to be able to evaluate one of them or if they stop evolving,
    7779             :     // because that doesn't necessarily prevent us from computing PN.
    7780             :     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
    7781        2552 :     for (const auto &I : CurrentIterVals) {
    7782        3332 :       PHINode *PHI = dyn_cast<PHINode>(I.first);
    7783        2949 :       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
    7784         383 :       PHIsToCompute.emplace_back(PHI, I.second);
    7785             :     }
    7786             :     // We use two distinct loops because EvaluateExpression may invalidate any
    7787             :     // iterators into CurrentIterVals.
    7788        1209 :     for (const auto &I : PHIsToCompute) {
    7789         383 :       PHINode *PHI = I.first;
    7790         766 :       Constant *&NextPHI = NextIterVals[PHI];
    7791         383 :       if (!NextPHI) {   // Not already computed.
    7792         383 :         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
    7793         383 :         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
    7794             :       }
    7795         383 :       if (NextPHI != I.second)
    7796             :         StoppedEvolving = false;
    7797             :     }
    7798             : 
    7799             :     // If all entries in CurrentIterVals == NextIterVals then we can stop
    7800             :     // iterating, the loop can't continue to change.
    7801         443 :     if (StoppedEvolving)
    7802           0 :       return RetVal = CurrentIterVals[PN];
    7803             : 
    7804             :     CurrentIterVals.swap(NextIterVals);
    7805         443 :   }
    7806             : }
    7807             : 
    7808        8512 : const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
    7809             :                                                           Value *Cond,
    7810             :                                                           bool ExitWhen) {
    7811        8512 :   PHINode *PN = getConstantEvolvingPHI(Cond, L);
    7812        8512 :   if (!PN) return getCouldNotCompute();
    7813             : 
    7814             :   // If the loop is canonicalized, the PHI will have exactly two entries.
    7815             :   // That's the only form we support here.
    7816        1066 :   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
    7817             : 
    7818             :   DenseMap<Instruction *, Constant *> CurrentIterVals;
    7819             :   BasicBlock *Header = L->getHeader();
    7820             :   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
    7821             : 
    7822        1063 :   BasicBlock *Latch = L->getLoopLatch();
    7823             :   assert(Latch && "Should follow from NumIncomingValues == 2!");
    7824             : 
    7825        1063 :   for (PHINode &PHI : Header->phis()) {
    7826        1889 :     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
    7827         934 :       CurrentIterVals[&PHI] = StartCST;
    7828             :   }
    7829             :   if (!CurrentIterVals.count(PN))
    7830         914 :     return getCouldNotCompute();
    7831             : 
    7832             :   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
    7833             :   // the loop symbolically to determine when the condition gets a value of
    7834             :   // "ExitWhen".
    7835             :   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
    7836         149 :   const DataLayout &DL = getDataLayout();
    7837       11709 :   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
    7838        5874 :     auto *CondVal = dyn_cast_or_null<ConstantInt>(
    7839        5874 :         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
    7840             : 
    7841             :     // Couldn't symbolically evaluate.
    7842         146 :     if (!CondVal) return getCouldNotCompute();
    7843             : 
    7844       11644 :     if (CondVal->getValue() == uint64_t(ExitWhen)) {
    7845             :       ++NumBruteForceTripCountsComputed;
    7846          84 :       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
    7847             :     }
    7848             : 
    7849             :     // Update all the PHI nodes for the next iteration.
    7850             :     DenseMap<Instruction *, Constant *> NextIterVals;
    7851             : 
    7852             :     // Create a list of which PHIs we need to compute. We want to do this before
    7853             :     // calling EvaluateExpression on them because that may invalidate iterators
    7854             :     // into CurrentIterVals.
    7855             :     SmallVector<PHINode *, 8> PHIsToCompute;
    7856       32462 :     for (const auto &I : CurrentIterVals) {
    7857       41804 :       PHINode *PHI = dyn_cast<PHINode>(I.first);
    7858       34610 :       if (!PHI || PHI->getParent() != Header) continue;
    7859        7194 :       PHIsToCompute.push_back(PHI);
    7860             :     }
    7861       20168 :     for (PHINode *PHI : PHIsToCompute) {
    7862       14388 :       Constant *&NextPHI = NextIterVals[PHI];
    7863        7194 :       if (NextPHI) continue;    // Already computed!
    7864             : 
    7865        7194 :       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
    7866        7194 :       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
    7867             :     }
    7868             :     CurrentIterVals.swap(NextIterVals);
    7869             :   }
    7870             : 
    7871             :   // Too many iterations were needed to evaluate.
    7872          55 :   return getCouldNotCompute();
    7873             : }
    7874             : 
    7875      522908 : const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
    7876             :   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
    7877      522908 :       ValuesAtScopes[V];
    7878             :   // Check to see if we've folded this expression at this loop before.
    7879     1606228 :   for (auto &LS : Values)
    7880      838158 :     if (LS.first == L)
    7881      296498 :       return LS.second ? LS.second : V;
    7882             : 
    7883      226410 :   Values.emplace_back(L, nullptr);
    7884             : 
    7885             :   // Otherwise compute it.
    7886      226410 :   const SCEV *C = computeSCEVAtScope(V, L);
    7887      226448 :   for (auto &LS : reverse(ValuesAtScopes[V]))
    7888      225752 :     if (LS.first == L) {
    7889      225714 :       LS.second = C;
    7890      225714 :       break;
    7891             :     }
    7892             :   return C;
    7893             : }
    7894             : 
    7895             : /// This builds up a Constant using the ConstantExpr interface.  That way, we
    7896             : /// will return Constants for objects which aren't represented by a
    7897             : /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
    7898             : /// Returns NULL if the SCEV isn't representable as a Constant.
    7899       40709 : static Constant *BuildConstantFromSCEV(const SCEV *V) {
    7900       40709 :   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
    7901             :     case scCouldNotCompute:
    7902             :     case scAddRecExpr:
    7903             :       break;
    7904             :     case scConstant:
    7905        7830 :       return cast<SCEVConstant>(V)->getValue();
    7906             :     case scUnknown:
    7907             :       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
    7908             :     case scSignExtend: {
    7909             :       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
    7910         335 :       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
    7911           0 :         return ConstantExpr::getSExt(CastOp, SS->getType());
    7912             :       break;
    7913             :     }
    7914             :     case scZeroExtend: {
    7915             :       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
    7916         309 :       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
    7917           5 :         return ConstantExpr::getZExt(CastOp, SZ->getType());
    7918             :       break;
    7919             :     }
    7920             :     case scTruncate: {
    7921             :       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
    7922         115 :       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
    7923           2 :         return ConstantExpr::getTrunc(CastOp, ST->getType());
    7924             :       break;
    7925             :     }
    7926             :     case scAddExpr: {
    7927             :       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
    7928       15632 :       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
    7929        5978 :         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
    7930             :           unsigned AS = PTy->getAddressSpace();
    7931           0 :           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
    7932           0 :           C = ConstantExpr::getBitCast(C, DestPtrTy);
    7933             :         }
    7934        5994 :         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
    7935       11958 :           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
    7936        5979 :           if (!C2) return nullptr;
    7937             : 
    7938             :           // First pointer!
    7939          48 :           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
    7940             :             unsigned AS = C2->getType()->getPointerAddressSpace();
    7941             :             std::swap(C, C2);
    7942          13 :             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
    7943             :             // The offsets have been converted to bytes.  We can add bytes to an
    7944             :             // i8* by GEP with the byte count in the first index.
    7945          13 :             C = ConstantExpr::getBitCast(C, DestPtrTy);
    7946             :           }
    7947             : 
    7948             :           // Don't bother trying to sum two pointers. We probably can't
    7949             :           // statically compute a load that results from it anyway.
    7950          32 :           if (C2->getType()->isPointerTy())
    7951             :             return nullptr;
    7952             : 
    7953          16 :           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
    7954          26 :             if (PTy->getElementType()->isStructTy())
    7955           0 :               C2 = ConstantExpr::getIntegerCast(
    7956           0 :                   C2, Type::getInt32Ty(C->getContext()), true);
    7957          13 :             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
    7958             :           } else
    7959           3 :             C = ConstantExpr::getAdd(C, C2);
    7960             :         }
    7961             :         return C;
    7962             :       }
    7963             :       break;
    7964             :     }
    7965             :     case scMulExpr: {
    7966             :       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
    7967        3594 :       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
    7968             :         // Don't bother with pointers at all.
    7969        3538 :         if (C->getType()->isPointerTy()) return nullptr;
    7970        1772 :         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
    7971        3538 :           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
    7972        1772 :           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
    7973           3 :           C = ConstantExpr::getMul(C, C2);
    7974             :         }
    7975             :         return C;
    7976             :       }
    7977             :       break;
    7978             :     }
    7979             :     case scUDivExpr: {
    7980             :       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
    7981         275 :       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
    7982           8 :         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
    7983           2 :           if (LHS->getType() == RHS->getType())
    7984           2 :             return ConstantExpr::getUDiv(LHS, RHS);
    7985             :       break;
    7986             :     }
    7987             :     case scSMaxExpr:
    7988             :     case scUMaxExpr:
    7989             :       break; // TODO: smax, umax.
    7990             :   }
    7991             :   return nullptr;
    7992             : }
    7993             : 
    7994      226410 : const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
    7995      226410 :   if (isa<SCEVConstant>(V)) return V;
    7996             : 
    7997             :   // If this instruction is evolved from a constant-evolving PHI, compute the
    7998             :   // exit value from the loop without using SCEVs.
    7999       52586 :   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
    8000             :     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
    8001       32077 :       const Loop *LI = this->LI[I->getParent()];
    8002       19020 :       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
    8003             :         if (PHINode *PN = dyn_cast<PHINode>(I))
    8004         626 :           if (PN->getParent() == LI->getHeader()) {
    8005             :             // Okay, there is no closed form solution for the PHI node.  Check
    8006             :             // to see if the loop that contains it has a known backedge-taken
    8007             :             // count.  If so, we may be able to force computation of the exit
    8008             :             // value.
    8009         249 :             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
    8010             :             if (const SCEVConstant *BTCC =
    8011             :                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
    8012             : 
    8013             :               // This trivial case can show up in some degenerate cases where
    8014             :               // the incoming IR has not yet been fully simplified.
    8015         286 :               if (BTCC->getValue()->isZero()) {
    8016             :                 Value *InitValue = nullptr;
    8017             :                 bool MultipleInitValues = false;
    8018          66 :                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
    8019          46 :                   if (!LI->contains(PN->getIncomingBlock(i))) {
    8020          26 :                     if (!InitValue)
    8021             :                       InitValue = PN->getIncomingValue(i);
    8022           0 :                     else if (InitValue != PN->getIncomingValue(i)) {
    8023             :                       MultipleInitValues = true;
    8024             :                       break;
    8025             :                     }
    8026             :                   }
    8027          46 :                   if (!MultipleInitValues && InitValue)
    8028          26 :                     return getSCEV(InitValue);
    8029             :                 }
    8030             :               }
    8031             :               // Okay, we know how many times the containing loop executes.  If
    8032             :               // this is a constant evolving PHI node, get the final value at
    8033             :               // the specified iteration number.
    8034             :               Constant *RV =
    8035         117 :                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
    8036         117 :               if (RV) return getSCEV(RV);
    8037             :             }
    8038             :           }
    8039             : 
    8040             :       // Okay, this is an expression that we cannot symbolically evaluate
    8041             :       // into a SCEV.  Check to see if it's possible to symbolically evaluate
    8042             :       // the arguments into constants, and if so, try to constant propagate the
    8043             :       // result.  This is particularly useful for computing loop exit values.
    8044       31986 :       if (CanConstantFold(I)) {
    8045             :         SmallVector<Constant *, 4> Operands;
    8046             :         bool MadeImprovement = false;
    8047       49630 :         for (Value *Op : I->operands()) {
    8048       25044 :           if (Constant *C = dyn_cast<Constant>(Op)) {
    8049        1300 :             Operands.push_back(C);
    8050        1300 :             continue;
    8051             :           }
    8052             : 
    8053             :           // If any of the operands is non-constant and if they are
    8054             :           // non-integer and non-pointer, don't even try to analyze them
    8055             :           // with scev techniques.
    8056       22444 :           if (!isSCEVable(Op->getType()))
    8057       22332 :             return V;
    8058             : 
    8059       22306 :           const SCEV *OrigV = getSCEV(Op);
    8060       22306 :           const SCEV *OpV = getSCEVAtScope(OrigV, L);
    8061       22306 :           MadeImprovement |= OrigV != OpV;
    8062             : 
    8063       22306 :           Constant *C = BuildConstantFromSCEV(OpV);
    8064       22306 :           if (!C) return V;
    8065         112 :           if (C->getType() != Op->getType())
    8066          20 :             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    8067             :                                                               Op->getType(),
    8068             :                                                               false),
    8069             :                                       C, Op->getType());
    8070         112 :           Operands.push_back(C);
    8071             :         }
    8072             : 
    8073             :         // Check to see if getSCEVAtScope actually made an improvement.
    8074        1071 :         if (MadeImprovement) {
    8075             :           Constant *C = nullptr;
    8076          37 :           const DataLayout &DL = getDataLayout();
    8077             :           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
    8078          26 :             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
    8079          13 :                                                 Operands[1], DL, &TLI);
    8080             :           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
    8081          12 :             if (!LI->isVolatile())
    8082          24 :               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
    8083             :           } else
    8084          24 :             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
    8085          37 :           if (!C) return V;
    8086          31 :           return getSCEV(C);
    8087             :         }
    8088             :       }
    8089             :     }
    8090             : 
    8091             :     // This is some other type of SCEVUnknown, just return it.
    8092             :     return V;
    8093             :   }
    8094             : 
    8095             :   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
    8096             :     // Avoid performing the look-up in the common case where the specified
    8097             :     // expression has no loop-variant portions.
    8098      149762 :     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
    8099      226342 :       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
    8100      226342 :       if (OpAtScope != Comm->getOperand(i)) {
    8101             :         // Okay, at least one of these operands is loop variant but might be
    8102             :         // foldable.  Build a new instance of the folded commutative expression.
    8103             :         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
    8104             :                                             Comm->op_begin()+i);
    8105       18391 :         NewOps.push_back(OpAtScope);
    8106             : 
    8107       31359 :         for (++i; i != e; ++i) {
    8108       25936 :           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
    8109       12968 :           NewOps.push_back(OpAtScope);
    8110             :         }
    8111       18391 :         if (isa<SCEVAddExpr>(Comm))
    8112        4242 :           return getAddExpr(NewOps);
    8113       14149 :         if (isa<SCEVMulExpr>(Comm))
    8114       14142 :           return getMulExpr(NewOps);
    8115           7 :         if (isa<SCEVSMaxExpr>(Comm))
    8116           4 :           return getSMaxExpr(NewOps);
    8117           3 :         if (isa<SCEVUMaxExpr>(Comm))
    8118           3 :           return getUMaxExpr(NewOps);
    8119           0 :         llvm_unreachable("Unknown commutative SCEV type!");
    8120             :       }
    8121             :     }
    8122             :     // If we got here, all operands are loop invariant.
    8123             :     return Comm;
    8124             :   }
    8125             : 
    8126             :   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
    8127        2071 :     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
    8128        2071 :     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
    8129        2071 :     if (LHS == Div->getLHS() && RHS == Div->getRHS())
    8130             :       return Div;   // must be loop invariant
    8131           8 :     return getUDivExpr(LHS, RHS);
    8132             :   }
    8133             : 
    8134             :   // If this is a loop recurrence for a loop that does not contain L, then we
    8135             :   // are dealing with the final value computed by the loop.
    8136             :   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
    8137             :     // First, attempt to evaluate each operand.
    8138             :     // Avoid performing the look-up in the common case where the specified
    8139             :     // expression has no loop-variant portions.
    8140      130473 :     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
    8141      176854 :       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
    8142      176854 :       if (OpAtScope == AddRec->getOperand(i))
    8143       85047 :         continue;
    8144             : 
    8145             :       // Okay, at least one of these operands is loop variant but might be
    8146             :       // foldable.  Build a new instance of the folded commutative expression.
    8147             :       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
    8148             :                                           AddRec->op_begin()+i);
    8149        3380 :       NewOps.push_back(OpAtScope);
    8150       10232 :       for (++i; i != e; ++i)
    8151       13704 :         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
    8152             : 
    8153             :       const SCEV *FoldedRec =
    8154        6760 :         getAddRecExpr(NewOps, AddRec->getLoop(),
    8155        3380 :                       AddRec->getNoWrapFlags(SCEV::FlagNW));
    8156             :       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
    8157             :       // The addrec may be folded to a nonrecurrence, for example, if the
    8158             :       // induction variable is multiplied by zero after constant folding. Go
    8159             :       // ahead and return the folded value.
    8160             :       if (!AddRec)
    8161             :         return FoldedRec;
    8162             :       break;
    8163             :     }
    8164             : 
    8165             :     // If the scope is outside the addrec's loop, evaluate it by using the
    8166             :     // loop exit value of the addrec.
    8167       88832 :     if (!AddRec->getLoop()->contains(L)) {
    8168             :       // To evaluate this recurrence, we need to know how many times the AddRec
    8169             :       // loop iterates.  Compute this now.
    8170        4395 :       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
    8171        4395 :       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
    8172             : 
    8173             :       // Then, evaluate the AddRec.
    8174        3902 :       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
    8175             :     }
    8176             : 
    8177             :     return AddRec;
    8178             :   }
    8179             : 
    8180             :   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
    8181        1932 :     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
    8182        1932 :     if (Op == Cast->getOperand())
    8183             :       return Cast;  // must be loop invariant
    8184          21 :     return getZeroExtendExpr(Op, Cast->getType());
    8185             :   }
    8186             : 
    8187             :   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
    8188        1879 :     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
    8189        1879 :     if (Op == Cast->getOperand())
    8190             :       return Cast;  // must be loop invariant
    8191          43 :     return getSignExtendExpr(Op, Cast->getType());
    8192             :   }
    8193             : 
    8194             :   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
    8195        1350 :     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
    8196        1350 :     if (Op == Cast->getOperand())
    8197             :       return Cast;  // must be loop invariant
    8198           9 :     return getTruncateExpr(Op, Cast->getType());
    8199             :   }
    8200             : 
    8201           0 :   llvm_unreachable("Unknown SCEV type!");
    8202             : }
    8203             : 
    8204      206816 : const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
    8205      206816 :   return getSCEVAtScope(getSCEV(V), L);
    8206             : }
    8207             : 
    8208        8033 : const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
    8209             :   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
    8210          47 :     return stripInjectiveFunctions(ZExt->getOperand());
    8211             :   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
    8212           0 :     return stripInjectiveFunctions(SExt->getOperand());
    8213             :   return S;
    8214             : }
    8215             : 
    8216             : /// Finds the minimum unsigned root of the following equation:
    8217             : ///
    8218             : ///     A * X = B (mod N)
    8219             : ///
    8220             : /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
    8221             : /// A and B isn't important.
    8222             : ///
    8223             : /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
    8224        1677 : static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
    8225             :                                                ScalarEvolution &SE) {
    8226        1677 :   uint32_t BW = A.getBitWidth();
    8227             :   assert(BW == SE.getTypeSizeInBits(B->getType()));
    8228             :   assert(A != 0 && "A must be non-zero.");
    8229             : 
    8230             :   // 1. D = gcd(A, N)
    8231             :   //
    8232             :   // The gcd of A and N may have only one prime factor: 2. The number of
    8233             :   // trailing zeros in A is its multiplicity
    8234        1677 :   uint32_t Mult2 = A.countTrailingZeros();
    8235             :   // D = 2^Mult2
    8236             : 
    8237             :   // 2. Check if B is divisible by D.
    8238             :   //
    8239             :   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
    8240             :   // is not less than multiplicity of this prime factor for D.
    8241        1677 :   if (SE.GetMinTrailingZeros(B) < Mult2)
    8242        1508 :     return SE.getCouldNotCompute();
    8243             : 
    8244             :   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
    8245             :   // modulo (N / D).
    8246             :   //
    8247             :   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
    8248             :   // (N / D) in general. The inverse itself always fits into BW bits, though,
    8249             :   // so we immediately truncate it.
    8250         338 :   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
    8251             :   APInt Mod(BW + 1, 0);
    8252         169 :   Mod.setBit(BW - Mult2);  // Mod = N / D
    8253         338 :   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
    8254             : 
    8255             :   // 4. Compute the minimum unsigned root of the equation:
    8256             :   // I * (B / D) mod (N / D)
    8257             :   // To simplify the computation, we factor out the divide by D:
    8258             :   // (I * B mod N) / D
    8259         338 :   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
    8260         169 :   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
    8261             : }
    8262             : 
    8263             : /// Find the roots of the quadratic equation for the given quadratic chrec
    8264             : /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
    8265             : /// two SCEVCouldNotCompute objects.
    8266             : static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
    8267          24 : SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
    8268             :   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
    8269          24 :   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
    8270             :   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
    8271             :   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
    8272             : 
    8273             :   // We currently can only solve this if the coefficients are constants.
    8274          24 :   if (!LC || !MC || !NC)
    8275             :     return None;
    8276             : 
    8277          24 :   uint32_t BitWidth = LC->getAPInt().getBitWidth();
    8278             :   const APInt &L = LC->getAPInt();
    8279             :   const APInt &M = MC->getAPInt();
    8280             :   const APInt &N = NC->getAPInt();
    8281             :   APInt Two(BitWidth, 2);
    8282             : 
    8283             :   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
    8284             : 
    8285             :   // The A coefficient is N/2
    8286          24 :   APInt A = N.sdiv(Two);
    8287             : 
    8288             :   // The B coefficient is M-N/2
    8289             :   APInt B = M;
    8290          24 :   B -= A; // A is the same as N/2.
    8291             : 
    8292             :   // The C coefficient is L.
    8293             :   const APInt& C = L;
    8294             : 
    8295             :   // Compute the B^2-4ac term.
    8296             :   APInt SqrtTerm = B;
    8297          24 :   SqrtTerm *= B;
    8298          96 :   SqrtTerm -= 4 * (A * C);
    8299             : 
    8300          48 :   if (SqrtTerm.isNegative()) {
    8301             :     // The loop is provably infinite.
    8302             :     return None;
    8303             :   }
    8304             : 
    8305             :   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
    8306             :   // integer value or else APInt::sqrt() will assert.
    8307          21 :   APInt SqrtVal = SqrtTerm.sqrt();
    8308             : 
    8309             :   // Compute the two solutions for the quadratic formula.
    8310             :   // The divisions must be performed as signed divisions.
    8311          21 :   APInt NegB = -std::move(B);
    8312             :   APInt TwoA = std::move(A);
    8313          21 :   TwoA <<= 1;
    8314          21 :   if (TwoA.isNullValue())
    8315             :     return None;
    8316             : 
    8317          12 :   LLVMContext &Context = SE.getContext();
    8318             : 
    8319             :   ConstantInt *Solution1 =
    8320          48 :     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
    8321             :   ConstantInt *Solution2 =
    8322          48 :     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
    8323             : 
    8324          12 :   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
    8325          12 :                         cast<SCEVConstant>(SE.getConstant(Solution2)));
    8326             : }
    8327             : 
    8328             : ScalarEvolution::ExitLimit
    8329        8045 : ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
    8330             :                               bool AllowPredicates) {
    8331             : 
    8332             :   // This is only used for loops with a "x != y" exit test. The exit condition
    8333             :   // is now expressed as a single expression, V = x-y. So the exit test is
    8334             :   // effectively V != 0.  We know and take advantage of the fact that this
    8335             :   // expression only being used in a comparison by zero context.
    8336             : 
    8337             :   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
    8338             :   // If the value is a constant
    8339             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
    8340             :     // If the value is already zero, the branch will execute zero times.
    8341          24 :     if (C->getValue()->isZero()) return C;
    8342           0 :     return getCouldNotCompute();  // Otherwise it will loop infinitely.
    8343             :   }
    8344             : 
    8345             :   const SCEVAddRecExpr *AddRec =
    8346        8033 :       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
    8347             : 
    8348        8033 :   if (!AddRec && AllowPredicates)
    8349             :     // Try to make this an AddRec using runtime tests, in the first X
    8350             :     // iterations of this loop, where X is the SCEV expression found by the
    8351             :     // algorithm below.
    8352         142 :     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
    8353             : 
    8354        8033 :   if (!AddRec || AddRec->getLoop() != L)
    8355        2584 :     return getCouldNotCompute();
    8356             : 
    8357             :   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
    8358             :   // the quadratic equation to solve it.
    8359        5458 :   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
    8360           9 :     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
    8361           3 :       const SCEVConstant *R1 = Roots->first;
    8362           3 :       const SCEVConstant *R2 = Roots->second;
    8363             :       // Pick the smallest positive root value.
    8364           3 :       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
    8365           3 :               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
    8366           3 :         if (!CB->getZExtValue())
    8367             :           std::swap(R1, R2); // R1 is the minimum root now.
    8368             : 
    8369             :         // We can only use this value if the chrec ends up with an exact zero
    8370             :         // value at this index.  When solving for "X*X != 5", for example, we
    8371             :         // should not accept a root of 2.
    8372           3 :         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
    8373           3 :         if (Val->isZero())
    8374             :           // We found a quadratic root!
    8375           0 :           return ExitLimit(R1, R1, false, Predicates);
    8376             :       }
    8377             :     }
    8378           9 :     return getCouldNotCompute();
    8379             :   }
    8380             : 
    8381             :   // Otherwise we can only handle this if it is affine.
    8382        5440 :   if (!AddRec->isAffine())
    8383           0 :     return getCouldNotCompute();
    8384             : 
    8385             :   // If this is an affine expression, the execution count of this branch is
    8386             :   // the minimum unsigned root of the following equation:
    8387             :   //
    8388             :   //     Start + Step*N = 0 (mod 2^BW)
    8389             :   //
    8390             :   // equivalent to:
    8391             :   //
    8392             :   //             Step*N = -Start (mod 2^BW)
    8393             :   //
    8394             :   // where BW is the common bit width of Start and Step.
    8395             : 
    8396             :   // Get the initial value for the loop.
    8397       10880 :   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
    8398       10880 :   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
    8399             : 
    8400             :   // For now we handle only constant steps.
    8401             :   //
    8402             :   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
    8403             :   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
    8404             :   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
    8405             :   // We have not yet seen any such cases.
    8406             :   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
    8407       10834 :   if (!StepC || StepC->getValue()->isZero())
    8408          26 :     return getCouldNotCompute();
    8409             : 
    8410             :   // For positive steps (counting up until unsigned overflow):
    8411             :   //   N = -Start/Step (as unsigned)
    8412             :   // For negative steps (counting down to zero):
    8413             :   //   N = Start/-Step
    8414             :   // First compute the unsigned distance from zero in the direction of Step.
    8415        5414 :   bool CountDown = StepC->getAPInt().isNegative();
    8416        5414 :   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
    8417             : 
    8418             :   // Handle unitary steps, which cannot wraparound.
    8419             :   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
    8420             :   //   N = Distance (as unsigned)
    8421       13665 :   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
    8422             :     APInt MaxBECount = getUnsignedRangeMax(Distance);
    8423             : 
    8424             :     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
    8425             :     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
    8426             :     // case, and see if we can improve the bound.
    8427             :     //
    8428             :     // Explicitly handling this here is necessary because getUnsignedRange
    8429             :     // isn't context-sensitive; it doesn't know that we only care about the
    8430             :     // range inside the loop.
    8431        3247 :     const SCEV *Zero = getZero(Distance->getType());
    8432        3247 :     const SCEV *One = getOne(Distance->getType());
    8433        3247 :     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
    8434        3247 :     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
    8435             :       // If Distance + 1 doesn't overflow, we can compute the maximum distance
    8436             :       // as "unsigned_max(Distance + 1) - 1".
    8437        1980 :       ConstantRange CR = getUnsignedRange(DistancePlusOne);
    8438        7920 :       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
    8439             :     }
    8440        3247 :     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
    8441             :   }
    8442             : 
    8443             :   // If the condition controls loop exit (the loop exits only if the expression
    8444             :   // is true) and the addition is no-wrap we can use unsigned divide to
    8445             :   // compute the backedge count.  In this case, the step may not divide the
    8446             :   // distance, but we don't care because if the condition is "missed" the loop
    8447             :   // will have undefined behavior due to wrapping.
    8448        5465 :   if (ControlsExit && AddRec->hasNoSelfWrap() &&
    8449        1359 :       loopHasNoAbnormalExits(AddRec->getLoop())) {
    8450             :     const SCEV *Exact =
    8451         490 :         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
    8452             :     const SCEV *Max =
    8453         490 :         Exact == getCouldNotCompute()
    8454         980 :             ? Exact
    8455         490 :             : getConstant(getUnsignedRangeMax(Exact));
    8456         490 :     return ExitLimit(Exact, Max, false, Predicates);
    8457             :   }
    8458             : 
    8459             :   // Solve the general equation.
    8460        1677 :   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
    8461        1677 :                                                getNegativeSCEV(Start), *this);
    8462        1677 :   const SCEV *M = E == getCouldNotCompute()
    8463        1846 :                       ? E
    8464        1677 :                       : getConstant(getUnsignedRangeMax(E));
    8465        1677 :   return ExitLimit(E, M, false, Predicates);
    8466             : }
    8467             : 
    8468             : ScalarEvolution::ExitLimit
    8469        1197 : ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
    8470             :   // Loops that look like: while (X == 0) are very strange indeed.  We don't
    8471             :   // handle them yet except for the trivial case.  This could be expanded in the
    8472             :   // future as needed.
    8473             : 
    8474             :   // If the value is a constant, check to see if it is known to be non-zero
    8475             :   // already.  If so, the backedge will execute zero times.
    8476             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
    8477          44 :     if (!C->getValue()->isZero())
    8478           0 :       return getZero(C->getType());
    8479          22 :     return getCouldNotCompute();  // Otherwise it will loop infinitely.
    8480             :   }
    8481             : 
    8482             :   // We could implement others, but I really doubt anyone writes loops like
    8483             :   // this, and if they did, they would already be constant folded.
    8484        1175 :   return getCouldNotCompute();
    8485             : }
    8486             : 
    8487             : std::pair<BasicBlock *, BasicBlock *>
    8488       47301 : ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
    8489             :   // If the block has a unique predecessor, then there is no path from the
    8490             :   // predecessor to the block that does not go through the direct edge
    8491             :   // from the predecessor to the block.
    8492       47301 :   if (BasicBlock *Pred = BB->getSinglePredecessor())
    8493       23848 :     return {Pred, BB};
    8494             : 
    8495             :   // A loop's header is defined to be a block that dominates the loop.
    8496             :   // If the header has a unique predecessor outside the loop, it must be
    8497             :   // a block that has exactly one successor that can reach the loop.
    8498       31687 :   if (Loop *L = LI.getLoopFor(BB))
    8499       16468 :     return {L->getLoopPredecessor(), L->getHeader()};
    8500             : 
    8501       15219 :   return {nullptr, nullptr};
    8502             : }
    8503             : 
    8504             : /// SCEV structural equivalence is usually sufficient for testing whether two
    8505             : /// expressions are equal, however for the purposes of looking for a condition
    8506             : /// guarding a loop, it can be useful to be a little more general, since a
    8507             : /// front-end may have replicated the controlling expression.
    8508      471436 : static bool HasSameValue(const SCEV *A, const SCEV *B) {
    8509             :   // Quick check to see if they are the same SCEV.
    8510      471436 :   if (A == B) return true;
    8511             : 
    8512        6169 :   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
    8513             :     // Not all instructions that are "identical" compute the same value.  For
    8514             :     // instance, two distinct alloca instructions allocating the same type are
    8515             :     // identical and do not read memory; but compute distinct values.
    8516        6244 :     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
    8517        6169 :   };
    8518             : 
    8519             :   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
    8520             :   // two different instructions with the same value. Check for this case.
    8521       67407 :   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
    8522       10768 :     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
    8523             :       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
    8524             :         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
    8525        6169 :           if (ComputesEqualValues(AI, BI))
    8526             :             return true;
    8527             : 
    8528             :   // Otherwise assume they may have a different value.
    8529             :   return false;
    8530             : }
    8531             : 
    8532      250564 : bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
    8533             :                                            const SCEV *&LHS, const SCEV *&RHS,
    8534             :                                            unsigned Depth) {
    8535             :   bool Changed = false;
    8536             : 
    8537             :   // If we hit the max recursion limit bail out.
    8538      250564 :   if (Depth >= 3)
    8539             :     return false;
    8540             : 
    8541             :   // Canonicalize a constant to the right side.
    8542      250564 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
    8543             :     // Check for both operands constant.
    8544       23212 :     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
    8545       19580 :       if (ConstantExpr::getICmp(Pred,
    8546        9790 :                                 LHSC->getValue(),
    8547       19580 :                                 RHSC->getValue())->isNullValue())
    8548             :         goto trivially_false;
    8549             :       else
    8550             :         goto trivially_true;
    8551             :     }
    8552             :     // Otherwise swap the operands to put the constant on the right.
    8553             :     std::swap(LHS, RHS);
    8554       13422 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    8555             :     Changed = true;
    8556             :   }
    8557             : 
    8558             :   // If we're comparing an addrec with a value which is loop-invariant in the
    8559             :   // addrec's loop, put the addrec on the left. Also make a dominance check,
    8560             :   // as both operands could be addrecs loop-invariant in each other's loop.
    8561      240774 :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
    8562        1416 :     const Loop *L = AR->getLoop();
    8563        1620 :     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
    8564             :       std::swap(LHS, RHS);
    8565         204 :       Pred = ICmpInst::getSwappedPredicate(Pred);
    8566             :       Changed = true;
    8567             :     }
    8568             :   }
    8569             : 
    8570             :   // If there's a constant operand, canonicalize comparisons with boundary
    8571             :   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
    8572      240774 :   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
    8573             :     const APInt &RA = RC->getAPInt();
    8574             : 
    8575             :     bool SimplifiedByConstantRange = false;
    8576             : 
    8577      384326 :     if (!ICmpInst::isEquality(Pred)) {
    8578      243966 :       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
    8579      122048 :       if (ExactCR.isFullSet())
    8580             :         goto trivially_true;
    8581      122039 :       else if (ExactCR.isEmptySet())
    8582             :         goto trivially_false;
    8583             : 
    8584             :       APInt NewRHS;
    8585             :       CmpInst::Predicate NewPred;
    8586      243836 :       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
    8587      121918 :           ICmpInst::isEquality(NewPred)) {
    8588             :         // We were able to convert an inequality to an equality.
    8589       22093 :         Pred = NewPred;
    8590       22093 :         RHS = getConstant(NewRHS);
    8591             :         Changed = SimplifiedByConstantRange = true;
    8592             :       }
    8593             :     }
    8594             : 
    8595      192033 :     if (!SimplifiedByConstantRange) {
    8596      169940 :       switch (Pred) {
    8597             :       default:
    8598             :         break;
    8599             :       case ICmpInst::ICMP_EQ:
    8600             :       case ICmpInst::ICMP_NE:
    8601             :         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
    8602       70115 :         if (!RA)
    8603       28781 :           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
    8604             :             if (const SCEVMulExpr *ME =
    8605        4350 :                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
    8606        1300 :               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
    8607        1200 :                   ME->getOperand(0)->isAllOnesValue()) {
    8608        1034 :                 RHS = AE->getOperand(1);
    8609        1034 :                 LHS = ME->getOperand(1);
    8610             :                 Changed = true;
    8611             :               }
    8612             :         break;
    8613             : 
    8614             : 
    8615             :         // The "Should have been caught earlier!" messages refer to the fact
    8616             :         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
    8617             :         // should have fired on the corresponding cases, and canonicalized the
    8618             :         // check to trivially_true or trivially_false.
    8619             : 
    8620        3766 :       case ICmpInst::ICMP_UGE:
    8621             :         assert(!RA.isMinValue() && "Should have been caught earlier!");
    8622        3766 :         Pred = ICmpInst::ICMP_UGT;
    8623       11298 :         RHS = getConstant(RA - 1);
    8624             :         Changed = true;
    8625        3766 :         break;
    8626        2380 :       case ICmpInst::ICMP_ULE:
    8627             :         assert(!RA.isMaxValue() && "Should have been caught earlier!");
    8628        2380 :         Pred = ICmpInst::ICMP_ULT;
    8629        7140 :         RHS = getConstant(RA + 1);
    8630             :         Changed = true;
    8631        2380 :         break;
    8632        8971 :       case ICmpInst::ICMP_SGE:
    8633             :         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
    8634        8971 :         Pred = ICmpInst::ICMP_SGT;
    8635       26913 :         RHS = getConstant(RA - 1);
    8636             :         Changed = true;
    8637        8971 :         break;
    8638        4926 :       case ICmpInst::ICMP_SLE:
    8639             :         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
    8640        4926 :         Pred = ICmpInst::ICMP_SLT;
    8641       14778 :         RHS = getConstant(RA + 1);
    8642             :         Changed = true;
    8643        4926 :         break;
    8644             :       }
    8645             :     }
    8646             :   }
    8647             : 
    8648             :   // Check for obvious equality.
    8649      240644 :   if (HasSameValue(LHS, RHS)) {
    8650         222 :     if (ICmpInst::isTrueWhenEqual(Pred))
    8651             :       goto trivially_true;
    8652          26 :     if (ICmpInst::isFalseWhenEqual(Pred))
    8653             :       goto trivially_false;
    8654             :   }
    8655             : 
    8656             :   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
    8657             :   // adding or subtracting 1 from one of the operands.
    8658      240422 :   switch (Pred) {
    8659        1765 :   case ICmpInst::ICMP_SLE:
    8660        5295 :     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
    8661         427 :       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
    8662             :                        SCEV::FlagNSW);
    8663         427 :       Pred = ICmpInst::ICMP_SLT;
    8664             :       Changed = true;
    8665        4014 :     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
    8666          78 :       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
    8667             :                        SCEV::FlagNSW);
    8668          78 :       Pred = ICmpInst::ICMP_SLT;
    8669             :       Changed = true;
    8670             :     }
    8671             :     break;
    8672        2694 :   case ICmpInst::ICMP_SGE:
    8673        8082 :     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
    8674         379 :       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
    8675             :                        SCEV::FlagNSW);
    8676         379 :       Pred = ICmpInst::ICMP_SGT;
    8677             :       Changed = true;
    8678        6945 :     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
    8679         161 :       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
    8680             :                        SCEV::FlagNSW);
    8681         161 :       Pred = ICmpInst::ICMP_SGT;
    8682             :       Changed = true;
    8683             :     }
    8684             :     break;
    8685        1305 :   case ICmpInst::ICMP_ULE:
    8686        2610 :     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
    8687         484 :       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
    8688             :                        SCEV::FlagNUW);
    8689         484 :       Pred = ICmpInst::ICMP_ULT;
    8690             :       Changed = true;
    8691        1642 :     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
    8692          34 :       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
    8693          34 :       Pred = ICmpInst::ICMP_ULT;
    8694             :       Changed = true;
    8695             :     }
    8696             :     break;
    8697        2770 :   case ICmpInst::ICMP_UGE:
    8698        5540 :     if (!getUnsignedRangeMin(RHS).isMinValue()) {
    8699          87 :       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
    8700          87 :       Pred = ICmpInst::ICMP_UGT;
    8701             :       Changed = true;
    8702        5366 :     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
    8703         880 :       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
    8704             :                        SCEV::FlagNUW);
    8705         880 :       Pred = ICmpInst::ICMP_UGT;
    8706             :       Changed = true;
    8707             :     }
    8708             :     break;
    8709             :   default:
    8710             :     break;
    8711             :   }
    8712             : 
    8713             :   // TODO: More simplifications are possible here.
    8714             : 
    8715             :   // Recursively simplify until we either hit a recursion limit or nothing
    8716             :   // changes.
    8717      237892 :   if (Changed)
    8718       51574 :     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
    8719             : 
    8720             :   return Changed;
    8721             : 
    8722        2100 : trivially_true:
    8723             :   // Return 0 == 0.
    8724        4218 :   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
    8725        2109 :   Pred = ICmpInst::ICMP_EQ;
    8726        2109 :   return true;
    8727             : 
    8728        7912 : trivially_false:
    8729             :   // Return 0 != 0.
    8730       16066 :   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
    8731        8033 :   Pred = ICmpInst::ICMP_NE;
    8732        8033 :   return true;
    8733             : }
    8734             : 
    8735       32854 : bool ScalarEvolution::isKnownNegative(const SCEV *S) {
    8736       65708 :   return getSignedRangeMax(S).isNegative();
    8737             : }
    8738             : 
    8739       51396 : bool ScalarEvolution::isKnownPositive(const SCEV *S) {
    8740      102792 :   return getSignedRangeMin(S).isStrictlyPositive();
    8741             : }
    8742             : 
    8743     1418431 : bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
    8744     4255293 :   return !getSignedRangeMin(S).isNegative();
    8745             : }
    8746             : 
    8747      139905 : bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
    8748      279810 :   return !getSignedRangeMax(S).isStrictlyPositive();
    8749             : }
    8750             : 
    8751       17415 : bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
    8752       17415 :   return isKnownNegative(S) || isKnownPositive(S);
    8753             : }
    8754             : 
    8755             : std::pair<const SCEV *, const SCEV *>
    8756       25680 : ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
    8757             :   // Compute SCEV on entry of loop L.
    8758       25680 :   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
    8759       25680 :   if (Start == getCouldNotCompute())
    8760        1045 :     return { Start, Start };
    8761             :   // Compute post increment SCEV for loop L.
    8762       24635 :   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
    8763             :   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
    8764       24635 :   return { Start, PostInc };
    8765             : }
    8766             : 
    8767       27879 : bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
    8768             :                                           const SCEV *LHS, const SCEV *RHS) {
    8769             :   // First collect all loops.
    8770             :   SmallPtrSet<const Loop *, 8> LoopsUsed;
    8771       27879 :   getUsedLoops(LHS, LoopsUsed);
    8772       27879 :   getUsedLoops(RHS, LoopsUsed);
    8773             : 
    8774       27879 :   if (LoopsUsed.empty())
    8775             :     return false;
    8776             : 
    8777             :   // Domination relationship must be a linear order on collected loops.
    8778             : #ifndef NDEBUG
    8779             :   for (auto *L1 : LoopsUsed)
    8780             :     for (auto *L2 : LoopsUsed)
    8781             :       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
    8782             :               DT.dominates(L2->getHeader(), L1->getHeader())) &&
    8783             :              "Domination relationship is not a linear order");
    8784             : #endif
    8785             : 
    8786             :   const Loop *MDL =
    8787       12932 :       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
    8788             :                         [&](const Loop *L1, const Loop *L2) {
    8789         335 :          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
    8790       13267 :        });
    8791             : 
    8792             :   // Get init and post increment value for LHS.
    8793       12932 :   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
    8794             :   // if LHS contains unknown non-invariant SCEV then bail out.
    8795       12932 :   if (SplitLHS.first == getCouldNotCompute())
    8796             :     return false;
    8797             :   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
    8798             :   // Get init and post increment value for RHS.
    8799       12748 :   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
    8800             :   // if RHS contains unknown non-invariant SCEV then bail out.
    8801       12748 :   if (SplitRHS.first == getCouldNotCompute())
    8802             :     return false;
    8803             :   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
    8804             :   // It is possible that init SCEV contains an invariant load but it does
    8805             :   // not dominate MDL and is not available at MDL loop entry, so we should
    8806             :   // check it here.
    8807       23774 :   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
    8808       11887 :       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
    8809             :     return false;
    8810             : 
    8811       17304 :   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
    8812        5417 :          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
    8813             :                                      SplitRHS.second);
    8814             : }
    8815             : 
    8816       27879 : bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
    8817             :                                        const SCEV *LHS, const SCEV *RHS) {
    8818             :   // Canonicalize the inputs first.
    8819       27879 :   (void)SimplifyICmpOperands(Pred, LHS, RHS);
    8820             : 
    8821       27879 :   if (isKnownViaInduction(Pred, LHS, RHS))
    8822             :     return true;
    8823             : 
    8824       26040 :   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
    8825             :     return true;
    8826             : 
    8827             :   // Otherwise see what can be done with some simple reasoning.
    8828       26022 :   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
    8829             : }
    8830             : 
    8831        9394 : bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
    8832             :                                               const SCEVAddRecExpr *LHS,
    8833             :                                               const SCEV *RHS) {
    8834        9394 :   const Loop *L = LHS->getLoop();
    8835       23146 :   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
    8836       13752 :          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
    8837             : }
    8838             : 
    8839         749 : bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
    8840             :                                            ICmpInst::Predicate Pred,
    8841             :                                            bool &Increasing) {
    8842         749 :   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
    8843             : 
    8844             : #ifndef NDEBUG
    8845             :   // Verify an invariant: inverting the predicate should turn a monotonically
    8846             :   // increasing change to a monotonically decreasing one, and vice versa.
    8847             :   bool IncreasingSwapped;
    8848             :   bool ResultSwapped = isMonotonicPredicateImpl(
    8849             :       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
    8850             : 
    8851             :   assert(Result == ResultSwapped && "should be able to analyze both!");
    8852             :   if (ResultSwapped)
    8853             :     assert(Increasing == !IncreasingSwapped &&
    8854             :            "monotonicity should flip as we flip the predicate");
    8855             : #endif
    8856             : 
    8857         749 :   return Result;
    8858             : }
    8859             : 
    8860         749 : bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
    8861             :                                                ICmpInst::Predicate Pred,
    8862             :                                                bool &Increasing) {
    8863             : 
    8864             :   // A zero step value for LHS means the induction variable is essentially a
    8865             :   // loop invariant value. We don't really depend on the predicate actually
    8866             :   // flipping from false to true (for increasing predicates, and the other way
    8867             :   // around for decreasing predicates), all we care about is that *if* the
    8868             :   // predicate changes then it only changes from false to true.
    8869             :   //
    8870             :   // A zero step value in itself is not very useful, but there may be places
    8871             :   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
    8872             :   // as general as possible.
    8873             : 
    8874         749 :   switch (Pred) {
    8875             :   default:
    8876             :     return false; // Conservative answer
    8877             : 
    8878         256 :   case ICmpInst::ICMP_UGT:
    8879             :   case ICmpInst::ICMP_UGE:
    8880             :   case ICmpInst::ICMP_ULT:
    8881             :   case ICmpInst::ICMP_ULE:
    8882         256 :     if (!LHS->hasNoUnsignedWrap())
    8883             :       return false;
    8884             : 
    8885         148 :     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
    8886         148 :     return true;
    8887             : 
    8888         237 :   case ICmpInst::ICMP_SGT:
    8889             :   case ICmpInst::ICMP_SGE:
    8890             :   case ICmpInst::ICMP_SLT:
    8891             :   case ICmpInst::ICMP_SLE: {
    8892         237 :     if (!LHS->hasNoSignedWrap())
    8893             :       return false;
    8894             : 
    8895         224 :     const SCEV *Step = LHS->getStepRecurrence(*this);
    8896             : 
    8897         224 :     if (isKnownNonNegative(Step)) {
    8898          70 :       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
    8899          70 :       return true;
    8900             :     }
    8901             : 
    8902         154 :     if (isKnownNonPositive(Step)) {
    8903         152 :       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
    8904         152 :       return true;
    8905             :     }
    8906             : 
    8907             :     return false;
    8908             :   }
    8909             : 
    8910             :   }
    8911             : 
    8912             :   llvm_unreachable("switch has default clause!");
    8913             : }
    8914             : 
    8915        1262 : bool ScalarEvolution::isLoopInvariantPredicate(
    8916             :     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
    8917             :     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
    8918             :     const SCEV *&InvariantRHS) {
    8919             : 
    8920             :   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
    8921        1262 :   if (!isLoopInvariant(RHS, L)) {
    8922         402 :     if (!isLoopInvariant(LHS, L))
    8923             :       return false;
    8924             : 
    8925             :     std::swap(LHS, RHS);
    8926           1 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    8927             :   }
    8928             : 
    8929             :   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
    8930         671 :   if (!ArLHS || ArLHS->getLoop() != L)
    8931             :     return false;
    8932             : 
    8933             :   bool Increasing;
    8934         671 :   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
    8935             :     return false;
    8936             : 
    8937             :   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
    8938             :   // true as the loop iterates, and the backedge is control dependent on
    8939             :   // "ArLHS `Pred` RHS" == true then we can reason as follows:
    8940             :   //
    8941             :   //   * if the predicate was false in the first iteration then the predicate
    8942             :   //     is never evaluated again, since the loop exits without taking the
    8943             :   //     backedge.
    8944             :   //   * if the predicate was true in the first iteration then it will
    8945             :   //     continue to be true for all future iterations since it is
    8946             :   //     monotonically increasing.
    8947             :   //
    8948             :   // For both the above possibilities, we can replace the loop varying
    8949             :   // predicate with its value on the first iteration of the loop (which is
    8950             :   // loop invariant).
    8951             :   //
    8952             :   // A similar reasoning applies for a monotonically decreasing predicate, by
    8953             :   // replacing true with false and false with true in the above two bullets.
    8954             : 
    8955         356 :   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
    8956             : 
    8957         356 :   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
    8958             :     return false;
    8959             : 
    8960          11 :   InvariantPred = Pred;
    8961          22 :   InvariantLHS = ArLHS->getStart();
    8962          11 :   InvariantRHS = RHS;
    8963          11 :   return true;
    8964             : }
    8965             : 
    8966      205366 : bool ScalarEvolution::isKnownPredicateViaConstantRanges(
    8967             :     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
    8968      205366 :   if (HasSameValue(LHS, RHS))
    8969       16358 :     return ICmpInst::isTrueWhenEqual(Pred);
    8970             : 
    8971             :   // This code is split out from isKnownPredicate because it is called from
    8972             :   // within isLoopEntryGuardedByCond.
    8973             : 
    8974             :   auto CheckRanges =
    8975      202947 :       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
    8976      405894 :     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
    8977             :         .contains(RangeLHS);
    8978      594902 :   };
    8979             : 
    8980             :   // The check at the top of the function catches the case where the values are
    8981             :   // known to be equal.
    8982      189008 :   if (Pred == CmpInst::ICMP_EQ)
    8983             :     return false;
    8984             : 
    8985      185465 :   if (Pred == CmpInst::ICMP_NE)
    8986       58048 :     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
    8987       55144 :            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
    8988       17379 :            isKnownNonZero(getMinusSCEV(LHS, RHS));
    8989             : 
    8990      165182 :   if (CmpInst::isSigned(Pred))
    8991       81382 :     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
    8992             : 
    8993       83800 :   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
    8994             : }
    8995             : 
    8996      156318 : bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
    8997             :                                                     const SCEV *LHS,
    8998             :                                                     const SCEV *RHS) {
    8999             :   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
    9000             :   // Return Y via OutY.
    9001             :   auto MatchBinaryAddToConst =
    9002             :       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
    9003      134839 :              SCEV::NoWrapFlags ExpectedFlags) {
    9004             :     const SCEV *NonConstOp, *ConstOp;
    9005             :     SCEV::NoWrapFlags FlagsPresent;
    9006             : 
    9007      155877 :     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
    9008      153015 :         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
    9009             :       return false;
    9010             : 
    9011         951 :     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
    9012         951 :     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
    9013      156318 :   };
    9014             : 
    9015             :   APInt C;
    9016             : 
    9017      156318 :   switch (Pred) {
    9018             :   default:
    9019             :     break;
    9020             : 
    9021             :   case ICmpInst::ICMP_SGE:
    9022             :     std::swap(LHS, RHS);
    9023             :     LLVM_FALLTHROUGH;
    9024       35620 :   case ICmpInst::ICMP_SLE:
    9025             :     // X s<= (X + C)<nsw> if C >= 0
    9026       35791 :     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
    9027             :       return true;
    9028             : 
    9029             :     // (X + C)<nsw> s<= X if C <= 0
    9030       35631 :     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
    9031         112 :         !C.isStrictlyPositive())
    9032             :       return true;
    9033             :     break;
    9034             : 
    9035             :   case ICmpInst::ICMP_SGT:
    9036             :     std::swap(LHS, RHS);
    9037             :     LLVM_FALLTHROUGH;
    9038       31851 :   case ICmpInst::ICMP_SLT:
    9039             :     // X s< (X + C)<nsw> if C > 0
    9040       31853 :     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
    9041           2 :         C.isStrictlyPositive())
    9042             :       return true;
    9043             : 
    9044             :     // (X + C)<nsw> s< X if C < 0
    9045       31849 :     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
    9046             :       return true;
    9047             :     break;
    9048             :   }
    9049             : 
    9050             :   return false;
    9051             : }
    9052             : 
    9053       26040 : bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
    9054             :                                                    const SCEV *LHS,
    9055             :                                                    const SCEV *RHS) {
    9056       26040 :   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
    9057             :     return false;
    9058             : 
    9059             :   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
    9060             :   // the stack can result in exponential time complexity.
    9061        2102 :   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
    9062             : 
    9063             :   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
    9064             :   //
    9065             :   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
    9066             :   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
    9067             :   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
    9068             :   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
    9069             :   // use isKnownPredicate later if needed.
    9070        3568 :   return isKnownNonNegative(RHS) &&
    9071        4881 :          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
    9072        1313 :          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
    9073             : }
    9074             : 
    9075      141097 : bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
    9076             :                                         ICmpInst::Predicate Pred,
    9077             :                                         const SCEV *LHS, const SCEV *RHS) {
    9078             :   // No need to even try if we know the module has no guards.
    9079      141097 :   if (!HasGuards)
    9080             :     return false;
    9081             : 
    9082        5242 :   return any_of(*BB, [&](Instruction &I) {
    9083             :     using namespace llvm::PatternMatch;
    9084             : 
    9085             :     Value *Condition;
    9086        3686 :     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
    9087        3832 :                          m_Value(Condition))) &&
    9088        3832 :            isImpliedCond(Pred, LHS, RHS, Condition, false);
    9089        1556 :   });
    9090             : }
    9091             : 
    9092             : /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
    9093             : /// protected by a conditional between LHS and RHS.  This is used to
    9094             : /// to eliminate casts.
    9095             : bool
    9096       30011 : ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
    9097             :                                              ICmpInst::Predicate Pred,
    9098             :                                              const SCEV *LHS, const SCEV *RHS) {
    9099             :   // Interpret a null as meaning no loop, where there is obviously no guard
    9100             :   // (interprocedural conditions notwithstanding).
    9101       30011 :   if (!L) return true;
    9102             : 
    9103       30011 :   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
    9104             :     return true;
    9105             : 
    9106       18456 :   BasicBlock *Latch = L->getLoopLatch();
    9107       18456 :   if (!Latch)
    9108             :     return false;
    9109             : 
    9110             :   BranchInst *LoopContinuePredicate =
    9111             :     dyn_cast<BranchInst>(Latch->getTerminator());
    9112       35389 :   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
    9113       33912 :       isImpliedCond(Pred, LHS, RHS,
    9114             :                     LoopContinuePredicate->getCondition(),
    9115             :                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
    9116             :     return true;
    9117             : 
    9118             :   // We don't want more than one activation of the following loops on the stack
    9119             :   // -- that can lead to O(n!) time complexity.
    9120       17521 :   if (WalkingBEDominatingConds)
    9121             :     return false;
    9122             : 
    9123       15971 :   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
    9124             : 
    9125             :   // See if we can exploit a trip count to prove the predicate.
    9126       15971 :   const auto &BETakenInfo = getBackedgeTakenInfo(L);
    9127       15971 :   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
    9128       15971 :   if (LatchBECount != getCouldNotCompute()) {
    9129             :     // We know that Latch branches back to the loop header exactly
    9130             :     // LatchBECount times.  This means the backdege condition at Latch is
    9131             :     // equivalent to  "{0,+,1} u< LatchBECount".
    9132       13624 :     Type *Ty = LatchBECount->getType();
    9133             :     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
    9134             :     const SCEV *LoopCounter =
    9135       13624 :       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
    9136       13624 :     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
    9137             :                       LatchBECount))
    9138             :       return true;
    9139             :   }
    9140             : 
    9141             :   // Check conditions due to any @llvm.assume intrinsics.
    9142       38844 :   for (auto &AssumeVH : AC.assumptions()) {
    9143        3479 :     if (!AssumeVH)
    9144           0 :       continue;
    9145             :     auto *CI = cast<CallInst>(AssumeVH);
    9146        6958 :     if (!DT.dominates(CI, Latch->getTerminator()))
    9147           0 :       continue;
    9148             : 
    9149        6958 :     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
    9150             :       return true;
    9151             :   }
    9152             : 
    9153             :   // If the loop is not reachable from the entry block, we risk running into an
    9154             :   // infinite loop as we walk up into the dom tree.  These loops do not matter
    9155             :   // anyway, so we just return a conservative answer when we see them.
    9156       31886 :   if (!DT.isReachableFromEntry(L->getHeader()))
    9157             :     return false;
    9158             : 
    9159       15943 :   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
    9160             :     return true;
    9161             : 
    9162       52871 :   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
    9163       36941 :        DTN != HeaderDTN; DTN = DTN->getIDom()) {
    9164             :     assert(DTN && "should reach the loop header before reaching the root!");
    9165             : 
    9166       21056 :     BasicBlock *BB = DTN->getBlock();
    9167       21056 :     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
    9168          45 :       return true;
    9169             : 
    9170             :     BasicBlock *PBB = BB->getSinglePredecessor();
    9171       21056 :     if (!PBB)
    9172       27244 :       continue;
    9173             : 
    9174             :     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
    9175       11257 :     if (!ContinuePredicate || !ContinuePredicate->isConditional())
    9176        5576 :       continue;
    9177             : 
    9178             :     Value *Condition = ContinuePredicate->getCondition();
    9179             : 
    9180             :     // If we have an edge `E` within the loop body that dominates the only
    9181             :     // latch, the condition guarding `E` also guards the backedge.  This
    9182             :     // reasoning works only for loops with a single latch.
    9183             : 
    9184             :     BasicBlockEdge DominatingEdge(PBB, BB);
    9185        4646 :     if (DominatingEdge.isSingleEdge()) {
    9186             :       // We're constructively (and conservatively) enumerating edges within the
    9187             :       // loop body that dominate the latch.  The dominator tree better agree
    9188             :       // with us on this:
    9189             :       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
    9190             : 
    9191        4646 :       if (isImpliedCond(Pred, LHS, RHS, Condition,
    9192             :                         BB != ContinuePredicate->getSuccessor(0)))
    9193             :         return true;
    9194             :     }
    9195             :   }
    9196             : 
    9197             :   return false;
    9198             : }
    9199             : 
    9200             : bool
    9201       29102 : ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
    9202             :                                           ICmpInst::Predicate Pred,
    9203             :                                           const SCEV *LHS, const SCEV *RHS) {
    9204             :   // Interpret a null as meaning no loop, where there is obviously no guard
    9205             :   // (interprocedural conditions notwithstanding).
    9206       29102 :   if (!L) return false;
    9207             : 
    9208             :   // Both LHS and RHS must be available at loop entry.
    9209             :   assert(isAvailableAtLoopEntry(LHS, L) &&
    9210             :          "LHS is not available at Loop Entry");
    9211             :   assert(isAvailableAtLoopEntry(RHS, L) &&
    9212             :          "RHS is not available at Loop Entry");
    9213             : 
    9214       29102 :   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
    9215             :     return true;
    9216             : 
    9217             :   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
    9218             :   // the facts (a >= b && a != b) separately. A typical situation is when the
    9219             :   // non-strict comparison is known from ranges and non-equality is known from
    9220             :   // dominating predicates. If we are proving strict comparison, we always try
    9221             :   // to prove non-equality and non-strict comparison separately.
    9222       19300 :   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
    9223       19300 :   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
    9224       19300 :   bool ProvedNonStrictComparison = false;
    9225       19300 :   bool ProvedNonEquality = false;
    9226             : 
    9227       19300 :   if (ProvingStrictComparison) {
    9228       13293 :     ProvedNonStrictComparison =
    9229       13293 :         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
    9230       13293 :     ProvedNonEquality =
    9231       13293 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
    9232       13293 :     if (ProvedNonStrictComparison && ProvedNonEquality)
    9233             :       return true;
    9234             :   }
    9235             : 
    9236             :   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
    9237       51374 :   auto ProveViaGuard = [&](BasicBlock *Block) {
    9238      156822 :     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
    9239             :       return true;
    9240       51358 :     if (ProvingStrictComparison) {
    9241       75074 :       if (!ProvedNonStrictComparison)
    9242       21085 :         ProvedNonStrictComparison =
    9243       42170 :             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
    9244       53995 :       if (!ProvedNonEquality)
    9245       31639 :         ProvedNonEquality =
    9246       63278 :             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
    9247       53995 :       if (ProvedNonStrictComparison && ProvedNonEquality)
    9248             :         return true;
    9249             :     }
    9250             :     return false;
    9251       19296 :   };
    9252             : 
    9253             :   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
    9254       21895 :   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
    9255       60213 :     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
    9256             :       return true;
    9257       17894 :     if (ProvingStrictComparison) {
    9258       27072 :       if (!ProvedNonStrictComparison)
    9259        7579 :         ProvedNonStrictComparison =
    9260       15158 :             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
    9261       20008 :       if (!ProvedNonEquality)
    9262       11580 :         ProvedNonEquality =
    9263       23160 :             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
    9264       20008 :       if (ProvedNonStrictComparison && ProvedNonEquality)
    9265             :         return true;
    9266             :     }
    9267             :     return false;
    9268       19296 :   };
    9269             : 
    9270             :   // Starting at the loop predecessor, climb up the predecessor chain, as long
    9271             :   // as there are predecessors that can be found that have unique successors
    9272             :   // leading to the original header.
    9273       47301 :   for (std::pair<BasicBlock *, BasicBlock *>
    9274       19296 :          Pair(L->getLoopPredecessor(), L->getHeader());
    9275       66597 :        Pair.first;
    9276       94602 :        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
    9277             : 
    9278       51374 :     if (ProveViaGuard(Pair.first))
    9279             :       return true;
    9280             : 
    9281             :     BranchInst *LoopEntryPredicate =
    9282             :       dyn_cast<BranchInst>(Pair.first->getTerminator());
    9283       77930 :     if (!LoopEntryPredicate ||
    9284             :         LoopEntryPredicate->isUnconditional())
    9285       29504 :       continue;
    9286             : 
    9287       43708 :     if (ProveViaCond(LoopEntryPredicate->getCondition(),
    9288             :                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
    9289             :       return true;
    9290             :   }
    9291             : 
    9292             :   // Check conditions due to any @llvm.assume intrinsics.
    9293       50016 :   for (auto &AssumeVH : AC.assumptions()) {
    9294        9794 :     if (!AssumeVH)
    9295           0 :       continue;
    9296             :     auto *CI = cast<CallInst>(AssumeVH);
    9297       19588 :     if (!DT.dominates(CI, L->getHeader()))
    9298        9753 :       continue;
    9299             : 
    9300          82 :     if (ProveViaCond(CI->getArgOperand(0), false))
    9301             :       return true;
    9302             :   }
    9303             : 
    9304             :   return false;
    9305             : }
    9306             : 
    9307       67213 : bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
    9308             :                                     const SCEV *LHS, const SCEV *RHS,
    9309             :                                     Value *FoundCondValue,
    9310             :                                     bool Inverse) {
    9311       67213 :   if (!PendingLoopPredicates.insert(FoundCondValue).second)
    9312             :     return false;
    9313             : 
    9314             :   auto ClearOnExit =
    9315       64764 :       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
    9316             : 
    9317             :   // Recursively handle And and Or conditions.
    9318             :   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
    9319         829 :     if (BO->getOpcode() == Instruction::And) {
    9320         505 :       if (!Inverse)
    9321         741 :         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
    9322         351 :                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
    9323         324 :     } else if (BO->getOpcode() == Instruction::Or) {
    9324         286 :       if (Inverse)
    9325         191 :         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
    9326          94 :                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
    9327             :     }
    9328             :   }
    9329             : 
    9330             :   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
    9331             :   if (!ICI) return false;
    9332             : 
    9333             :   // Now that we found a conditional branch that dominates the loop or controls
    9334             :   // the loop latch. Check to see if it is the comparison we are looking for.
    9335             :   ICmpInst::Predicate FoundPred;
    9336       61615 :   if (Inverse)
    9337             :     FoundPred = ICI->getInversePredicate();
    9338             :   else
    9339             :     FoundPred = ICI->getPredicate();
    9340             : 
    9341       61615 :   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
    9342       61615 :   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
    9343             : 
    9344       61615 :   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
    9345             : }
    9346             : 
    9347       75239 : bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
    9348             :                                     const SCEV *RHS,
    9349             :                                     ICmpInst::Predicate FoundPred,
    9350             :                                     const SCEV *FoundLHS,
    9351             :                                     const SCEV *FoundRHS) {
    9352             :   // Balance the types.
    9353      150478 :   if (getTypeSizeInBits(LHS->getType()) <
    9354       75239 :       getTypeSizeInBits(FoundLHS->getType())) {
    9355       10545 :     if (CmpInst::isSigned(Pred)) {
    9356        1443 :       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
    9357        1443 :       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
    9358             :     } else {
    9359        9102 :       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
    9360        9102 :       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
    9361             :     }
    9362      129388 :   } else if (getTypeSizeInBits(LHS->getType()) >
    9363       64694 :       getTypeSizeInBits(FoundLHS->getType())) {
    9364        7207 :     if (CmpInst::isSigned(FoundPred)) {
    9365        3302 :       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
    9366        3302 :       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
    9367             :     } else {
    9368        3905 :       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
    9369        3905 :       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
    9370             :     }
    9371             :   }
    9372             : 
    9373             :   // Canonicalize the query to match the way instcombine will have
    9374             :   // canonicalized the comparison.
    9375       75239 :   if (SimplifyICmpOperands(Pred, LHS, RHS))
    9376        3532 :     if (LHS == RHS)
    9377        3532 :       return CmpInst::isTrueWhenEqual(Pred);
    9378       71707 :   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
    9379          39 :     if (FoundLHS == FoundRHS)
    9380          39 :       return CmpInst::isFalseWhenEqual(FoundPred);
    9381             : 
    9382             :   // Check to see if we can make the LHS or RHS match.
    9383       71668 :   if (LHS == FoundRHS || RHS == FoundLHS) {
    9384        1452 :     if (isa<SCEVConstant>(RHS)) {
    9385             :       std::swap(FoundLHS, FoundRHS);
    9386         409 :       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
    9387             :     } else {
    9388             :       std::swap(LHS, RHS);
    9389         317 :       Pred = ICmpInst::getSwappedPredicate(Pred);
    9390             :     }
    9391             :   }
    9392             : 
    9393             :   // Check whether the found predicate is the same as the desired predicate.
    9394       71668 :   if (FoundPred == Pred)
    9395       21673 :     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
    9396             : 
    9397             :   // Check whether swapping the found predicate makes it the same as the
    9398             :   // desired predicate.
    9399       49995 :   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
    9400        8766 :     if (isa<SCEVConstant>(RHS))
    9401        4091 :       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
    9402             :     else
    9403         292 :       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
    9404         292 :                                    RHS, LHS, FoundLHS, FoundRHS);
    9405             :   }
    9406             : 
    9407             :   // Unsigned comparison is the same as signed comparison when both the operands
    9408             :   // are non-negative.
    9409       65986 :   if (CmpInst::isUnsigned(FoundPred) &&
    9410       24587 :       CmpInst::getSignedPredicate(FoundPred) == Pred &&
    9411       53165 :       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
    9412        2842 :     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
    9413             : 
    9414             :   // Check if we can make progress by sharpening ranges.
    9415       53706 :   if (FoundPred == ICmpInst::ICMP_NE &&
    9416       32808 :       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
    9417             : 
    9418             :     const SCEVConstant *C = nullptr;
    9419             :     const SCEV *V = nullptr;
    9420             : 
    9421        8257 :     if (isa<SCEVConstant>(FoundLHS)) {
    9422             :       C = cast<SCEVConstant>(FoundLHS);
    9423           0 :       V = FoundRHS;
    9424             :     } else {
    9425        8257 :       C = cast<SCEVConstant>(FoundRHS);
    9426             :       V = FoundLHS;
    9427             :     }
    9428             : 
    9429             :     // The guarding predicate tells us that C != V. If the known range
    9430             :     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
    9431             :     // range we consider has to correspond to same signedness as the
    9432             :     // predicate we're interested in folding.
    9433             : 
    9434        8257 :     APInt Min = ICmpInst::isSigned(Pred) ?
    9435        8257 :         getSignedRangeMin(V) : getUnsignedRangeMin(V);
    9436             : 
    9437        8257 :     if (Min == C->getAPInt()) {
    9438             :       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
    9439             :       // This is true even if (Min + 1) wraps around -- in case of
    9440             :       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
    9441             : 
    9442        2622 :       APInt SharperMin = Min + 1;
    9443             : 
    9444        2622 :       switch (Pred) {
    9445          33 :         case ICmpInst::ICMP_SGE:
    9446             :         case ICmpInst::ICMP_UGE:
    9447             :           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
    9448             :           // RHS, we're done.
    9449          33 :           if (isImpliedCondOperands(Pred, LHS, RHS, V,
    9450             :                                     getConstant(SharperMin)))
    9451             :             return true;
    9452             :           LLVM_FALLTHROUGH;
    9453             : 
    9454             :         case ICmpInst::ICMP_SGT:
    9455             :         case ICmpInst::ICMP_UGT:
    9456             :           // We know from the range information that (V `Pred` Min ||
    9457             :           // V == Min).  We know from the guarding condition that !(V
    9458             :           // == Min).  This gives us
    9459             :           //
    9460             :           //       V `Pred` Min || V == Min && !(V == Min)
    9461             :           //   =>  V `Pred` Min
    9462             :           //
    9463             :           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
    9464             : 
    9465         929 :           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
    9466             :             return true;
    9467             :           LLVM_FALLTHROUGH;
    9468             : 
    9469             :         default:
    9470             :           // No change
    9471             :           break;
    9472             :       }
    9473             :     }
    9474             :   }
    9475             : 
    9476             :   // Check whether the actual condition is beyond sufficient.
    9477       42698 :   if (FoundPred == ICmpInst::ICMP_EQ)
    9478        5154 :     if (ICmpInst::isTrueWhenEqual(Pred))
    9479           6 :       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
    9480             :         return true;
    9481       42698 :   if (Pred == ICmpInst::ICMP_NE)
    9482       23689 :     if (!ICmpInst::isTrueWhenEqual(FoundPred))
    9483       19559 :       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
    9484             :         return true;
    9485             : 
    9486             :   // Otherwise assume the worst.
    9487             :   return false;
    9488             : }
    9489             : 
    9490      199038 : bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
    9491             :                                      const SCEV *&L, const SCEV *&R,
    9492             :                                      SCEV::NoWrapFlags &Flags) {
    9493             :   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
    9494       44048 :   if (!AE || AE->getNumOperands() != 2)
    9495             :     return false;
    9496             : 
    9497       75850 :   L = AE->getOperand(0);
    9498       37925 :   R = AE->getOperand(1);
    9499       75850 :   Flags = AE->getNoWrapFlags();
    9500       37925 :   return true;
    9501             : }
    9502             : 
    9503       59300 : Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
    9504             :                                                            const SCEV *Less) {
    9505             :   // We avoid subtracting expressions here because this function is usually
    9506             :   // fairly deep in the call stack (i.e. is called many times).
    9507             : 
    9508       88158 :   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
    9509             :     const auto *LAR = cast<SCEVAddRecExpr>(Less);
    9510             :     const auto *MAR = cast<SCEVAddRecExpr>(More);
    9511             : 
    9512       26171 :     if (LAR->getLoop() != MAR->getLoop())
    9513             :       return None;
    9514             : 
    9515             :     // We look at affine expressions only; not for correctness but to keep
    9516             :     // getStepRecurrence cheap.
    9517       52172 :     if (!LAR->isAffine() || !MAR->isAffine())
    9518             :       return None;
    9519             : 
    9520       26064 :     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
    9521             :       return None;
    9522             : 
    9523       20983 :     Less = LAR->getStart();
    9524       20983 :     More = MAR->getStart();
    9525             : 
    9526             :     // fall through
    9527             :   }
    9528             : 
    9529       79914 :   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
    9530             :     const auto &M = cast<SCEVConstant>(More)->getAPInt();
    9531             :     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
    9532       21732 :     return M - L;
    9533             :   }
    9534             : 
    9535             :   SCEV::NoWrapFlags Flags;
    9536       32380 :   const SCEV *LLess = nullptr, *RLess = nullptr;
    9537       32380 :   const SCEV *LMore = nullptr, *RMore = nullptr;
    9538             :   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
    9539             :   // Compare (X + C1) vs X.
    9540       32380 :   if (splitBinaryAdd(Less, LLess, RLess, Flags))
    9541        7638 :     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
    9542        6269 :       if (RLess == More)
    9543         561 :         return -(C1->getAPInt());
    9544             : 
    9545             :   // Compare X vs (X + C2).
    9546       31819 :   if (splitBinaryAdd(More, LMore, RMore, Flags))
    9547        9249 :     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
    9548        8722 :       if (RMore == Less)
    9549             :         return C2->getAPInt();
    9550             : 
    9551             :   // Compare (X + C1) vs (X + C2).
    9552       29674 :   if (C1 && C2 && RLess == RMore)
    9553        1727 :     return C2->getAPInt() - C1->getAPInt();
    9554             : 
    9555             :   return None;
    9556             : }
    9557             : 
    9558       48056 : bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
    9559             :     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
    9560             :     const SCEV *FoundLHS, const SCEV *FoundRHS) {
    9561       48056 :   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
    9562             :     return false;
    9563             : 
    9564             :   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
    9565             :   if (!AddRecLHS)
    9566             :     return false;
    9567             : 
    9568             :   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
    9569             :   if (!AddRecFoundLHS)
    9570             :     return false;
    9571             : 
    9572             :   // We'd like to let SCEV reason about control dependencies, so we constrain
    9573             :   // both the inequalities to be about add recurrences on the same loop.  This
    9574             :   // way we can use isLoopEntryGuardedByCond later.
    9575             : 
    9576       15466 :   const Loop *L = AddRecFoundLHS->getLoop();
    9577       15466 :   if (L != AddRecLHS->getLoop())
    9578             :     return false;
    9579             : 
    9580             :   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
    9581             :   //
    9582             :   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
    9583             :   //                                                                  ... (2)
    9584             :   //
    9585             :   // Informal proof for (2), assuming (1) [*]:
    9586             :   //
    9587             :   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
    9588             :   //
    9589             :   // Then
    9590             :   //
    9591             :   //       FoundLHS s< FoundRHS s< INT_MIN - C
    9592             :   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
    9593             :   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
    9594             :   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
    9595             :   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
    9596             :   // <=>  FoundLHS + C s< FoundRHS + C
    9597             :   //
    9598             :   // [*]: (1) can be proved by ruling out overflow.
    9599             :   //
    9600             :   // [**]: This can be proved by analyzing all the four possibilities:
    9601             :   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
    9602             :   //    (A s>= 0, B s>= 0).
    9603             :   //
    9604             :   // Note:
    9605             :   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
    9606             :   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
    9607             :   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
    9608             :   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
    9609             :   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
    9610             :   // C)".
    9611             : 
    9612       15030 :   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
    9613       15030 :   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
    9614       20260 :   if (!LDiff || !RDiff || *LDiff != *RDiff)
    9615             :     return false;
    9616             : 
    9617          20 :   if (LDiff->isMinValue())
    9618             :     return true;
    9619             : 
    9620             :   APInt FoundRHSLimit;
    9621             : 
    9622          12 :   if (Pred == CmpInst::ICMP_ULT) {
    9623           7 :     FoundRHSLimit = -(*RDiff);
    9624             :   } else {
    9625             :     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
    9626          10 :     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
    9627             :   }
    9628             : 
    9629             :   // Try to prove (1) or (2), as needed.
    9630          22 :   return isAvailableAtLoopEntry(FoundRHS, L) &&
    9631          10 :          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
    9632             :                                   getConstant(FoundRHSLimit));
    9633             : }
    9634             : 
    9635       29844 : bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
    9636             :                                         const SCEV *LHS, const SCEV *RHS,
    9637             :                                         const SCEV *FoundLHS,
    9638             :                                         const SCEV *FoundRHS, unsigned Depth) {
    9639       29844 :   const PHINode *LPhi = nullptr, *RPhi = nullptr;
    9640             : 
    9641       29844 :   auto ClearOnExit = make_scope_exit([&]() {
    9642       29844 :     if (LPhi) {
    9643         406 :       bool Erased = PendingMerges.erase(LPhi);
    9644             :       assert(Erased && "Failed to erase LPhi!");
    9645             :       (void)Erased;
    9646             :     }
    9647       29844 :     if (RPhi) {
    9648             :       bool Erased = PendingMerges.erase(RPhi);
    9649             :       assert(Erased && "Failed to erase RPhi!");
    9650             :       (void)Erased;
    9651             :     }
    9652       29844 :   });
    9653             : 
    9654             :   // Find respective Phis and check that they are not being pending.
    9655        3528 :   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
    9656             :     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
    9657         332 :       if (!PendingMerges.insert(Phi).second)
    9658             :         return false;
    9659         332 :       LPhi = Phi;
    9660             :     }
    9661        1144 :   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
    9662             :     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
    9663             :       // If we detect a loop of Phi nodes being processed by this method, for
    9664             :       // example:
    9665             :       //
    9666             :       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
    9667             :       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
    9668             :       //
    9669             :       // we don't want to deal with a case that complex, so return conservative
    9670             :       // answer false.
    9671          74 :       if (!PendingMerges.insert(Phi).second)
    9672             :         return false;
    9673          74 :       RPhi = Phi;
    9674             :     }
    9675             : 
    9676             :   // If none of LHS, RHS is a Phi, nothing to do here.
    9677       29844 :   if (!LPhi && !RPhi)
    9678             :     return false;
    9679             : 
    9680             :   // If there is a SCEVUnknown Phi we are interested in, make it left.
    9681         386 :   if (!LPhi) {
    9682             :     std::swap(LHS, RHS);
    9683             :     std::swap(FoundLHS, FoundRHS);
    9684             :     std::swap(LPhi, RPhi);
    9685          54 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    9686             :   }
    9687             : 
    9688             :   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
    9689         386 :   const BasicBlock *LBB = LPhi->getParent();
    9690             :   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
    9691             : 
    9692         439 :   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
    9693        2004 :     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
    9694        2348 :            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
    9695        1484 :            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
    9696         825 :   };
    9697             : 
    9698         386 :   if (RPhi && RPhi->getParent() == LBB) {
    9699             :     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
    9700             :     // If we compare two Phis from the same block, and for each entry block
    9701             :     // the predicate is true for incoming values from this block, then the
    9702             :     // predicate is also true for the Phis.
    9703          40 :     for (const BasicBlock *IncBB : predecessors(LBB)) {
    9704          20 :       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
    9705          20 :       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
    9706          20 :       if (!ProvedEasily(L, R))
    9707          20 :         return false;
    9708             :     }
    9709         366 :   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
    9710             :     // Case two: RHS is also a Phi from the same basic block, and it is an
    9711             :     // AddRec. It means that there is a loop which has both AddRec and Unknown
    9712             :     // PHIs, for it we can compare incoming values of AddRec from above the loop
    9713             :     // and latch with their respective incoming values of LPhi.
    9714             :     assert(LPhi->getNumIncomingValues() == 2 &&
    9715             :            "Phi node standing in loop header does not have exactly 2 inputs?");
    9716             :     auto *RLoop = RAR->getLoop();
    9717           0 :     auto *Predecessor = RLoop->getLoopPredecessor();
    9718             :     assert(Predecessor && "Loop with AddRec with no predecessor?");
    9719           0 :     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
    9720           0 :     if (!ProvedEasily(L1, RAR->getStart()))
    9721             :       return false;
    9722           0 :     auto *Latch = RLoop->getLoopLatch();
    9723             :     assert(Latch && "Loop with AddRec with no latch?");
    9724           0 :     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
    9725           0 :     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
    9726             :       return false;
    9727             :   } else {
    9728             :     // In all other cases go over inputs of LHS and compare each of them to RHS,
    9729             :     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
    9730             :     // At this point RHS is either a non-Phi, or it is a Phi from some block
    9731             :     // different from LBB.
    9732         804 :     for (const BasicBlock *IncBB : predecessors(LBB)) {
    9733             :       // Check that RHS is available in this block.
    9734         419 :       if (!dominates(RHS, IncBB))
    9735         347 :         return false;
    9736         419 :       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
    9737         419 :       if (!ProvedEasily(L, RHS))
    9738             :         return false;
    9739             :     }
    9740             :   }
    9741             :   return true;
    9742             : }
    9743             : 
    9744       49425 : bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
    9745             :                                             const SCEV *LHS, const SCEV *RHS,
    9746             :                                             const SCEV *FoundLHS,
    9747             :                                             const SCEV *FoundRHS) {
    9748       49425 :   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
    9749             :     return true;
    9750             : 
    9751       48056 :   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
    9752             :     return true;
    9753             : 
    9754       48041 :   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
    9755       91820 :                                      FoundLHS, FoundRHS) ||
    9756             :          // ~x < ~y --> x > y
    9757       43779 :          isImpliedCondOperandsHelper(Pred, LHS, RHS,
    9758             :                                      getNotSCEV(FoundRHS),
    9759             :                                      getNotSCEV(FoundLHS));
    9760             : }
    9761             : 
    9762             : /// If Expr computes ~A, return A else return nullptr
    9763       80429 : static const SCEV *MatchNotExpr(const SCEV *Expr) {
    9764             :   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
    9765       21191 :   if (!Add || Add->getNumOperands() != 2 ||
    9766       18978 :       !Add->getOperand(0)->isAllOnesValue())
    9767             :     return nullptr;
    9768             : 
    9769        3936 :   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
    9770        5112 :   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
    9771        5094 :       !AddRHS->getOperand(0)->isAllOnesValue())
    9772             :     return nullptr;
    9773             : 
    9774        4888 :   return AddRHS->getOperand(1);
    9775             : }
    9776             : 
    9777             : /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
    9778             : template<typename MaxExprType>
    9779       82857 : static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
    9780             :                               const SCEV *Candidate) {
    9781             :   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
    9782             :   if (!MaxExpr) return false;
    9783             : 
    9784         462 :   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
    9785             : }
    9786             : 
    9787             : /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
    9788             : template<typename MaxExprType>
    9789       80429 : static bool IsMinConsistingOf(ScalarEvolution &SE,
    9790             :                               const SCEV *MaybeMinExpr,
    9791             :                               const SCEV *Candidate) {
    9792       80429 :   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
    9793       80429 :   if (!MaybeMaxExpr)
    9794             :     return false;
    9795             : 
    9796        2444 :   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
    9797             : }
    9798             : 
    9799      156598 : static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
    9800             :                                            ICmpInst::Predicate Pred,
    9801             :                                            const SCEV *LHS, const SCEV *RHS) {
    9802             :   // If both sides are affine addrecs for the same loop, with equal
    9803             :   // steps, and we know the recurrences don't wrap, then we only
    9804             :   // need to check the predicate on the starting values.
    9805             : 
    9806      156598 :   if (!ICmpInst::isRelational(Pred))
    9807             :     return false;
    9808             : 
    9809             :   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
    9810             :   if (!LAR)
    9811             :     return false;
    9812             :   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
    9813             :   if (!RAR)
    9814             :     return false;
    9815       15734 :   if (LAR->getLoop() != RAR->getLoop())
    9816             :     return false;
    9817       30075 :   if (!LAR->isAffine() || !RAR->isAffine())
    9818             :     return false;
    9819             : 
    9820       15032 :   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
    9821             :     return false;
    9822             : 
    9823       10349 :   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
    9824             :                          SCEV::FlagNSW : SCEV::FlagNUW;
    9825       22111 :   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
    9826             :     return false;
    9827             : 
    9828        4005 :   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
    9829             : }
    9830             : 
    9831             : /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
    9832             : /// expression?
    9833      156630 : static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
    9834             :                                         ICmpInst::Predicate Pred,
    9835             :                                         const SCEV *LHS, const SCEV *RHS) {
    9836      156630 :   switch (Pred) {
    9837             :   default:
    9838             :     return false;
    9839             : 
    9840             :   case ICmpInst::ICMP_SGE:
    9841             :     std::swap(LHS, RHS);
    9842             :     LLVM_FALLTHROUGH;
    9843       35677 :   case ICmpInst::ICMP_SLE:
    9844             :     return
    9845             :       // min(A, ...) <= A
    9846       71346 :       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
    9847             :       // A <= max(A, ...)
    9848       35669 :       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
    9849             : 
    9850             :   case ICmpInst::ICMP_UGE:
    9851             :     std::swap(LHS, RHS);
    9852             :     LLVM_FALLTHROUGH;
    9853       44752 :   case ICmpInst::ICMP_ULE:
    9854             :     return
    9855             :       // min(A, ...) <= A
    9856       89496 :       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
    9857             :       // A <= max(A, ...)
    9858       44744 :       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
    9859             :   }
    9860             : 
    9861             :   llvm_unreachable("covered switch fell through?!");
    9862             : }
    9863             : 
    9864       94391 : bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
    9865             :                                              const SCEV *LHS, const SCEV *RHS,
    9866             :                                              const SCEV *FoundLHS,
    9867             :                                              const SCEV *FoundRHS,
    9868             :                                              unsigned Depth) {
    9869             :   assert(getTypeSizeInBits(LHS->getType()) ==
    9870             :              getTypeSizeInBits(RHS->getType()) &&
    9871             :          "LHS and RHS have different sizes?");
    9872             :   assert(getTypeSizeInBits(FoundLHS->getType()) ==
    9873             :              getTypeSizeInBits(FoundRHS->getType()) &&
    9874             :          "FoundLHS and FoundRHS have different sizes?");
    9875             :   // We want to avoid hurting the compile time with analysis of too big trees.
    9876       94391 :   if (Depth > MaxSCEVOperationsImplicationDepth)
    9877             :     return false;
    9878             :   // We only want to work with ICMP_SGT comparison so far.
    9879             :   // TODO: Extend to ICMP_UGT?
    9880       94303 :   if (Pred == ICmpInst::ICMP_SLT) {
    9881             :     Pred = ICmpInst::ICMP_SGT;
    9882             :     std::swap(LHS, RHS);
    9883             :     std::swap(FoundLHS, FoundRHS);
    9884             :   }
    9885       94303 :   if (Pred != ICmpInst::ICMP_SGT)
    9886             :     return false;
    9887             : 
    9888             :   auto GetOpFromSExt = [&](const SCEV *S) {
    9889             :     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
    9890        5552 :       return Ext->getOperand();
    9891             :     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
    9892             :     // the constant in some cases.
    9893             :     return S;
    9894             :   };
    9895             : 
    9896             :   // Acquire values from extensions.
    9897             :   auto *OrigLHS = LHS;
    9898       35037 :   auto *OrigFoundLHS = FoundLHS;
    9899             :   LHS = GetOpFromSExt(LHS);
    9900             :   FoundLHS = GetOpFromSExt(FoundLHS);
    9901             : 
    9902             :   // Is the SGT predicate can be proved trivially or using the found context.
    9903        9824 :   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
    9904       16247 :     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
    9905       12846 :            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
    9906       12846 :                                   FoundRHS, Depth + 1);
    9907       44861 :   };
    9908             : 
    9909             :   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
    9910             :     // We want to avoid creation of any new non-constant SCEV. Since we are
    9911             :     // going to compare the operands to RHS, we should be certain that we don't
    9912             :     // need any size extensions for this. So let's decline all cases when the
    9913             :     // sizes of types of LHS and RHS do not match.
    9914             :     // TODO: Maybe try to get RHS from sext to catch more cases?
    9915        7959 :     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
    9916        4802 :       return false;
    9917             : 
    9918             :     // Should not overflow.
    9919        7861 :     if (!LHSAddExpr->hasNoSignedWrap())
    9920             :       return false;
    9921             : 
    9922        3177 :     auto *LL = LHSAddExpr->getOperand(0);
    9923             :     auto *LR = LHSAddExpr->getOperand(1);
    9924        6354 :     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
    9925             : 
    9926             :     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
    9927        6338 :     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
    9928        6338 :       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
    9929        9515 :     };
    9930             :     // Try to prove the following rule:
    9931             :     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
    9932             :     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
    9933        3177 :     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
    9934             :       return true;
    9935        4629 :   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
    9936             :     Value *LL, *LR;
    9937             :     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
    9938             : 
    9939             :     using namespace llvm::PatternMatch;
    9940             : 
    9941        9258 :     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
    9942             :       // Rules for division.
    9943             :       // We are going to perform some comparisons with Denominator and its
    9944             :       // derivative expressions. In general case, creating a SCEV for it may
    9945             :       // lead to a complex analysis of the entire graph, and in particular it
    9946             :       // can request trip count recalculation for the same loop. This would
    9947             :       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
    9948             :       // this, we only want to create SCEVs that are constants in this section.
    9949             :       // So we bail if Denominator is not a constant.
    9950         894 :       if (!isa<ConstantInt>(LR))
    9951         391 :         return false;
    9952             : 
    9953         447 :       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
    9954             : 
    9955             :       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
    9956             :       // then a SCEV for the numerator already exists and matches with FoundLHS.
    9957         447 :       auto *Numerator = getExistingSCEV(LL);
    9958         447 :       if (!Numerator || Numerator->getType() != FoundLHS->getType())
    9959             :         return false;
    9960             : 
    9961             :       // Make sure that the numerator matches with FoundLHS and the denominator
    9962             :       // is positive.
    9963         431 :       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
    9964             :         return false;
    9965             : 
    9966          86 :       auto *DTy = Denominator->getType();
    9967          86 :       auto *FRHSTy = FoundRHS->getType();
    9968          86 :       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
    9969             :         // One of types is a pointer and another one is not. We cannot extend
    9970             :         // them properly to a wider type, so let us just reject this case.
    9971             :         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
    9972             :         // to avoid this check.
    9973             :         return false;
    9974             : 
    9975             :       // Given that:
    9976             :       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
    9977          86 :       auto *WTy = getWiderType(DTy, FRHSTy);
    9978          86 :       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
    9979          86 :       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
    9980             : 
    9981             :       // Try to prove the following rule:
    9982             :       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
    9983             :       // For example, given that FoundLHS > 2. It means that FoundLHS is at
    9984             :       // least 3. If we divide it by Denominator < 4, we will have at least 1.
    9985          86 :       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
    9986         154 :       if (isKnownNonPositive(RHS) &&
    9987          68 :           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
    9988             :         return true;
    9989             : 
    9990             :       // Try to prove the following rule:
    9991             :       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
    9992             :       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
    9993             :       // If we divide it by Denominator > 2, then:
    9994             :       // 1. If FoundLHS is negative, then the result is 0.
    9995             :       // 2. If FoundLHS is non-negative, then the result is non-negative.
    9996             :       // Anyways, the result is non-negative.
    9997          73 :       auto *MinusOne = getNegativeSCEV(getOne(WTy));
    9998          73 :       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
    9999         114 :       if (isKnownNegative(RHS) &&
   10000          41 :           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
   10001             :         return true;
   10002             :     }
   10003             :   }
   10004             : 
   10005             :   // If our expression contained SCEVUnknown Phis, and we split it down and now
   10006             :   // need to prove something for them, try to prove the predicate for every
   10007             :   // possible incoming values of those Phis.
   10008       29844 :   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
   10009             :     return true;
   10010             : 
   10011       29825 :   return false;
   10012             : }
   10013             : 
   10014             : bool
   10015      205366 : ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
   10016             :                                            const SCEV *LHS, const SCEV *RHS) {
   10017      361996 :   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
   10018      313228 :          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
   10019      518282 :          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
   10020      361684 :          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
   10021             : }
   10022             : 
   10023             : bool
   10024       91820 : ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
   10025             :                                              const SCEV *LHS, const SCEV *RHS,
   10026             :                                              const SCEV *FoundLHS,
   10027             :                                              const SCEV *FoundRHS) {
   10028       91820 :   switch (Pred) {
   10029           0 :   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
   10030       22233 :   case ICmpInst::ICMP_EQ:
   10031             :   case ICmpInst::ICMP_NE:
   10032       22233 :     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
   10033             :       return true;
   10034             :     break;
   10035       13120 :   case ICmpInst::ICMP_SLT:
   10036             :   case ICmpInst::ICMP_SLE:
   10037       13757 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
   10038         637 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
   10039             :       return true;
   10040             :     break;
   10041       17647 :   case ICmpInst::ICMP_SGT:
   10042             :   case ICmpInst::ICMP_SGE:
   10043       21581 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
   10044        3934 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
   10045             :       return true;
   10046             :     break;
   10047       32534 :   case ICmpInst::ICMP_ULT:
   10048             :   case ICmpInst::ICMP_ULE:
   10049       39208 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
   10050        6674 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
   10051             :       return true;
   10052             :     break;
   10053        6286 :   case ICmpInst::ICMP_UGT:
   10054             :   case ICmpInst::ICMP_UGE:
   10055        6676 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
   10056         390 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
   10057             :       return true;
   10058             :     break;
   10059             :   }
   10060             :