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/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/Sequence.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/InstructionSimplify.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
73 #include "llvm/Analysis/TargetLibraryInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/InstIterator.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/LLVMContext.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/Operator.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/MathExtras.h"
93 #include "llvm/Support/raw_ostream.h"
94 #include "llvm/Support/SaveAndRestore.h"
95 #include <algorithm>
96 using namespace llvm;
97 
98 #define DEBUG_TYPE "scalar-evolution"
99 
100 STATISTIC(NumArrayLenItCounts,
101           "Number of trip counts computed with array length");
102 STATISTIC(NumTripCountsComputed,
103           "Number of loops with predictable loop counts");
104 STATISTIC(NumTripCountsNotComputed,
105           "Number of loops without predictable loop counts");
106 STATISTIC(NumBruteForceTripCountsComputed,
107           "Number of loops with trip counts computed by force");
108 
109 static cl::opt<unsigned>
110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
111                         cl::desc("Maximum number of iterations SCEV will "
112                                  "symbolically execute a constant "
113                                  "derived loop"),
114                         cl::init(100));
115 
116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
117 static cl::opt<bool>
118 VerifySCEV("verify-scev",
119            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
120 static cl::opt<bool>
121     VerifySCEVMap("verify-scev-maps",
122                   cl::desc("Verify no dangling value in ScalarEvolution's "
123                            "ExprValueMap (slow)"));
124 
125 static cl::opt<unsigned> MulOpsInlineThreshold(
126     "scev-mulops-inline-threshold", cl::Hidden,
127     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
128     cl::init(1000));
129 
130 static cl::opt<unsigned> AddOpsInlineThreshold(
131     "scev-addops-inline-threshold", cl::Hidden,
132     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
133     cl::init(500));
134 
135 static cl::opt<unsigned> MaxSCEVCompareDepth(
136     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
137     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
138     cl::init(32));
139 
140 static cl::opt<unsigned> MaxValueCompareDepth(
141     "scalar-evolution-max-value-compare-depth", cl::Hidden,
142     cl::desc("Maximum depth of recursive value complexity comparisons"),
143     cl::init(2));
144 
145 static cl::opt<unsigned>
146     MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
147                     cl::desc("Maximum depth of recursive AddExpr"),
148                     cl::init(32));
149 
150 static cl::opt<unsigned> MaxConstantEvolvingDepth(
151     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
152     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
153 
154 //===----------------------------------------------------------------------===//
155 //                           SCEV class definitions
156 //===----------------------------------------------------------------------===//
157 
158 //===----------------------------------------------------------------------===//
159 // Implementation of the SCEV class.
160 //
161 
162 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
163 LLVM_DUMP_METHOD void SCEV::dump() const {
164   print(dbgs());
165   dbgs() << '\n';
166 }
167 #endif
168 
169 void SCEV::print(raw_ostream &OS) const {
170   switch (static_cast<SCEVTypes>(getSCEVType())) {
171   case scConstant:
172     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
173     return;
174   case scTruncate: {
175     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
176     const SCEV *Op = Trunc->getOperand();
177     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
178        << *Trunc->getType() << ")";
179     return;
180   }
181   case scZeroExtend: {
182     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
183     const SCEV *Op = ZExt->getOperand();
184     OS << "(zext " << *Op->getType() << " " << *Op << " to "
185        << *ZExt->getType() << ")";
186     return;
187   }
188   case scSignExtend: {
189     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
190     const SCEV *Op = SExt->getOperand();
191     OS << "(sext " << *Op->getType() << " " << *Op << " to "
192        << *SExt->getType() << ")";
193     return;
194   }
195   case scAddRecExpr: {
196     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
197     OS << "{" << *AR->getOperand(0);
198     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
199       OS << ",+," << *AR->getOperand(i);
200     OS << "}<";
201     if (AR->hasNoUnsignedWrap())
202       OS << "nuw><";
203     if (AR->hasNoSignedWrap())
204       OS << "nsw><";
205     if (AR->hasNoSelfWrap() &&
206         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
207       OS << "nw><";
208     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
209     OS << ">";
210     return;
211   }
212   case scAddExpr:
213   case scMulExpr:
214   case scUMaxExpr:
215   case scSMaxExpr: {
216     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
217     const char *OpStr = nullptr;
218     switch (NAry->getSCEVType()) {
219     case scAddExpr: OpStr = " + "; break;
220     case scMulExpr: OpStr = " * "; break;
221     case scUMaxExpr: OpStr = " umax "; break;
222     case scSMaxExpr: OpStr = " smax "; break;
223     }
224     OS << "(";
225     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
226          I != E; ++I) {
227       OS << **I;
228       if (std::next(I) != E)
229         OS << OpStr;
230     }
231     OS << ")";
232     switch (NAry->getSCEVType()) {
233     case scAddExpr:
234     case scMulExpr:
235       if (NAry->hasNoUnsignedWrap())
236         OS << "<nuw>";
237       if (NAry->hasNoSignedWrap())
238         OS << "<nsw>";
239     }
240     return;
241   }
242   case scUDivExpr: {
243     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
244     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
245     return;
246   }
247   case scUnknown: {
248     const SCEVUnknown *U = cast<SCEVUnknown>(this);
249     Type *AllocTy;
250     if (U->isSizeOf(AllocTy)) {
251       OS << "sizeof(" << *AllocTy << ")";
252       return;
253     }
254     if (U->isAlignOf(AllocTy)) {
255       OS << "alignof(" << *AllocTy << ")";
256       return;
257     }
258 
259     Type *CTy;
260     Constant *FieldNo;
261     if (U->isOffsetOf(CTy, FieldNo)) {
262       OS << "offsetof(" << *CTy << ", ";
263       FieldNo->printAsOperand(OS, false);
264       OS << ")";
265       return;
266     }
267 
268     // Otherwise just print it normally.
269     U->getValue()->printAsOperand(OS, false);
270     return;
271   }
272   case scCouldNotCompute:
273     OS << "***COULDNOTCOMPUTE***";
274     return;
275   }
276   llvm_unreachable("Unknown SCEV kind!");
277 }
278 
279 Type *SCEV::getType() const {
280   switch (static_cast<SCEVTypes>(getSCEVType())) {
281   case scConstant:
282     return cast<SCEVConstant>(this)->getType();
283   case scTruncate:
284   case scZeroExtend:
285   case scSignExtend:
286     return cast<SCEVCastExpr>(this)->getType();
287   case scAddRecExpr:
288   case scMulExpr:
289   case scUMaxExpr:
290   case scSMaxExpr:
291     return cast<SCEVNAryExpr>(this)->getType();
292   case scAddExpr:
293     return cast<SCEVAddExpr>(this)->getType();
294   case scUDivExpr:
295     return cast<SCEVUDivExpr>(this)->getType();
296   case scUnknown:
297     return cast<SCEVUnknown>(this)->getType();
298   case scCouldNotCompute:
299     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
300   }
301   llvm_unreachable("Unknown SCEV kind!");
302 }
303 
304 bool SCEV::isZero() const {
305   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
306     return SC->getValue()->isZero();
307   return false;
308 }
309 
310 bool SCEV::isOne() const {
311   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
312     return SC->getValue()->isOne();
313   return false;
314 }
315 
316 bool SCEV::isAllOnesValue() const {
317   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
318     return SC->getValue()->isAllOnesValue();
319   return false;
320 }
321 
322 bool SCEV::isNonConstantNegative() const {
323   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
324   if (!Mul) return false;
325 
326   // If there is a constant factor, it will be first.
327   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
328   if (!SC) return false;
329 
330   // Return true if the value is negative, this matches things like (-42 * V).
331   return SC->getAPInt().isNegative();
332 }
333 
334 SCEVCouldNotCompute::SCEVCouldNotCompute() :
335   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
336 
337 bool SCEVCouldNotCompute::classof(const SCEV *S) {
338   return S->getSCEVType() == scCouldNotCompute;
339 }
340 
341 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
342   FoldingSetNodeID ID;
343   ID.AddInteger(scConstant);
344   ID.AddPointer(V);
345   void *IP = nullptr;
346   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
347   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
348   UniqueSCEVs.InsertNode(S, IP);
349   return S;
350 }
351 
352 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
353   return getConstant(ConstantInt::get(getContext(), Val));
354 }
355 
356 const SCEV *
357 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
358   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
359   return getConstant(ConstantInt::get(ITy, V, isSigned));
360 }
361 
362 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
363                            unsigned SCEVTy, const SCEV *op, Type *ty)
364   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
365 
366 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
367                                    const SCEV *op, Type *ty)
368   : SCEVCastExpr(ID, scTruncate, op, ty) {
369   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
370          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
371          "Cannot truncate non-integer value!");
372 }
373 
374 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
375                                        const SCEV *op, Type *ty)
376   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
377   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
378          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
379          "Cannot zero extend non-integer value!");
380 }
381 
382 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
383                                        const SCEV *op, Type *ty)
384   : SCEVCastExpr(ID, scSignExtend, op, ty) {
385   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
386          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
387          "Cannot sign extend non-integer value!");
388 }
389 
390 void SCEVUnknown::deleted() {
391   // Clear this SCEVUnknown from various maps.
392   SE->forgetMemoizedResults(this);
393 
394   // Remove this SCEVUnknown from the uniquing map.
395   SE->UniqueSCEVs.RemoveNode(this);
396 
397   // Release the value.
398   setValPtr(nullptr);
399 }
400 
401 void SCEVUnknown::allUsesReplacedWith(Value *New) {
402   // Clear this SCEVUnknown from various maps.
403   SE->forgetMemoizedResults(this);
404 
405   // Remove this SCEVUnknown from the uniquing map.
406   SE->UniqueSCEVs.RemoveNode(this);
407 
408   // Update this SCEVUnknown to point to the new value. This is needed
409   // because there may still be outstanding SCEVs which still point to
410   // this SCEVUnknown.
411   setValPtr(New);
412 }
413 
414 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
415   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
416     if (VCE->getOpcode() == Instruction::PtrToInt)
417       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
418         if (CE->getOpcode() == Instruction::GetElementPtr &&
419             CE->getOperand(0)->isNullValue() &&
420             CE->getNumOperands() == 2)
421           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
422             if (CI->isOne()) {
423               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
424                                  ->getElementType();
425               return true;
426             }
427 
428   return false;
429 }
430 
431 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
432   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
433     if (VCE->getOpcode() == Instruction::PtrToInt)
434       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435         if (CE->getOpcode() == Instruction::GetElementPtr &&
436             CE->getOperand(0)->isNullValue()) {
437           Type *Ty =
438             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
439           if (StructType *STy = dyn_cast<StructType>(Ty))
440             if (!STy->isPacked() &&
441                 CE->getNumOperands() == 3 &&
442                 CE->getOperand(1)->isNullValue()) {
443               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
444                 if (CI->isOne() &&
445                     STy->getNumElements() == 2 &&
446                     STy->getElementType(0)->isIntegerTy(1)) {
447                   AllocTy = STy->getElementType(1);
448                   return true;
449                 }
450             }
451         }
452 
453   return false;
454 }
455 
456 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
457   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
458     if (VCE->getOpcode() == Instruction::PtrToInt)
459       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
460         if (CE->getOpcode() == Instruction::GetElementPtr &&
461             CE->getNumOperands() == 3 &&
462             CE->getOperand(0)->isNullValue() &&
463             CE->getOperand(1)->isNullValue()) {
464           Type *Ty =
465             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
466           // Ignore vector types here so that ScalarEvolutionExpander doesn't
467           // emit getelementptrs that index into vectors.
468           if (Ty->isStructTy() || Ty->isArrayTy()) {
469             CTy = Ty;
470             FieldNo = CE->getOperand(2);
471             return true;
472           }
473         }
474 
475   return false;
476 }
477 
478 //===----------------------------------------------------------------------===//
479 //                               SCEV Utilities
480 //===----------------------------------------------------------------------===//
481 
482 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
483 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
484 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
485 /// have been previously deemed to be "equally complex" by this routine.  It is
486 /// intended to avoid exponential time complexity in cases like:
487 ///
488 ///   %a = f(%x, %y)
489 ///   %b = f(%a, %a)
490 ///   %c = f(%b, %b)
491 ///
492 ///   %d = f(%x, %y)
493 ///   %e = f(%d, %d)
494 ///   %f = f(%e, %e)
495 ///
496 ///   CompareValueComplexity(%f, %c)
497 ///
498 /// Since we do not continue running this routine on expression trees once we
499 /// have seen unequal values, there is no need to track them in the cache.
500 static int
501 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
502                        const LoopInfo *const LI, Value *LV, Value *RV,
503                        unsigned Depth) {
504   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
505     return 0;
506 
507   // Order pointer values after integer values. This helps SCEVExpander form
508   // GEPs.
509   bool LIsPointer = LV->getType()->isPointerTy(),
510        RIsPointer = RV->getType()->isPointerTy();
511   if (LIsPointer != RIsPointer)
512     return (int)LIsPointer - (int)RIsPointer;
513 
514   // Compare getValueID values.
515   unsigned LID = LV->getValueID(), RID = RV->getValueID();
516   if (LID != RID)
517     return (int)LID - (int)RID;
518 
519   // Sort arguments by their position.
520   if (const auto *LA = dyn_cast<Argument>(LV)) {
521     const auto *RA = cast<Argument>(RV);
522     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
523     return (int)LArgNo - (int)RArgNo;
524   }
525 
526   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
527     const auto *RGV = cast<GlobalValue>(RV);
528 
529     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
530       auto LT = GV->getLinkage();
531       return !(GlobalValue::isPrivateLinkage(LT) ||
532                GlobalValue::isInternalLinkage(LT));
533     };
534 
535     // Use the names to distinguish the two values, but only if the
536     // names are semantically important.
537     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
538       return LGV->getName().compare(RGV->getName());
539   }
540 
541   // For instructions, compare their loop depth, and their operand count.  This
542   // is pretty loose.
543   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
544     const auto *RInst = cast<Instruction>(RV);
545 
546     // Compare loop depths.
547     const BasicBlock *LParent = LInst->getParent(),
548                      *RParent = RInst->getParent();
549     if (LParent != RParent) {
550       unsigned LDepth = LI->getLoopDepth(LParent),
551                RDepth = LI->getLoopDepth(RParent);
552       if (LDepth != RDepth)
553         return (int)LDepth - (int)RDepth;
554     }
555 
556     // Compare the number of operands.
557     unsigned LNumOps = LInst->getNumOperands(),
558              RNumOps = RInst->getNumOperands();
559     if (LNumOps != RNumOps)
560       return (int)LNumOps - (int)RNumOps;
561 
562     for (unsigned Idx : seq(0u, LNumOps)) {
563       int Result =
564           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
565                                  RInst->getOperand(Idx), Depth + 1);
566       if (Result != 0)
567         return Result;
568     }
569   }
570 
571   EqCache.insert({LV, RV});
572   return 0;
573 }
574 
575 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
576 // than RHS, respectively. A three-way result allows recursive comparisons to be
577 // more efficient.
578 static int CompareSCEVComplexity(
579     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
580     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
581     unsigned Depth = 0) {
582   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
583   if (LHS == RHS)
584     return 0;
585 
586   // Primarily, sort the SCEVs by their getSCEVType().
587   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
588   if (LType != RType)
589     return (int)LType - (int)RType;
590 
591   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
592     return 0;
593   // Aside from the getSCEVType() ordering, the particular ordering
594   // isn't very important except that it's beneficial to be consistent,
595   // so that (a + b) and (b + a) don't end up as different expressions.
596   switch (static_cast<SCEVTypes>(LType)) {
597   case scUnknown: {
598     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
599     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
600 
601     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
602     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
603                                    Depth + 1);
604     if (X == 0)
605       EqCacheSCEV.insert({LHS, RHS});
606     return X;
607   }
608 
609   case scConstant: {
610     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
611     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
612 
613     // Compare constant values.
614     const APInt &LA = LC->getAPInt();
615     const APInt &RA = RC->getAPInt();
616     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
617     if (LBitWidth != RBitWidth)
618       return (int)LBitWidth - (int)RBitWidth;
619     return LA.ult(RA) ? -1 : 1;
620   }
621 
622   case scAddRecExpr: {
623     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
624     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
625 
626     // Compare addrec loop depths.
627     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
628     if (LLoop != RLoop) {
629       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
630       if (LDepth != RDepth)
631         return (int)LDepth - (int)RDepth;
632     }
633 
634     // Addrec complexity grows with operand count.
635     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
636     if (LNumOps != RNumOps)
637       return (int)LNumOps - (int)RNumOps;
638 
639     // Lexicographically compare.
640     for (unsigned i = 0; i != LNumOps; ++i) {
641       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
642                                     RA->getOperand(i), Depth + 1);
643       if (X != 0)
644         return X;
645     }
646     EqCacheSCEV.insert({LHS, RHS});
647     return 0;
648   }
649 
650   case scAddExpr:
651   case scMulExpr:
652   case scSMaxExpr:
653   case scUMaxExpr: {
654     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
655     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
656 
657     // Lexicographically compare n-ary expressions.
658     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
659     if (LNumOps != RNumOps)
660       return (int)LNumOps - (int)RNumOps;
661 
662     for (unsigned i = 0; i != LNumOps; ++i) {
663       if (i >= RNumOps)
664         return 1;
665       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
666                                     RC->getOperand(i), Depth + 1);
667       if (X != 0)
668         return X;
669     }
670     EqCacheSCEV.insert({LHS, RHS});
671     return 0;
672   }
673 
674   case scUDivExpr: {
675     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
676     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
677 
678     // Lexicographically compare udiv expressions.
679     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
680                                   Depth + 1);
681     if (X != 0)
682       return X;
683     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
684                               Depth + 1);
685     if (X == 0)
686       EqCacheSCEV.insert({LHS, RHS});
687     return X;
688   }
689 
690   case scTruncate:
691   case scZeroExtend:
692   case scSignExtend: {
693     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
694     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
695 
696     // Compare cast expressions by operand.
697     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
698                                   RC->getOperand(), Depth + 1);
699     if (X == 0)
700       EqCacheSCEV.insert({LHS, RHS});
701     return X;
702   }
703 
704   case scCouldNotCompute:
705     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
706   }
707   llvm_unreachable("Unknown SCEV kind!");
708 }
709 
710 /// Given a list of SCEV objects, order them by their complexity, and group
711 /// objects of the same complexity together by value.  When this routine is
712 /// finished, we know that any duplicates in the vector are consecutive and that
713 /// complexity is monotonically increasing.
714 ///
715 /// Note that we go take special precautions to ensure that we get deterministic
716 /// results from this routine.  In other words, we don't want the results of
717 /// this to depend on where the addresses of various SCEV objects happened to
718 /// land in memory.
719 ///
720 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
721                               LoopInfo *LI) {
722   if (Ops.size() < 2) return;  // Noop
723 
724   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
725   if (Ops.size() == 2) {
726     // This is the common case, which also happens to be trivially simple.
727     // Special case it.
728     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
729     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
730       std::swap(LHS, RHS);
731     return;
732   }
733 
734   // Do the rough sort by complexity.
735   std::stable_sort(Ops.begin(), Ops.end(),
736                    [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
737                      return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
738                    });
739 
740   // Now that we are sorted by complexity, group elements of the same
741   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
742   // be extremely short in practice.  Note that we take this approach because we
743   // do not want to depend on the addresses of the objects we are grouping.
744   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
745     const SCEV *S = Ops[i];
746     unsigned Complexity = S->getSCEVType();
747 
748     // If there are any objects of the same complexity and same value as this
749     // one, group them.
750     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
751       if (Ops[j] == S) { // Found a duplicate.
752         // Move it to immediately after i'th element.
753         std::swap(Ops[i+1], Ops[j]);
754         ++i;   // no need to rescan it.
755         if (i == e-2) return;  // Done!
756       }
757     }
758   }
759 }
760 
761 // Returns the size of the SCEV S.
762 static inline int sizeOfSCEV(const SCEV *S) {
763   struct FindSCEVSize {
764     int Size;
765     FindSCEVSize() : Size(0) {}
766 
767     bool follow(const SCEV *S) {
768       ++Size;
769       // Keep looking at all operands of S.
770       return true;
771     }
772     bool isDone() const {
773       return false;
774     }
775   };
776 
777   FindSCEVSize F;
778   SCEVTraversal<FindSCEVSize> ST(F);
779   ST.visitAll(S);
780   return F.Size;
781 }
782 
783 namespace {
784 
785 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
786 public:
787   // Computes the Quotient and Remainder of the division of Numerator by
788   // Denominator.
789   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
790                      const SCEV *Denominator, const SCEV **Quotient,
791                      const SCEV **Remainder) {
792     assert(Numerator && Denominator && "Uninitialized SCEV");
793 
794     SCEVDivision D(SE, Numerator, Denominator);
795 
796     // Check for the trivial case here to avoid having to check for it in the
797     // rest of the code.
798     if (Numerator == Denominator) {
799       *Quotient = D.One;
800       *Remainder = D.Zero;
801       return;
802     }
803 
804     if (Numerator->isZero()) {
805       *Quotient = D.Zero;
806       *Remainder = D.Zero;
807       return;
808     }
809 
810     // A simple case when N/1. The quotient is N.
811     if (Denominator->isOne()) {
812       *Quotient = Numerator;
813       *Remainder = D.Zero;
814       return;
815     }
816 
817     // Split the Denominator when it is a product.
818     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
819       const SCEV *Q, *R;
820       *Quotient = Numerator;
821       for (const SCEV *Op : T->operands()) {
822         divide(SE, *Quotient, Op, &Q, &R);
823         *Quotient = Q;
824 
825         // Bail out when the Numerator is not divisible by one of the terms of
826         // the Denominator.
827         if (!R->isZero()) {
828           *Quotient = D.Zero;
829           *Remainder = Numerator;
830           return;
831         }
832       }
833       *Remainder = D.Zero;
834       return;
835     }
836 
837     D.visit(Numerator);
838     *Quotient = D.Quotient;
839     *Remainder = D.Remainder;
840   }
841 
842   // Except in the trivial case described above, we do not know how to divide
843   // Expr by Denominator for the following functions with empty implementation.
844   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
845   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
846   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
847   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
848   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
849   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
850   void visitUnknown(const SCEVUnknown *Numerator) {}
851   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
852 
853   void visitConstant(const SCEVConstant *Numerator) {
854     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
855       APInt NumeratorVal = Numerator->getAPInt();
856       APInt DenominatorVal = D->getAPInt();
857       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
858       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
859 
860       if (NumeratorBW > DenominatorBW)
861         DenominatorVal = DenominatorVal.sext(NumeratorBW);
862       else if (NumeratorBW < DenominatorBW)
863         NumeratorVal = NumeratorVal.sext(DenominatorBW);
864 
865       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
866       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
867       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
868       Quotient = SE.getConstant(QuotientVal);
869       Remainder = SE.getConstant(RemainderVal);
870       return;
871     }
872   }
873 
874   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
875     const SCEV *StartQ, *StartR, *StepQ, *StepR;
876     if (!Numerator->isAffine())
877       return cannotDivide(Numerator);
878     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
879     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
880     // Bail out if the types do not match.
881     Type *Ty = Denominator->getType();
882     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
883         Ty != StepQ->getType() || Ty != StepR->getType())
884       return cannotDivide(Numerator);
885     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
886                                 Numerator->getNoWrapFlags());
887     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
888                                  Numerator->getNoWrapFlags());
889   }
890 
891   void visitAddExpr(const SCEVAddExpr *Numerator) {
892     SmallVector<const SCEV *, 2> Qs, Rs;
893     Type *Ty = Denominator->getType();
894 
895     for (const SCEV *Op : Numerator->operands()) {
896       const SCEV *Q, *R;
897       divide(SE, Op, Denominator, &Q, &R);
898 
899       // Bail out if types do not match.
900       if (Ty != Q->getType() || Ty != R->getType())
901         return cannotDivide(Numerator);
902 
903       Qs.push_back(Q);
904       Rs.push_back(R);
905     }
906 
907     if (Qs.size() == 1) {
908       Quotient = Qs[0];
909       Remainder = Rs[0];
910       return;
911     }
912 
913     Quotient = SE.getAddExpr(Qs);
914     Remainder = SE.getAddExpr(Rs);
915   }
916 
917   void visitMulExpr(const SCEVMulExpr *Numerator) {
918     SmallVector<const SCEV *, 2> Qs;
919     Type *Ty = Denominator->getType();
920 
921     bool FoundDenominatorTerm = false;
922     for (const SCEV *Op : Numerator->operands()) {
923       // Bail out if types do not match.
924       if (Ty != Op->getType())
925         return cannotDivide(Numerator);
926 
927       if (FoundDenominatorTerm) {
928         Qs.push_back(Op);
929         continue;
930       }
931 
932       // Check whether Denominator divides one of the product operands.
933       const SCEV *Q, *R;
934       divide(SE, Op, Denominator, &Q, &R);
935       if (!R->isZero()) {
936         Qs.push_back(Op);
937         continue;
938       }
939 
940       // Bail out if types do not match.
941       if (Ty != Q->getType())
942         return cannotDivide(Numerator);
943 
944       FoundDenominatorTerm = true;
945       Qs.push_back(Q);
946     }
947 
948     if (FoundDenominatorTerm) {
949       Remainder = Zero;
950       if (Qs.size() == 1)
951         Quotient = Qs[0];
952       else
953         Quotient = SE.getMulExpr(Qs);
954       return;
955     }
956 
957     if (!isa<SCEVUnknown>(Denominator))
958       return cannotDivide(Numerator);
959 
960     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
961     ValueToValueMap RewriteMap;
962     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
963         cast<SCEVConstant>(Zero)->getValue();
964     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
965 
966     if (Remainder->isZero()) {
967       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
968       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
969           cast<SCEVConstant>(One)->getValue();
970       Quotient =
971           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
972       return;
973     }
974 
975     // Quotient is (Numerator - Remainder) divided by Denominator.
976     const SCEV *Q, *R;
977     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
978     // This SCEV does not seem to simplify: fail the division here.
979     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
980       return cannotDivide(Numerator);
981     divide(SE, Diff, Denominator, &Q, &R);
982     if (R != Zero)
983       return cannotDivide(Numerator);
984     Quotient = Q;
985   }
986 
987 private:
988   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
989                const SCEV *Denominator)
990       : SE(S), Denominator(Denominator) {
991     Zero = SE.getZero(Denominator->getType());
992     One = SE.getOne(Denominator->getType());
993 
994     // We generally do not know how to divide Expr by Denominator. We
995     // initialize the division to a "cannot divide" state to simplify the rest
996     // of the code.
997     cannotDivide(Numerator);
998   }
999 
1000   // Convenience function for giving up on the division. We set the quotient to
1001   // be equal to zero and the remainder to be equal to the numerator.
1002   void cannotDivide(const SCEV *Numerator) {
1003     Quotient = Zero;
1004     Remainder = Numerator;
1005   }
1006 
1007   ScalarEvolution &SE;
1008   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1009 };
1010 
1011 }
1012 
1013 //===----------------------------------------------------------------------===//
1014 //                      Simple SCEV method implementations
1015 //===----------------------------------------------------------------------===//
1016 
1017 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1018 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1019                                        ScalarEvolution &SE,
1020                                        Type *ResultTy) {
1021   // Handle the simplest case efficiently.
1022   if (K == 1)
1023     return SE.getTruncateOrZeroExtend(It, ResultTy);
1024 
1025   // We are using the following formula for BC(It, K):
1026   //
1027   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1028   //
1029   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1030   // overflow.  Hence, we must assure that the result of our computation is
1031   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1032   // safe in modular arithmetic.
1033   //
1034   // However, this code doesn't use exactly that formula; the formula it uses
1035   // is something like the following, where T is the number of factors of 2 in
1036   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1037   // exponentiation:
1038   //
1039   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1040   //
1041   // This formula is trivially equivalent to the previous formula.  However,
1042   // this formula can be implemented much more efficiently.  The trick is that
1043   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1044   // arithmetic.  To do exact division in modular arithmetic, all we have
1045   // to do is multiply by the inverse.  Therefore, this step can be done at
1046   // width W.
1047   //
1048   // The next issue is how to safely do the division by 2^T.  The way this
1049   // is done is by doing the multiplication step at a width of at least W + T
1050   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1051   // when we perform the division by 2^T (which is equivalent to a right shift
1052   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1053   // truncated out after the division by 2^T.
1054   //
1055   // In comparison to just directly using the first formula, this technique
1056   // is much more efficient; using the first formula requires W * K bits,
1057   // but this formula less than W + K bits. Also, the first formula requires
1058   // a division step, whereas this formula only requires multiplies and shifts.
1059   //
1060   // It doesn't matter whether the subtraction step is done in the calculation
1061   // width or the input iteration count's width; if the subtraction overflows,
1062   // the result must be zero anyway.  We prefer here to do it in the width of
1063   // the induction variable because it helps a lot for certain cases; CodeGen
1064   // isn't smart enough to ignore the overflow, which leads to much less
1065   // efficient code if the width of the subtraction is wider than the native
1066   // register width.
1067   //
1068   // (It's possible to not widen at all by pulling out factors of 2 before
1069   // the multiplication; for example, K=2 can be calculated as
1070   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1071   // extra arithmetic, so it's not an obvious win, and it gets
1072   // much more complicated for K > 3.)
1073 
1074   // Protection from insane SCEVs; this bound is conservative,
1075   // but it probably doesn't matter.
1076   if (K > 1000)
1077     return SE.getCouldNotCompute();
1078 
1079   unsigned W = SE.getTypeSizeInBits(ResultTy);
1080 
1081   // Calculate K! / 2^T and T; we divide out the factors of two before
1082   // multiplying for calculating K! / 2^T to avoid overflow.
1083   // Other overflow doesn't matter because we only care about the bottom
1084   // W bits of the result.
1085   APInt OddFactorial(W, 1);
1086   unsigned T = 1;
1087   for (unsigned i = 3; i <= K; ++i) {
1088     APInt Mult(W, i);
1089     unsigned TwoFactors = Mult.countTrailingZeros();
1090     T += TwoFactors;
1091     Mult = Mult.lshr(TwoFactors);
1092     OddFactorial *= Mult;
1093   }
1094 
1095   // We need at least W + T bits for the multiplication step
1096   unsigned CalculationBits = W + T;
1097 
1098   // Calculate 2^T, at width T+W.
1099   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1100 
1101   // Calculate the multiplicative inverse of K! / 2^T;
1102   // this multiplication factor will perform the exact division by
1103   // K! / 2^T.
1104   APInt Mod = APInt::getSignedMinValue(W+1);
1105   APInt MultiplyFactor = OddFactorial.zext(W+1);
1106   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1107   MultiplyFactor = MultiplyFactor.trunc(W);
1108 
1109   // Calculate the product, at width T+W
1110   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1111                                                       CalculationBits);
1112   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1113   for (unsigned i = 1; i != K; ++i) {
1114     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1115     Dividend = SE.getMulExpr(Dividend,
1116                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1117   }
1118 
1119   // Divide by 2^T
1120   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1121 
1122   // Truncate the result, and divide by K! / 2^T.
1123 
1124   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1125                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1126 }
1127 
1128 /// Return the value of this chain of recurrences at the specified iteration
1129 /// number.  We can evaluate this recurrence by multiplying each element in the
1130 /// chain by the binomial coefficient corresponding to it.  In other words, we
1131 /// can evaluate {A,+,B,+,C,+,D} as:
1132 ///
1133 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1134 ///
1135 /// where BC(It, k) stands for binomial coefficient.
1136 ///
1137 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1138                                                 ScalarEvolution &SE) const {
1139   const SCEV *Result = getStart();
1140   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1141     // The computation is correct in the face of overflow provided that the
1142     // multiplication is performed _after_ the evaluation of the binomial
1143     // coefficient.
1144     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1145     if (isa<SCEVCouldNotCompute>(Coeff))
1146       return Coeff;
1147 
1148     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1149   }
1150   return Result;
1151 }
1152 
1153 //===----------------------------------------------------------------------===//
1154 //                    SCEV Expression folder implementations
1155 //===----------------------------------------------------------------------===//
1156 
1157 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1158                                              Type *Ty) {
1159   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1160          "This is not a truncating conversion!");
1161   assert(isSCEVable(Ty) &&
1162          "This is not a conversion to a SCEVable type!");
1163   Ty = getEffectiveSCEVType(Ty);
1164 
1165   FoldingSetNodeID ID;
1166   ID.AddInteger(scTruncate);
1167   ID.AddPointer(Op);
1168   ID.AddPointer(Ty);
1169   void *IP = nullptr;
1170   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1171 
1172   // Fold if the operand is constant.
1173   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1174     return getConstant(
1175       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1176 
1177   // trunc(trunc(x)) --> trunc(x)
1178   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1179     return getTruncateExpr(ST->getOperand(), Ty);
1180 
1181   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1182   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1183     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1184 
1185   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1186   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1187     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1188 
1189   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1190   // eliminate all the truncates, or we replace other casts with truncates.
1191   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1192     SmallVector<const SCEV *, 4> Operands;
1193     bool hasTrunc = false;
1194     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1195       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1196       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1197         hasTrunc = isa<SCEVTruncateExpr>(S);
1198       Operands.push_back(S);
1199     }
1200     if (!hasTrunc)
1201       return getAddExpr(Operands);
1202     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1203   }
1204 
1205   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1206   // eliminate all the truncates, or we replace other casts with truncates.
1207   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1208     SmallVector<const SCEV *, 4> Operands;
1209     bool hasTrunc = false;
1210     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1211       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1212       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1213         hasTrunc = isa<SCEVTruncateExpr>(S);
1214       Operands.push_back(S);
1215     }
1216     if (!hasTrunc)
1217       return getMulExpr(Operands);
1218     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1219   }
1220 
1221   // If the input value is a chrec scev, truncate the chrec's operands.
1222   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1223     SmallVector<const SCEV *, 4> Operands;
1224     for (const SCEV *Op : AddRec->operands())
1225       Operands.push_back(getTruncateExpr(Op, Ty));
1226     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1227   }
1228 
1229   // The cast wasn't folded; create an explicit cast node. We can reuse
1230   // the existing insert position since if we get here, we won't have
1231   // made any changes which would invalidate it.
1232   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1233                                                  Op, Ty);
1234   UniqueSCEVs.InsertNode(S, IP);
1235   return S;
1236 }
1237 
1238 // Get the limit of a recurrence such that incrementing by Step cannot cause
1239 // signed overflow as long as the value of the recurrence within the
1240 // loop does not exceed this limit before incrementing.
1241 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1242                                                  ICmpInst::Predicate *Pred,
1243                                                  ScalarEvolution *SE) {
1244   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1245   if (SE->isKnownPositive(Step)) {
1246     *Pred = ICmpInst::ICMP_SLT;
1247     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1248                            SE->getSignedRange(Step).getSignedMax());
1249   }
1250   if (SE->isKnownNegative(Step)) {
1251     *Pred = ICmpInst::ICMP_SGT;
1252     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1253                            SE->getSignedRange(Step).getSignedMin());
1254   }
1255   return nullptr;
1256 }
1257 
1258 // Get the limit of a recurrence such that incrementing by Step cannot cause
1259 // unsigned overflow as long as the value of the recurrence within the loop does
1260 // not exceed this limit before incrementing.
1261 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1262                                                    ICmpInst::Predicate *Pred,
1263                                                    ScalarEvolution *SE) {
1264   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1265   *Pred = ICmpInst::ICMP_ULT;
1266 
1267   return SE->getConstant(APInt::getMinValue(BitWidth) -
1268                          SE->getUnsignedRange(Step).getUnsignedMax());
1269 }
1270 
1271 namespace {
1272 
1273 struct ExtendOpTraitsBase {
1274   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1275 };
1276 
1277 // Used to make code generic over signed and unsigned overflow.
1278 template <typename ExtendOp> struct ExtendOpTraits {
1279   // Members present:
1280   //
1281   // static const SCEV::NoWrapFlags WrapType;
1282   //
1283   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1284   //
1285   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1286   //                                           ICmpInst::Predicate *Pred,
1287   //                                           ScalarEvolution *SE);
1288 };
1289 
1290 template <>
1291 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1292   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1293 
1294   static const GetExtendExprTy GetExtendExpr;
1295 
1296   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1297                                              ICmpInst::Predicate *Pred,
1298                                              ScalarEvolution *SE) {
1299     return getSignedOverflowLimitForStep(Step, Pred, SE);
1300   }
1301 };
1302 
1303 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1304     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1305 
1306 template <>
1307 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1308   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1309 
1310   static const GetExtendExprTy GetExtendExpr;
1311 
1312   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1313                                              ICmpInst::Predicate *Pred,
1314                                              ScalarEvolution *SE) {
1315     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1316   }
1317 };
1318 
1319 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1320     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1321 }
1322 
1323 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1324 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1325 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1326 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1327 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1328 // expression "Step + sext/zext(PreIncAR)" is congruent with
1329 // "sext/zext(PostIncAR)"
1330 template <typename ExtendOpTy>
1331 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1332                                         ScalarEvolution *SE) {
1333   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1334   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1335 
1336   const Loop *L = AR->getLoop();
1337   const SCEV *Start = AR->getStart();
1338   const SCEV *Step = AR->getStepRecurrence(*SE);
1339 
1340   // Check for a simple looking step prior to loop entry.
1341   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1342   if (!SA)
1343     return nullptr;
1344 
1345   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1346   // subtraction is expensive. For this purpose, perform a quick and dirty
1347   // difference, by checking for Step in the operand list.
1348   SmallVector<const SCEV *, 4> DiffOps;
1349   for (const SCEV *Op : SA->operands())
1350     if (Op != Step)
1351       DiffOps.push_back(Op);
1352 
1353   if (DiffOps.size() == SA->getNumOperands())
1354     return nullptr;
1355 
1356   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1357   // `Step`:
1358 
1359   // 1. NSW/NUW flags on the step increment.
1360   auto PreStartFlags =
1361     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1362   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1363   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1364       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1365 
1366   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1367   // "S+X does not sign/unsign-overflow".
1368   //
1369 
1370   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1371   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1372       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1373     return PreStart;
1374 
1375   // 2. Direct overflow check on the step operation's expression.
1376   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1377   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1378   const SCEV *OperandExtendedStart =
1379       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1380                      (SE->*GetExtendExpr)(Step, WideTy));
1381   if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1382     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1383       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1384       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1385       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1386       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1387     }
1388     return PreStart;
1389   }
1390 
1391   // 3. Loop precondition.
1392   ICmpInst::Predicate Pred;
1393   const SCEV *OverflowLimit =
1394       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1395 
1396   if (OverflowLimit &&
1397       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1398     return PreStart;
1399 
1400   return nullptr;
1401 }
1402 
1403 // Get the normalized zero or sign extended expression for this AddRec's Start.
1404 template <typename ExtendOpTy>
1405 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1406                                         ScalarEvolution *SE) {
1407   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1408 
1409   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1410   if (!PreStart)
1411     return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1412 
1413   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1414                         (SE->*GetExtendExpr)(PreStart, Ty));
1415 }
1416 
1417 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1418 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1419 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1420 //
1421 // Formally:
1422 //
1423 //     {S,+,X} == {S-T,+,X} + T
1424 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1425 //
1426 // If ({S-T,+,X} + T) does not overflow  ... (1)
1427 //
1428 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1429 //
1430 // If {S-T,+,X} does not overflow  ... (2)
1431 //
1432 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1433 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1434 //
1435 // If (S-T)+T does not overflow  ... (3)
1436 //
1437 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1438 //      == {Ext(S),+,Ext(X)} == LHS
1439 //
1440 // Thus, if (1), (2) and (3) are true for some T, then
1441 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1442 //
1443 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1444 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1445 // to check for (1) and (2).
1446 //
1447 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1448 // is `Delta` (defined below).
1449 //
1450 template <typename ExtendOpTy>
1451 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1452                                                 const SCEV *Step,
1453                                                 const Loop *L) {
1454   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1455 
1456   // We restrict `Start` to a constant to prevent SCEV from spending too much
1457   // time here.  It is correct (but more expensive) to continue with a
1458   // non-constant `Start` and do a general SCEV subtraction to compute
1459   // `PreStart` below.
1460   //
1461   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1462   if (!StartC)
1463     return false;
1464 
1465   APInt StartAI = StartC->getAPInt();
1466 
1467   for (unsigned Delta : {-2, -1, 1, 2}) {
1468     const SCEV *PreStart = getConstant(StartAI - Delta);
1469 
1470     FoldingSetNodeID ID;
1471     ID.AddInteger(scAddRecExpr);
1472     ID.AddPointer(PreStart);
1473     ID.AddPointer(Step);
1474     ID.AddPointer(L);
1475     void *IP = nullptr;
1476     const auto *PreAR =
1477       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1478 
1479     // Give up if we don't already have the add recurrence we need because
1480     // actually constructing an add recurrence is relatively expensive.
1481     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1482       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1483       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1484       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1485           DeltaS, &Pred, this);
1486       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1487         return true;
1488     }
1489   }
1490 
1491   return false;
1492 }
1493 
1494 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1495                                                Type *Ty) {
1496   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1497          "This is not an extending conversion!");
1498   assert(isSCEVable(Ty) &&
1499          "This is not a conversion to a SCEVable type!");
1500   Ty = getEffectiveSCEVType(Ty);
1501 
1502   // Fold if the operand is constant.
1503   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1504     return getConstant(
1505       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1506 
1507   // zext(zext(x)) --> zext(x)
1508   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1509     return getZeroExtendExpr(SZ->getOperand(), Ty);
1510 
1511   // Before doing any expensive analysis, check to see if we've already
1512   // computed a SCEV for this Op and Ty.
1513   FoldingSetNodeID ID;
1514   ID.AddInteger(scZeroExtend);
1515   ID.AddPointer(Op);
1516   ID.AddPointer(Ty);
1517   void *IP = nullptr;
1518   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1519 
1520   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1521   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1522     // It's possible the bits taken off by the truncate were all zero bits. If
1523     // so, we should be able to simplify this further.
1524     const SCEV *X = ST->getOperand();
1525     ConstantRange CR = getUnsignedRange(X);
1526     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1527     unsigned NewBits = getTypeSizeInBits(Ty);
1528     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1529             CR.zextOrTrunc(NewBits)))
1530       return getTruncateOrZeroExtend(X, Ty);
1531   }
1532 
1533   // If the input value is a chrec scev, and we can prove that the value
1534   // did not overflow the old, smaller, value, we can zero extend all of the
1535   // operands (often constants).  This allows analysis of something like
1536   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1537   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1538     if (AR->isAffine()) {
1539       const SCEV *Start = AR->getStart();
1540       const SCEV *Step = AR->getStepRecurrence(*this);
1541       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1542       const Loop *L = AR->getLoop();
1543 
1544       if (!AR->hasNoUnsignedWrap()) {
1545         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1546         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1547       }
1548 
1549       // If we have special knowledge that this addrec won't overflow,
1550       // we don't need to do any further analysis.
1551       if (AR->hasNoUnsignedWrap())
1552         return getAddRecExpr(
1553             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1554             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1555 
1556       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1557       // Note that this serves two purposes: It filters out loops that are
1558       // simply not analyzable, and it covers the case where this code is
1559       // being called from within backedge-taken count analysis, such that
1560       // attempting to ask for the backedge-taken count would likely result
1561       // in infinite recursion. In the later case, the analysis code will
1562       // cope with a conservative value, and it will take care to purge
1563       // that value once it has finished.
1564       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1565       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1566         // Manually compute the final value for AR, checking for
1567         // overflow.
1568 
1569         // Check whether the backedge-taken count can be losslessly casted to
1570         // the addrec's type. The count is always unsigned.
1571         const SCEV *CastedMaxBECount =
1572           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1573         const SCEV *RecastedMaxBECount =
1574           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1575         if (MaxBECount == RecastedMaxBECount) {
1576           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1577           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1578           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1579           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1580           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1581           const SCEV *WideMaxBECount =
1582             getZeroExtendExpr(CastedMaxBECount, WideTy);
1583           const SCEV *OperandExtendedAdd =
1584             getAddExpr(WideStart,
1585                        getMulExpr(WideMaxBECount,
1586                                   getZeroExtendExpr(Step, WideTy)));
1587           if (ZAdd == OperandExtendedAdd) {
1588             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1589             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1590             // Return the expression with the addrec on the outside.
1591             return getAddRecExpr(
1592                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1593                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1594           }
1595           // Similar to above, only this time treat the step value as signed.
1596           // This covers loops that count down.
1597           OperandExtendedAdd =
1598             getAddExpr(WideStart,
1599                        getMulExpr(WideMaxBECount,
1600                                   getSignExtendExpr(Step, WideTy)));
1601           if (ZAdd == OperandExtendedAdd) {
1602             // Cache knowledge of AR NW, which is propagated to this AddRec.
1603             // Negative step causes unsigned wrap, but it still can't self-wrap.
1604             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1605             // Return the expression with the addrec on the outside.
1606             return getAddRecExpr(
1607                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1608                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1609           }
1610         }
1611       }
1612 
1613       // Normally, in the cases we can prove no-overflow via a
1614       // backedge guarding condition, we can also compute a backedge
1615       // taken count for the loop.  The exceptions are assumptions and
1616       // guards present in the loop -- SCEV is not great at exploiting
1617       // these to compute max backedge taken counts, but can still use
1618       // these to prove lack of overflow.  Use this fact to avoid
1619       // doing extra work that may not pay off.
1620       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1621           !AC.assumptions().empty()) {
1622         // If the backedge is guarded by a comparison with the pre-inc
1623         // value the addrec is safe. Also, if the entry is guarded by
1624         // a comparison with the start value and the backedge is
1625         // guarded by a comparison with the post-inc value, the addrec
1626         // is safe.
1627         if (isKnownPositive(Step)) {
1628           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1629                                       getUnsignedRange(Step).getUnsignedMax());
1630           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1631               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1632                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1633                                            AR->getPostIncExpr(*this), N))) {
1634             // Cache knowledge of AR NUW, which is propagated to this
1635             // AddRec.
1636             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1637             // Return the expression with the addrec on the outside.
1638             return getAddRecExpr(
1639                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1640                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1641           }
1642         } else if (isKnownNegative(Step)) {
1643           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1644                                       getSignedRange(Step).getSignedMin());
1645           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1646               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1647                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1648                                            AR->getPostIncExpr(*this), N))) {
1649             // Cache knowledge of AR NW, which is propagated to this
1650             // AddRec.  Negative step causes unsigned wrap, but it
1651             // still can't self-wrap.
1652             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1653             // Return the expression with the addrec on the outside.
1654             return getAddRecExpr(
1655                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1656                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1657           }
1658         }
1659       }
1660 
1661       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1662         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1663         return getAddRecExpr(
1664             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1665             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1666       }
1667     }
1668 
1669   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1670     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1671     if (SA->hasNoUnsignedWrap()) {
1672       // If the addition does not unsign overflow then we can, by definition,
1673       // commute the zero extension with the addition operation.
1674       SmallVector<const SCEV *, 4> Ops;
1675       for (const auto *Op : SA->operands())
1676         Ops.push_back(getZeroExtendExpr(Op, Ty));
1677       return getAddExpr(Ops, SCEV::FlagNUW);
1678     }
1679   }
1680 
1681   // The cast wasn't folded; create an explicit cast node.
1682   // Recompute the insert position, as it may have been invalidated.
1683   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1684   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1685                                                    Op, Ty);
1686   UniqueSCEVs.InsertNode(S, IP);
1687   return S;
1688 }
1689 
1690 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1691                                                Type *Ty) {
1692   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1693          "This is not an extending conversion!");
1694   assert(isSCEVable(Ty) &&
1695          "This is not a conversion to a SCEVable type!");
1696   Ty = getEffectiveSCEVType(Ty);
1697 
1698   // Fold if the operand is constant.
1699   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1700     return getConstant(
1701       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1702 
1703   // sext(sext(x)) --> sext(x)
1704   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1705     return getSignExtendExpr(SS->getOperand(), Ty);
1706 
1707   // sext(zext(x)) --> zext(x)
1708   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1709     return getZeroExtendExpr(SZ->getOperand(), Ty);
1710 
1711   // Before doing any expensive analysis, check to see if we've already
1712   // computed a SCEV for this Op and Ty.
1713   FoldingSetNodeID ID;
1714   ID.AddInteger(scSignExtend);
1715   ID.AddPointer(Op);
1716   ID.AddPointer(Ty);
1717   void *IP = nullptr;
1718   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1719 
1720   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1721   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1722     // It's possible the bits taken off by the truncate were all sign bits. If
1723     // so, we should be able to simplify this further.
1724     const SCEV *X = ST->getOperand();
1725     ConstantRange CR = getSignedRange(X);
1726     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1727     unsigned NewBits = getTypeSizeInBits(Ty);
1728     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1729             CR.sextOrTrunc(NewBits)))
1730       return getTruncateOrSignExtend(X, Ty);
1731   }
1732 
1733   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1734   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1735     if (SA->getNumOperands() == 2) {
1736       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1737       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1738       if (SMul && SC1) {
1739         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1740           const APInt &C1 = SC1->getAPInt();
1741           const APInt &C2 = SC2->getAPInt();
1742           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1743               C2.ugt(C1) && C2.isPowerOf2())
1744             return getAddExpr(getSignExtendExpr(SC1, Ty),
1745                               getSignExtendExpr(SMul, Ty));
1746         }
1747       }
1748     }
1749 
1750     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1751     if (SA->hasNoSignedWrap()) {
1752       // If the addition does not sign overflow then we can, by definition,
1753       // commute the sign extension with the addition operation.
1754       SmallVector<const SCEV *, 4> Ops;
1755       for (const auto *Op : SA->operands())
1756         Ops.push_back(getSignExtendExpr(Op, Ty));
1757       return getAddExpr(Ops, SCEV::FlagNSW);
1758     }
1759   }
1760   // If the input value is a chrec scev, and we can prove that the value
1761   // did not overflow the old, smaller, value, we can sign extend all of the
1762   // operands (often constants).  This allows analysis of something like
1763   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1764   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1765     if (AR->isAffine()) {
1766       const SCEV *Start = AR->getStart();
1767       const SCEV *Step = AR->getStepRecurrence(*this);
1768       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1769       const Loop *L = AR->getLoop();
1770 
1771       if (!AR->hasNoSignedWrap()) {
1772         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1773         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1774       }
1775 
1776       // If we have special knowledge that this addrec won't overflow,
1777       // we don't need to do any further analysis.
1778       if (AR->hasNoSignedWrap())
1779         return getAddRecExpr(
1780             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1781             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1782 
1783       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1784       // Note that this serves two purposes: It filters out loops that are
1785       // simply not analyzable, and it covers the case where this code is
1786       // being called from within backedge-taken count analysis, such that
1787       // attempting to ask for the backedge-taken count would likely result
1788       // in infinite recursion. In the later case, the analysis code will
1789       // cope with a conservative value, and it will take care to purge
1790       // that value once it has finished.
1791       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1792       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1793         // Manually compute the final value for AR, checking for
1794         // overflow.
1795 
1796         // Check whether the backedge-taken count can be losslessly casted to
1797         // the addrec's type. The count is always unsigned.
1798         const SCEV *CastedMaxBECount =
1799           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1800         const SCEV *RecastedMaxBECount =
1801           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1802         if (MaxBECount == RecastedMaxBECount) {
1803           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1804           // Check whether Start+Step*MaxBECount has no signed overflow.
1805           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1806           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1807           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1808           const SCEV *WideMaxBECount =
1809             getZeroExtendExpr(CastedMaxBECount, WideTy);
1810           const SCEV *OperandExtendedAdd =
1811             getAddExpr(WideStart,
1812                        getMulExpr(WideMaxBECount,
1813                                   getSignExtendExpr(Step, WideTy)));
1814           if (SAdd == OperandExtendedAdd) {
1815             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1816             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1817             // Return the expression with the addrec on the outside.
1818             return getAddRecExpr(
1819                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1820                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1821           }
1822           // Similar to above, only this time treat the step value as unsigned.
1823           // This covers loops that count up with an unsigned step.
1824           OperandExtendedAdd =
1825             getAddExpr(WideStart,
1826                        getMulExpr(WideMaxBECount,
1827                                   getZeroExtendExpr(Step, WideTy)));
1828           if (SAdd == OperandExtendedAdd) {
1829             // If AR wraps around then
1830             //
1831             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1832             // => SAdd != OperandExtendedAdd
1833             //
1834             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1835             // (SAdd == OperandExtendedAdd => AR is NW)
1836 
1837             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1838 
1839             // Return the expression with the addrec on the outside.
1840             return getAddRecExpr(
1841                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1842                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1843           }
1844         }
1845       }
1846 
1847       // Normally, in the cases we can prove no-overflow via a
1848       // backedge guarding condition, we can also compute a backedge
1849       // taken count for the loop.  The exceptions are assumptions and
1850       // guards present in the loop -- SCEV is not great at exploiting
1851       // these to compute max backedge taken counts, but can still use
1852       // these to prove lack of overflow.  Use this fact to avoid
1853       // doing extra work that may not pay off.
1854 
1855       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1856           !AC.assumptions().empty()) {
1857         // If the backedge is guarded by a comparison with the pre-inc
1858         // value the addrec is safe. Also, if the entry is guarded by
1859         // a comparison with the start value and the backedge is
1860         // guarded by a comparison with the post-inc value, the addrec
1861         // is safe.
1862         ICmpInst::Predicate Pred;
1863         const SCEV *OverflowLimit =
1864             getSignedOverflowLimitForStep(Step, &Pred, this);
1865         if (OverflowLimit &&
1866             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1867              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1868               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1869                                           OverflowLimit)))) {
1870           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1871           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1872           return getAddRecExpr(
1873               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1874               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1875         }
1876       }
1877 
1878       // If Start and Step are constants, check if we can apply this
1879       // transformation:
1880       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1881       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1882       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1883       if (SC1 && SC2) {
1884         const APInt &C1 = SC1->getAPInt();
1885         const APInt &C2 = SC2->getAPInt();
1886         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1887             C2.isPowerOf2()) {
1888           Start = getSignExtendExpr(Start, Ty);
1889           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1890                                             AR->getNoWrapFlags());
1891           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1892         }
1893       }
1894 
1895       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1896         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1897         return getAddRecExpr(
1898             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1899             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1900       }
1901     }
1902 
1903   // If the input value is provably positive and we could not simplify
1904   // away the sext build a zext instead.
1905   if (isKnownNonNegative(Op))
1906     return getZeroExtendExpr(Op, Ty);
1907 
1908   // The cast wasn't folded; create an explicit cast node.
1909   // Recompute the insert position, as it may have been invalidated.
1910   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1911   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1912                                                    Op, Ty);
1913   UniqueSCEVs.InsertNode(S, IP);
1914   return S;
1915 }
1916 
1917 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1918 /// unspecified bits out to the given type.
1919 ///
1920 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1921                                               Type *Ty) {
1922   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1923          "This is not an extending conversion!");
1924   assert(isSCEVable(Ty) &&
1925          "This is not a conversion to a SCEVable type!");
1926   Ty = getEffectiveSCEVType(Ty);
1927 
1928   // Sign-extend negative constants.
1929   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1930     if (SC->getAPInt().isNegative())
1931       return getSignExtendExpr(Op, Ty);
1932 
1933   // Peel off a truncate cast.
1934   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1935     const SCEV *NewOp = T->getOperand();
1936     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1937       return getAnyExtendExpr(NewOp, Ty);
1938     return getTruncateOrNoop(NewOp, Ty);
1939   }
1940 
1941   // Next try a zext cast. If the cast is folded, use it.
1942   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1943   if (!isa<SCEVZeroExtendExpr>(ZExt))
1944     return ZExt;
1945 
1946   // Next try a sext cast. If the cast is folded, use it.
1947   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1948   if (!isa<SCEVSignExtendExpr>(SExt))
1949     return SExt;
1950 
1951   // Force the cast to be folded into the operands of an addrec.
1952   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1953     SmallVector<const SCEV *, 4> Ops;
1954     for (const SCEV *Op : AR->operands())
1955       Ops.push_back(getAnyExtendExpr(Op, Ty));
1956     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1957   }
1958 
1959   // If the expression is obviously signed, use the sext cast value.
1960   if (isa<SCEVSMaxExpr>(Op))
1961     return SExt;
1962 
1963   // Absent any other information, use the zext cast value.
1964   return ZExt;
1965 }
1966 
1967 /// Process the given Ops list, which is a list of operands to be added under
1968 /// the given scale, update the given map. This is a helper function for
1969 /// getAddRecExpr. As an example of what it does, given a sequence of operands
1970 /// that would form an add expression like this:
1971 ///
1972 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1973 ///
1974 /// where A and B are constants, update the map with these values:
1975 ///
1976 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1977 ///
1978 /// and add 13 + A*B*29 to AccumulatedConstant.
1979 /// This will allow getAddRecExpr to produce this:
1980 ///
1981 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1982 ///
1983 /// This form often exposes folding opportunities that are hidden in
1984 /// the original operand list.
1985 ///
1986 /// Return true iff it appears that any interesting folding opportunities
1987 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1988 /// the common case where no interesting opportunities are present, and
1989 /// is also used as a check to avoid infinite recursion.
1990 ///
1991 static bool
1992 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1993                              SmallVectorImpl<const SCEV *> &NewOps,
1994                              APInt &AccumulatedConstant,
1995                              const SCEV *const *Ops, size_t NumOperands,
1996                              const APInt &Scale,
1997                              ScalarEvolution &SE) {
1998   bool Interesting = false;
1999 
2000   // Iterate over the add operands. They are sorted, with constants first.
2001   unsigned i = 0;
2002   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2003     ++i;
2004     // Pull a buried constant out to the outside.
2005     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2006       Interesting = true;
2007     AccumulatedConstant += Scale * C->getAPInt();
2008   }
2009 
2010   // Next comes everything else. We're especially interested in multiplies
2011   // here, but they're in the middle, so just visit the rest with one loop.
2012   for (; i != NumOperands; ++i) {
2013     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2014     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2015       APInt NewScale =
2016           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2017       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2018         // A multiplication of a constant with another add; recurse.
2019         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2020         Interesting |=
2021           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2022                                        Add->op_begin(), Add->getNumOperands(),
2023                                        NewScale, SE);
2024       } else {
2025         // A multiplication of a constant with some other value. Update
2026         // the map.
2027         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2028         const SCEV *Key = SE.getMulExpr(MulOps);
2029         auto Pair = M.insert({Key, NewScale});
2030         if (Pair.second) {
2031           NewOps.push_back(Pair.first->first);
2032         } else {
2033           Pair.first->second += NewScale;
2034           // The map already had an entry for this value, which may indicate
2035           // a folding opportunity.
2036           Interesting = true;
2037         }
2038       }
2039     } else {
2040       // An ordinary operand. Update the map.
2041       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2042           M.insert({Ops[i], Scale});
2043       if (Pair.second) {
2044         NewOps.push_back(Pair.first->first);
2045       } else {
2046         Pair.first->second += Scale;
2047         // The map already had an entry for this value, which may indicate
2048         // a folding opportunity.
2049         Interesting = true;
2050       }
2051     }
2052   }
2053 
2054   return Interesting;
2055 }
2056 
2057 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2058 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2059 // can't-overflow flags for the operation if possible.
2060 static SCEV::NoWrapFlags
2061 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2062                       const SmallVectorImpl<const SCEV *> &Ops,
2063                       SCEV::NoWrapFlags Flags) {
2064   using namespace std::placeholders;
2065   typedef OverflowingBinaryOperator OBO;
2066 
2067   bool CanAnalyze =
2068       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2069   (void)CanAnalyze;
2070   assert(CanAnalyze && "don't call from other places!");
2071 
2072   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2073   SCEV::NoWrapFlags SignOrUnsignWrap =
2074       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2075 
2076   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2077   auto IsKnownNonNegative = [&](const SCEV *S) {
2078     return SE->isKnownNonNegative(S);
2079   };
2080 
2081   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2082     Flags =
2083         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2084 
2085   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2086 
2087   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2088       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2089 
2090     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2091     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2092 
2093     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2094     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2095       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2096           Instruction::Add, C, OBO::NoSignedWrap);
2097       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2098         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2099     }
2100     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2101       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2102           Instruction::Add, C, OBO::NoUnsignedWrap);
2103       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2104         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2105     }
2106   }
2107 
2108   return Flags;
2109 }
2110 
2111 /// Get a canonical add expression, or something simpler if possible.
2112 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2113                                         SCEV::NoWrapFlags Flags,
2114                                         unsigned Depth) {
2115   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2116          "only nuw or nsw allowed");
2117   assert(!Ops.empty() && "Cannot get empty add!");
2118   if (Ops.size() == 1) return Ops[0];
2119 #ifndef NDEBUG
2120   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2121   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2122     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2123            "SCEVAddExpr operand types don't match!");
2124 #endif
2125 
2126   // Sort by complexity, this groups all similar expression types together.
2127   GroupByComplexity(Ops, &LI);
2128 
2129   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2130 
2131   // If there are any constants, fold them together.
2132   unsigned Idx = 0;
2133   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2134     ++Idx;
2135     assert(Idx < Ops.size());
2136     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2137       // We found two constants, fold them together!
2138       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2139       if (Ops.size() == 2) return Ops[0];
2140       Ops.erase(Ops.begin()+1);  // Erase the folded element
2141       LHSC = cast<SCEVConstant>(Ops[0]);
2142     }
2143 
2144     // If we are left with a constant zero being added, strip it off.
2145     if (LHSC->getValue()->isZero()) {
2146       Ops.erase(Ops.begin());
2147       --Idx;
2148     }
2149 
2150     if (Ops.size() == 1) return Ops[0];
2151   }
2152 
2153   // Limit recursion calls depth
2154   if (Depth > MaxAddExprDepth)
2155     return getOrCreateAddExpr(Ops, Flags);
2156 
2157   // Okay, check to see if the same value occurs in the operand list more than
2158   // once.  If so, merge them together into an multiply expression.  Since we
2159   // sorted the list, these values are required to be adjacent.
2160   Type *Ty = Ops[0]->getType();
2161   bool FoundMatch = false;
2162   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2163     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2164       // Scan ahead to count how many equal operands there are.
2165       unsigned Count = 2;
2166       while (i+Count != e && Ops[i+Count] == Ops[i])
2167         ++Count;
2168       // Merge the values into a multiply.
2169       const SCEV *Scale = getConstant(Ty, Count);
2170       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2171       if (Ops.size() == Count)
2172         return Mul;
2173       Ops[i] = Mul;
2174       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2175       --i; e -= Count - 1;
2176       FoundMatch = true;
2177     }
2178   if (FoundMatch)
2179     return getAddExpr(Ops, Flags);
2180 
2181   // Check for truncates. If all the operands are truncated from the same
2182   // type, see if factoring out the truncate would permit the result to be
2183   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2184   // if the contents of the resulting outer trunc fold to something simple.
2185   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2186     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2187     Type *DstType = Trunc->getType();
2188     Type *SrcType = Trunc->getOperand()->getType();
2189     SmallVector<const SCEV *, 8> LargeOps;
2190     bool Ok = true;
2191     // Check all the operands to see if they can be represented in the
2192     // source type of the truncate.
2193     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2194       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2195         if (T->getOperand()->getType() != SrcType) {
2196           Ok = false;
2197           break;
2198         }
2199         LargeOps.push_back(T->getOperand());
2200       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2201         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2202       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2203         SmallVector<const SCEV *, 8> LargeMulOps;
2204         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2205           if (const SCEVTruncateExpr *T =
2206                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2207             if (T->getOperand()->getType() != SrcType) {
2208               Ok = false;
2209               break;
2210             }
2211             LargeMulOps.push_back(T->getOperand());
2212           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2213             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2214           } else {
2215             Ok = false;
2216             break;
2217           }
2218         }
2219         if (Ok)
2220           LargeOps.push_back(getMulExpr(LargeMulOps));
2221       } else {
2222         Ok = false;
2223         break;
2224       }
2225     }
2226     if (Ok) {
2227       // Evaluate the expression in the larger type.
2228       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2229       // If it folds to something simple, use it. Otherwise, don't.
2230       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2231         return getTruncateExpr(Fold, DstType);
2232     }
2233   }
2234 
2235   // Skip past any other cast SCEVs.
2236   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2237     ++Idx;
2238 
2239   // If there are add operands they would be next.
2240   if (Idx < Ops.size()) {
2241     bool DeletedAdd = false;
2242     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2243       if (Ops.size() > AddOpsInlineThreshold ||
2244           Add->getNumOperands() > AddOpsInlineThreshold)
2245         break;
2246       // If we have an add, expand the add operands onto the end of the operands
2247       // list.
2248       Ops.erase(Ops.begin()+Idx);
2249       Ops.append(Add->op_begin(), Add->op_end());
2250       DeletedAdd = true;
2251     }
2252 
2253     // If we deleted at least one add, we added operands to the end of the list,
2254     // and they are not necessarily sorted.  Recurse to resort and resimplify
2255     // any operands we just acquired.
2256     if (DeletedAdd)
2257       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2258   }
2259 
2260   // Skip over the add expression until we get to a multiply.
2261   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2262     ++Idx;
2263 
2264   // Check to see if there are any folding opportunities present with
2265   // operands multiplied by constant values.
2266   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2267     uint64_t BitWidth = getTypeSizeInBits(Ty);
2268     DenseMap<const SCEV *, APInt> M;
2269     SmallVector<const SCEV *, 8> NewOps;
2270     APInt AccumulatedConstant(BitWidth, 0);
2271     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2272                                      Ops.data(), Ops.size(),
2273                                      APInt(BitWidth, 1), *this)) {
2274       struct APIntCompare {
2275         bool operator()(const APInt &LHS, const APInt &RHS) const {
2276           return LHS.ult(RHS);
2277         }
2278       };
2279 
2280       // Some interesting folding opportunity is present, so its worthwhile to
2281       // re-generate the operands list. Group the operands by constant scale,
2282       // to avoid multiplying by the same constant scale multiple times.
2283       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2284       for (const SCEV *NewOp : NewOps)
2285         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2286       // Re-generate the operands list.
2287       Ops.clear();
2288       if (AccumulatedConstant != 0)
2289         Ops.push_back(getConstant(AccumulatedConstant));
2290       for (auto &MulOp : MulOpLists)
2291         if (MulOp.first != 0)
2292           Ops.push_back(getMulExpr(
2293               getConstant(MulOp.first),
2294               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2295       if (Ops.empty())
2296         return getZero(Ty);
2297       if (Ops.size() == 1)
2298         return Ops[0];
2299       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2300     }
2301   }
2302 
2303   // If we are adding something to a multiply expression, make sure the
2304   // something is not already an operand of the multiply.  If so, merge it into
2305   // the multiply.
2306   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2307     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2308     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2309       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2310       if (isa<SCEVConstant>(MulOpSCEV))
2311         continue;
2312       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2313         if (MulOpSCEV == Ops[AddOp]) {
2314           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2315           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2316           if (Mul->getNumOperands() != 2) {
2317             // If the multiply has more than two operands, we must get the
2318             // Y*Z term.
2319             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2320                                                 Mul->op_begin()+MulOp);
2321             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2322             InnerMul = getMulExpr(MulOps);
2323           }
2324           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2325           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2326           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2327           if (Ops.size() == 2) return OuterMul;
2328           if (AddOp < Idx) {
2329             Ops.erase(Ops.begin()+AddOp);
2330             Ops.erase(Ops.begin()+Idx-1);
2331           } else {
2332             Ops.erase(Ops.begin()+Idx);
2333             Ops.erase(Ops.begin()+AddOp-1);
2334           }
2335           Ops.push_back(OuterMul);
2336           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2337         }
2338 
2339       // Check this multiply against other multiplies being added together.
2340       for (unsigned OtherMulIdx = Idx+1;
2341            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2342            ++OtherMulIdx) {
2343         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2344         // If MulOp occurs in OtherMul, we can fold the two multiplies
2345         // together.
2346         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2347              OMulOp != e; ++OMulOp)
2348           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2349             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2350             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2351             if (Mul->getNumOperands() != 2) {
2352               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2353                                                   Mul->op_begin()+MulOp);
2354               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2355               InnerMul1 = getMulExpr(MulOps);
2356             }
2357             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2358             if (OtherMul->getNumOperands() != 2) {
2359               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2360                                                   OtherMul->op_begin()+OMulOp);
2361               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2362               InnerMul2 = getMulExpr(MulOps);
2363             }
2364             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2365             const SCEV *InnerMulSum =
2366                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2367             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2368             if (Ops.size() == 2) return OuterMul;
2369             Ops.erase(Ops.begin()+Idx);
2370             Ops.erase(Ops.begin()+OtherMulIdx-1);
2371             Ops.push_back(OuterMul);
2372             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2373           }
2374       }
2375     }
2376   }
2377 
2378   // If there are any add recurrences in the operands list, see if any other
2379   // added values are loop invariant.  If so, we can fold them into the
2380   // recurrence.
2381   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2382     ++Idx;
2383 
2384   // Scan over all recurrences, trying to fold loop invariants into them.
2385   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2386     // Scan all of the other operands to this add and add them to the vector if
2387     // they are loop invariant w.r.t. the recurrence.
2388     SmallVector<const SCEV *, 8> LIOps;
2389     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2390     const Loop *AddRecLoop = AddRec->getLoop();
2391     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2392       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2393         LIOps.push_back(Ops[i]);
2394         Ops.erase(Ops.begin()+i);
2395         --i; --e;
2396       }
2397 
2398     // If we found some loop invariants, fold them into the recurrence.
2399     if (!LIOps.empty()) {
2400       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2401       LIOps.push_back(AddRec->getStart());
2402 
2403       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2404                                              AddRec->op_end());
2405       // This follows from the fact that the no-wrap flags on the outer add
2406       // expression are applicable on the 0th iteration, when the add recurrence
2407       // will be equal to its start value.
2408       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2409 
2410       // Build the new addrec. Propagate the NUW and NSW flags if both the
2411       // outer add and the inner addrec are guaranteed to have no overflow.
2412       // Always propagate NW.
2413       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2414       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2415 
2416       // If all of the other operands were loop invariant, we are done.
2417       if (Ops.size() == 1) return NewRec;
2418 
2419       // Otherwise, add the folded AddRec by the non-invariant parts.
2420       for (unsigned i = 0;; ++i)
2421         if (Ops[i] == AddRec) {
2422           Ops[i] = NewRec;
2423           break;
2424         }
2425       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2426     }
2427 
2428     // Okay, if there weren't any loop invariants to be folded, check to see if
2429     // there are multiple AddRec's with the same loop induction variable being
2430     // added together.  If so, we can fold them.
2431     for (unsigned OtherIdx = Idx+1;
2432          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2433          ++OtherIdx)
2434       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2435         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2436         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2437                                                AddRec->op_end());
2438         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2439              ++OtherIdx)
2440           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2441             if (OtherAddRec->getLoop() == AddRecLoop) {
2442               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2443                    i != e; ++i) {
2444                 if (i >= AddRecOps.size()) {
2445                   AddRecOps.append(OtherAddRec->op_begin()+i,
2446                                    OtherAddRec->op_end());
2447                   break;
2448                 }
2449                 SmallVector<const SCEV *, 2> TwoOps = {
2450                     AddRecOps[i], OtherAddRec->getOperand(i)};
2451                 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2452               }
2453               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2454             }
2455         // Step size has changed, so we cannot guarantee no self-wraparound.
2456         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2457         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2458       }
2459 
2460     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2461     // next one.
2462   }
2463 
2464   // Okay, it looks like we really DO need an add expr.  Check to see if we
2465   // already have one, otherwise create a new one.
2466   return getOrCreateAddExpr(Ops, Flags);
2467 }
2468 
2469 const SCEV *
2470 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2471                                     SCEV::NoWrapFlags Flags) {
2472   FoldingSetNodeID ID;
2473   ID.AddInteger(scAddExpr);
2474   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2475     ID.AddPointer(Ops[i]);
2476   void *IP = nullptr;
2477   SCEVAddExpr *S =
2478       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2479   if (!S) {
2480     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2481     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2482     S = new (SCEVAllocator)
2483         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2484     UniqueSCEVs.InsertNode(S, IP);
2485   }
2486   S->setNoWrapFlags(Flags);
2487   return S;
2488 }
2489 
2490 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2491   uint64_t k = i*j;
2492   if (j > 1 && k / j != i) Overflow = true;
2493   return k;
2494 }
2495 
2496 /// Compute the result of "n choose k", the binomial coefficient.  If an
2497 /// intermediate computation overflows, Overflow will be set and the return will
2498 /// be garbage. Overflow is not cleared on absence of overflow.
2499 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2500   // We use the multiplicative formula:
2501   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2502   // At each iteration, we take the n-th term of the numeral and divide by the
2503   // (k-n)th term of the denominator.  This division will always produce an
2504   // integral result, and helps reduce the chance of overflow in the
2505   // intermediate computations. However, we can still overflow even when the
2506   // final result would fit.
2507 
2508   if (n == 0 || n == k) return 1;
2509   if (k > n) return 0;
2510 
2511   if (k > n/2)
2512     k = n-k;
2513 
2514   uint64_t r = 1;
2515   for (uint64_t i = 1; i <= k; ++i) {
2516     r = umul_ov(r, n-(i-1), Overflow);
2517     r /= i;
2518   }
2519   return r;
2520 }
2521 
2522 /// Determine if any of the operands in this SCEV are a constant or if
2523 /// any of the add or multiply expressions in this SCEV contain a constant.
2524 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2525   SmallVector<const SCEV *, 4> Ops;
2526   Ops.push_back(StartExpr);
2527   while (!Ops.empty()) {
2528     const SCEV *CurrentExpr = Ops.pop_back_val();
2529     if (isa<SCEVConstant>(*CurrentExpr))
2530       return true;
2531 
2532     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2533       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2534       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2535     }
2536   }
2537   return false;
2538 }
2539 
2540 /// Get a canonical multiply expression, or something simpler if possible.
2541 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2542                                         SCEV::NoWrapFlags Flags) {
2543   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2544          "only nuw or nsw allowed");
2545   assert(!Ops.empty() && "Cannot get empty mul!");
2546   if (Ops.size() == 1) return Ops[0];
2547 #ifndef NDEBUG
2548   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2549   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2550     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2551            "SCEVMulExpr operand types don't match!");
2552 #endif
2553 
2554   // Sort by complexity, this groups all similar expression types together.
2555   GroupByComplexity(Ops, &LI);
2556 
2557   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2558 
2559   // If there are any constants, fold them together.
2560   unsigned Idx = 0;
2561   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2562 
2563     // C1*(C2+V) -> C1*C2 + C1*V
2564     if (Ops.size() == 2)
2565         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2566           // If any of Add's ops are Adds or Muls with a constant,
2567           // apply this transformation as well.
2568           if (Add->getNumOperands() == 2)
2569             if (containsConstantSomewhere(Add))
2570               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2571                                 getMulExpr(LHSC, Add->getOperand(1)));
2572 
2573     ++Idx;
2574     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2575       // We found two constants, fold them together!
2576       ConstantInt *Fold =
2577           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2578       Ops[0] = getConstant(Fold);
2579       Ops.erase(Ops.begin()+1);  // Erase the folded element
2580       if (Ops.size() == 1) return Ops[0];
2581       LHSC = cast<SCEVConstant>(Ops[0]);
2582     }
2583 
2584     // If we are left with a constant one being multiplied, strip it off.
2585     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2586       Ops.erase(Ops.begin());
2587       --Idx;
2588     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2589       // If we have a multiply of zero, it will always be zero.
2590       return Ops[0];
2591     } else if (Ops[0]->isAllOnesValue()) {
2592       // If we have a mul by -1 of an add, try distributing the -1 among the
2593       // add operands.
2594       if (Ops.size() == 2) {
2595         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2596           SmallVector<const SCEV *, 4> NewOps;
2597           bool AnyFolded = false;
2598           for (const SCEV *AddOp : Add->operands()) {
2599             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2600             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2601             NewOps.push_back(Mul);
2602           }
2603           if (AnyFolded)
2604             return getAddExpr(NewOps);
2605         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2606           // Negation preserves a recurrence's no self-wrap property.
2607           SmallVector<const SCEV *, 4> Operands;
2608           for (const SCEV *AddRecOp : AddRec->operands())
2609             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2610 
2611           return getAddRecExpr(Operands, AddRec->getLoop(),
2612                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2613         }
2614       }
2615     }
2616 
2617     if (Ops.size() == 1)
2618       return Ops[0];
2619   }
2620 
2621   // Skip over the add expression until we get to a multiply.
2622   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2623     ++Idx;
2624 
2625   // If there are mul operands inline them all into this expression.
2626   if (Idx < Ops.size()) {
2627     bool DeletedMul = false;
2628     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2629       if (Ops.size() > MulOpsInlineThreshold)
2630         break;
2631       // If we have an mul, expand the mul operands onto the end of the operands
2632       // list.
2633       Ops.erase(Ops.begin()+Idx);
2634       Ops.append(Mul->op_begin(), Mul->op_end());
2635       DeletedMul = true;
2636     }
2637 
2638     // If we deleted at least one mul, we added operands to the end of the list,
2639     // and they are not necessarily sorted.  Recurse to resort and resimplify
2640     // any operands we just acquired.
2641     if (DeletedMul)
2642       return getMulExpr(Ops);
2643   }
2644 
2645   // If there are any add recurrences in the operands list, see if any other
2646   // added values are loop invariant.  If so, we can fold them into the
2647   // recurrence.
2648   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2649     ++Idx;
2650 
2651   // Scan over all recurrences, trying to fold loop invariants into them.
2652   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2653     // Scan all of the other operands to this mul and add them to the vector if
2654     // they are loop invariant w.r.t. the recurrence.
2655     SmallVector<const SCEV *, 8> LIOps;
2656     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2657     const Loop *AddRecLoop = AddRec->getLoop();
2658     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2659       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2660         LIOps.push_back(Ops[i]);
2661         Ops.erase(Ops.begin()+i);
2662         --i; --e;
2663       }
2664 
2665     // If we found some loop invariants, fold them into the recurrence.
2666     if (!LIOps.empty()) {
2667       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2668       SmallVector<const SCEV *, 4> NewOps;
2669       NewOps.reserve(AddRec->getNumOperands());
2670       const SCEV *Scale = getMulExpr(LIOps);
2671       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2672         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2673 
2674       // Build the new addrec. Propagate the NUW and NSW flags if both the
2675       // outer mul and the inner addrec are guaranteed to have no overflow.
2676       //
2677       // No self-wrap cannot be guaranteed after changing the step size, but
2678       // will be inferred if either NUW or NSW is true.
2679       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2680       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2681 
2682       // If all of the other operands were loop invariant, we are done.
2683       if (Ops.size() == 1) return NewRec;
2684 
2685       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2686       for (unsigned i = 0;; ++i)
2687         if (Ops[i] == AddRec) {
2688           Ops[i] = NewRec;
2689           break;
2690         }
2691       return getMulExpr(Ops);
2692     }
2693 
2694     // Okay, if there weren't any loop invariants to be folded, check to see if
2695     // there are multiple AddRec's with the same loop induction variable being
2696     // multiplied together.  If so, we can fold them.
2697 
2698     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2699     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2700     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2701     //   ]]],+,...up to x=2n}.
2702     // Note that the arguments to choose() are always integers with values
2703     // known at compile time, never SCEV objects.
2704     //
2705     // The implementation avoids pointless extra computations when the two
2706     // addrec's are of different length (mathematically, it's equivalent to
2707     // an infinite stream of zeros on the right).
2708     bool OpsModified = false;
2709     for (unsigned OtherIdx = Idx+1;
2710          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2711          ++OtherIdx) {
2712       const SCEVAddRecExpr *OtherAddRec =
2713         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2714       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2715         continue;
2716 
2717       bool Overflow = false;
2718       Type *Ty = AddRec->getType();
2719       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2720       SmallVector<const SCEV*, 7> AddRecOps;
2721       for (int x = 0, xe = AddRec->getNumOperands() +
2722              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2723         const SCEV *Term = getZero(Ty);
2724         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2725           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2726           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2727                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2728                z < ze && !Overflow; ++z) {
2729             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2730             uint64_t Coeff;
2731             if (LargerThan64Bits)
2732               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2733             else
2734               Coeff = Coeff1*Coeff2;
2735             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2736             const SCEV *Term1 = AddRec->getOperand(y-z);
2737             const SCEV *Term2 = OtherAddRec->getOperand(z);
2738             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2739           }
2740         }
2741         AddRecOps.push_back(Term);
2742       }
2743       if (!Overflow) {
2744         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2745                                               SCEV::FlagAnyWrap);
2746         if (Ops.size() == 2) return NewAddRec;
2747         Ops[Idx] = NewAddRec;
2748         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2749         OpsModified = true;
2750         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2751         if (!AddRec)
2752           break;
2753       }
2754     }
2755     if (OpsModified)
2756       return getMulExpr(Ops);
2757 
2758     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2759     // next one.
2760   }
2761 
2762   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2763   // already have one, otherwise create a new one.
2764   FoldingSetNodeID ID;
2765   ID.AddInteger(scMulExpr);
2766   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2767     ID.AddPointer(Ops[i]);
2768   void *IP = nullptr;
2769   SCEVMulExpr *S =
2770     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2771   if (!S) {
2772     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2773     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2774     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2775                                         O, Ops.size());
2776     UniqueSCEVs.InsertNode(S, IP);
2777   }
2778   S->setNoWrapFlags(Flags);
2779   return S;
2780 }
2781 
2782 /// Get a canonical unsigned division expression, or something simpler if
2783 /// possible.
2784 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2785                                          const SCEV *RHS) {
2786   assert(getEffectiveSCEVType(LHS->getType()) ==
2787          getEffectiveSCEVType(RHS->getType()) &&
2788          "SCEVUDivExpr operand types don't match!");
2789 
2790   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2791     if (RHSC->getValue()->equalsInt(1))
2792       return LHS;                               // X udiv 1 --> x
2793     // If the denominator is zero, the result of the udiv is undefined. Don't
2794     // try to analyze it, because the resolution chosen here may differ from
2795     // the resolution chosen in other parts of the compiler.
2796     if (!RHSC->getValue()->isZero()) {
2797       // Determine if the division can be folded into the operands of
2798       // its operands.
2799       // TODO: Generalize this to non-constants by using known-bits information.
2800       Type *Ty = LHS->getType();
2801       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2802       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2803       // For non-power-of-two values, effectively round the value up to the
2804       // nearest power of two.
2805       if (!RHSC->getAPInt().isPowerOf2())
2806         ++MaxShiftAmt;
2807       IntegerType *ExtTy =
2808         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2809       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2810         if (const SCEVConstant *Step =
2811             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2812           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2813           const APInt &StepInt = Step->getAPInt();
2814           const APInt &DivInt = RHSC->getAPInt();
2815           if (!StepInt.urem(DivInt) &&
2816               getZeroExtendExpr(AR, ExtTy) ==
2817               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2818                             getZeroExtendExpr(Step, ExtTy),
2819                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2820             SmallVector<const SCEV *, 4> Operands;
2821             for (const SCEV *Op : AR->operands())
2822               Operands.push_back(getUDivExpr(Op, RHS));
2823             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2824           }
2825           /// Get a canonical UDivExpr for a recurrence.
2826           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2827           // We can currently only fold X%N if X is constant.
2828           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2829           if (StartC && !DivInt.urem(StepInt) &&
2830               getZeroExtendExpr(AR, ExtTy) ==
2831               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2832                             getZeroExtendExpr(Step, ExtTy),
2833                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2834             const APInt &StartInt = StartC->getAPInt();
2835             const APInt &StartRem = StartInt.urem(StepInt);
2836             if (StartRem != 0)
2837               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2838                                   AR->getLoop(), SCEV::FlagNW);
2839           }
2840         }
2841       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2842       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2843         SmallVector<const SCEV *, 4> Operands;
2844         for (const SCEV *Op : M->operands())
2845           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2846         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2847           // Find an operand that's safely divisible.
2848           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2849             const SCEV *Op = M->getOperand(i);
2850             const SCEV *Div = getUDivExpr(Op, RHSC);
2851             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2852               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2853                                                       M->op_end());
2854               Operands[i] = Div;
2855               return getMulExpr(Operands);
2856             }
2857           }
2858       }
2859       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2860       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2861         SmallVector<const SCEV *, 4> Operands;
2862         for (const SCEV *Op : A->operands())
2863           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2864         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2865           Operands.clear();
2866           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2867             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2868             if (isa<SCEVUDivExpr>(Op) ||
2869                 getMulExpr(Op, RHS) != A->getOperand(i))
2870               break;
2871             Operands.push_back(Op);
2872           }
2873           if (Operands.size() == A->getNumOperands())
2874             return getAddExpr(Operands);
2875         }
2876       }
2877 
2878       // Fold if both operands are constant.
2879       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2880         Constant *LHSCV = LHSC->getValue();
2881         Constant *RHSCV = RHSC->getValue();
2882         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2883                                                                    RHSCV)));
2884       }
2885     }
2886   }
2887 
2888   FoldingSetNodeID ID;
2889   ID.AddInteger(scUDivExpr);
2890   ID.AddPointer(LHS);
2891   ID.AddPointer(RHS);
2892   void *IP = nullptr;
2893   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2894   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2895                                              LHS, RHS);
2896   UniqueSCEVs.InsertNode(S, IP);
2897   return S;
2898 }
2899 
2900 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2901   APInt A = C1->getAPInt().abs();
2902   APInt B = C2->getAPInt().abs();
2903   uint32_t ABW = A.getBitWidth();
2904   uint32_t BBW = B.getBitWidth();
2905 
2906   if (ABW > BBW)
2907     B = B.zext(ABW);
2908   else if (ABW < BBW)
2909     A = A.zext(BBW);
2910 
2911   return APIntOps::GreatestCommonDivisor(A, B);
2912 }
2913 
2914 /// Get a canonical unsigned division expression, or something simpler if
2915 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2916 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2917 /// it's not exact because the udiv may be clearing bits.
2918 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2919                                               const SCEV *RHS) {
2920   // TODO: we could try to find factors in all sorts of things, but for now we
2921   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2922   // end of this file for inspiration.
2923 
2924   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2925   if (!Mul || !Mul->hasNoUnsignedWrap())
2926     return getUDivExpr(LHS, RHS);
2927 
2928   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2929     // If the mulexpr multiplies by a constant, then that constant must be the
2930     // first element of the mulexpr.
2931     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2932       if (LHSCst == RHSCst) {
2933         SmallVector<const SCEV *, 2> Operands;
2934         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2935         return getMulExpr(Operands);
2936       }
2937 
2938       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2939       // that there's a factor provided by one of the other terms. We need to
2940       // check.
2941       APInt Factor = gcd(LHSCst, RHSCst);
2942       if (!Factor.isIntN(1)) {
2943         LHSCst =
2944             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2945         RHSCst =
2946             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
2947         SmallVector<const SCEV *, 2> Operands;
2948         Operands.push_back(LHSCst);
2949         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2950         LHS = getMulExpr(Operands);
2951         RHS = RHSCst;
2952         Mul = dyn_cast<SCEVMulExpr>(LHS);
2953         if (!Mul)
2954           return getUDivExactExpr(LHS, RHS);
2955       }
2956     }
2957   }
2958 
2959   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2960     if (Mul->getOperand(i) == RHS) {
2961       SmallVector<const SCEV *, 2> Operands;
2962       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2963       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2964       return getMulExpr(Operands);
2965     }
2966   }
2967 
2968   return getUDivExpr(LHS, RHS);
2969 }
2970 
2971 /// Get an add recurrence expression for the specified loop.  Simplify the
2972 /// expression as much as possible.
2973 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2974                                            const Loop *L,
2975                                            SCEV::NoWrapFlags Flags) {
2976   SmallVector<const SCEV *, 4> Operands;
2977   Operands.push_back(Start);
2978   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2979     if (StepChrec->getLoop() == L) {
2980       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2981       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2982     }
2983 
2984   Operands.push_back(Step);
2985   return getAddRecExpr(Operands, L, Flags);
2986 }
2987 
2988 /// Get an add recurrence expression for the specified loop.  Simplify the
2989 /// expression as much as possible.
2990 const SCEV *
2991 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2992                                const Loop *L, SCEV::NoWrapFlags Flags) {
2993   if (Operands.size() == 1) return Operands[0];
2994 #ifndef NDEBUG
2995   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2996   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2997     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2998            "SCEVAddRecExpr operand types don't match!");
2999   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3000     assert(isLoopInvariant(Operands[i], L) &&
3001            "SCEVAddRecExpr operand is not loop-invariant!");
3002 #endif
3003 
3004   if (Operands.back()->isZero()) {
3005     Operands.pop_back();
3006     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3007   }
3008 
3009   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3010   // use that information to infer NUW and NSW flags. However, computing a
3011   // BE count requires calling getAddRecExpr, so we may not yet have a
3012   // meaningful BE count at this point (and if we don't, we'd be stuck
3013   // with a SCEVCouldNotCompute as the cached BE count).
3014 
3015   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3016 
3017   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3018   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3019     const Loop *NestedLoop = NestedAR->getLoop();
3020     if (L->contains(NestedLoop)
3021             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3022             : (!NestedLoop->contains(L) &&
3023                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3024       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3025                                                   NestedAR->op_end());
3026       Operands[0] = NestedAR->getStart();
3027       // AddRecs require their operands be loop-invariant with respect to their
3028       // loops. Don't perform this transformation if it would break this
3029       // requirement.
3030       bool AllInvariant = all_of(
3031           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3032 
3033       if (AllInvariant) {
3034         // Create a recurrence for the outer loop with the same step size.
3035         //
3036         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3037         // inner recurrence has the same property.
3038         SCEV::NoWrapFlags OuterFlags =
3039           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3040 
3041         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3042         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3043           return isLoopInvariant(Op, NestedLoop);
3044         });
3045 
3046         if (AllInvariant) {
3047           // Ok, both add recurrences are valid after the transformation.
3048           //
3049           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3050           // the outer recurrence has the same property.
3051           SCEV::NoWrapFlags InnerFlags =
3052             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3053           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3054         }
3055       }
3056       // Reset Operands to its original state.
3057       Operands[0] = NestedAR;
3058     }
3059   }
3060 
3061   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3062   // already have one, otherwise create a new one.
3063   FoldingSetNodeID ID;
3064   ID.AddInteger(scAddRecExpr);
3065   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3066     ID.AddPointer(Operands[i]);
3067   ID.AddPointer(L);
3068   void *IP = nullptr;
3069   SCEVAddRecExpr *S =
3070     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3071   if (!S) {
3072     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3073     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3074     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3075                                            O, Operands.size(), L);
3076     UniqueSCEVs.InsertNode(S, IP);
3077   }
3078   S->setNoWrapFlags(Flags);
3079   return S;
3080 }
3081 
3082 const SCEV *
3083 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3084                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3085   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3086   // getSCEV(Base)->getType() has the same address space as Base->getType()
3087   // because SCEV::getType() preserves the address space.
3088   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3089   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3090   // instruction to its SCEV, because the Instruction may be guarded by control
3091   // flow and the no-overflow bits may not be valid for the expression in any
3092   // context. This can be fixed similarly to how these flags are handled for
3093   // adds.
3094   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3095                                              : SCEV::FlagAnyWrap;
3096 
3097   const SCEV *TotalOffset = getZero(IntPtrTy);
3098   // The array size is unimportant. The first thing we do on CurTy is getting
3099   // its element type.
3100   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3101   for (const SCEV *IndexExpr : IndexExprs) {
3102     // Compute the (potentially symbolic) offset in bytes for this index.
3103     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3104       // For a struct, add the member offset.
3105       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3106       unsigned FieldNo = Index->getZExtValue();
3107       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3108 
3109       // Add the field offset to the running total offset.
3110       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3111 
3112       // Update CurTy to the type of the field at Index.
3113       CurTy = STy->getTypeAtIndex(Index);
3114     } else {
3115       // Update CurTy to its element type.
3116       CurTy = cast<SequentialType>(CurTy)->getElementType();
3117       // For an array, add the element offset, explicitly scaled.
3118       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3119       // Getelementptr indices are signed.
3120       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3121 
3122       // Multiply the index by the element size to compute the element offset.
3123       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3124 
3125       // Add the element offset to the running total offset.
3126       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3127     }
3128   }
3129 
3130   // Add the total offset from all the GEP indices to the base.
3131   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3132 }
3133 
3134 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3135                                          const SCEV *RHS) {
3136   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3137   return getSMaxExpr(Ops);
3138 }
3139 
3140 const SCEV *
3141 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3142   assert(!Ops.empty() && "Cannot get empty smax!");
3143   if (Ops.size() == 1) return Ops[0];
3144 #ifndef NDEBUG
3145   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3146   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3147     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3148            "SCEVSMaxExpr operand types don't match!");
3149 #endif
3150 
3151   // Sort by complexity, this groups all similar expression types together.
3152   GroupByComplexity(Ops, &LI);
3153 
3154   // If there are any constants, fold them together.
3155   unsigned Idx = 0;
3156   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3157     ++Idx;
3158     assert(Idx < Ops.size());
3159     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3160       // We found two constants, fold them together!
3161       ConstantInt *Fold = ConstantInt::get(
3162           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3163       Ops[0] = getConstant(Fold);
3164       Ops.erase(Ops.begin()+1);  // Erase the folded element
3165       if (Ops.size() == 1) return Ops[0];
3166       LHSC = cast<SCEVConstant>(Ops[0]);
3167     }
3168 
3169     // If we are left with a constant minimum-int, strip it off.
3170     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3171       Ops.erase(Ops.begin());
3172       --Idx;
3173     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3174       // If we have an smax with a constant maximum-int, it will always be
3175       // maximum-int.
3176       return Ops[0];
3177     }
3178 
3179     if (Ops.size() == 1) return Ops[0];
3180   }
3181 
3182   // Find the first SMax
3183   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3184     ++Idx;
3185 
3186   // Check to see if one of the operands is an SMax. If so, expand its operands
3187   // onto our operand list, and recurse to simplify.
3188   if (Idx < Ops.size()) {
3189     bool DeletedSMax = false;
3190     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3191       Ops.erase(Ops.begin()+Idx);
3192       Ops.append(SMax->op_begin(), SMax->op_end());
3193       DeletedSMax = true;
3194     }
3195 
3196     if (DeletedSMax)
3197       return getSMaxExpr(Ops);
3198   }
3199 
3200   // Okay, check to see if the same value occurs in the operand list twice.  If
3201   // so, delete one.  Since we sorted the list, these values are required to
3202   // be adjacent.
3203   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3204     //  X smax Y smax Y  -->  X smax Y
3205     //  X smax Y         -->  X, if X is always greater than Y
3206     if (Ops[i] == Ops[i+1] ||
3207         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3208       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3209       --i; --e;
3210     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3211       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3212       --i; --e;
3213     }
3214 
3215   if (Ops.size() == 1) return Ops[0];
3216 
3217   assert(!Ops.empty() && "Reduced smax down to nothing!");
3218 
3219   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3220   // already have one, otherwise create a new one.
3221   FoldingSetNodeID ID;
3222   ID.AddInteger(scSMaxExpr);
3223   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3224     ID.AddPointer(Ops[i]);
3225   void *IP = nullptr;
3226   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3227   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3228   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3229   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3230                                              O, Ops.size());
3231   UniqueSCEVs.InsertNode(S, IP);
3232   return S;
3233 }
3234 
3235 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3236                                          const SCEV *RHS) {
3237   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3238   return getUMaxExpr(Ops);
3239 }
3240 
3241 const SCEV *
3242 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3243   assert(!Ops.empty() && "Cannot get empty umax!");
3244   if (Ops.size() == 1) return Ops[0];
3245 #ifndef NDEBUG
3246   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3247   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3248     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3249            "SCEVUMaxExpr operand types don't match!");
3250 #endif
3251 
3252   // Sort by complexity, this groups all similar expression types together.
3253   GroupByComplexity(Ops, &LI);
3254 
3255   // If there are any constants, fold them together.
3256   unsigned Idx = 0;
3257   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3258     ++Idx;
3259     assert(Idx < Ops.size());
3260     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3261       // We found two constants, fold them together!
3262       ConstantInt *Fold = ConstantInt::get(
3263           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3264       Ops[0] = getConstant(Fold);
3265       Ops.erase(Ops.begin()+1);  // Erase the folded element
3266       if (Ops.size() == 1) return Ops[0];
3267       LHSC = cast<SCEVConstant>(Ops[0]);
3268     }
3269 
3270     // If we are left with a constant minimum-int, strip it off.
3271     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3272       Ops.erase(Ops.begin());
3273       --Idx;
3274     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3275       // If we have an umax with a constant maximum-int, it will always be
3276       // maximum-int.
3277       return Ops[0];
3278     }
3279 
3280     if (Ops.size() == 1) return Ops[0];
3281   }
3282 
3283   // Find the first UMax
3284   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3285     ++Idx;
3286 
3287   // Check to see if one of the operands is a UMax. If so, expand its operands
3288   // onto our operand list, and recurse to simplify.
3289   if (Idx < Ops.size()) {
3290     bool DeletedUMax = false;
3291     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3292       Ops.erase(Ops.begin()+Idx);
3293       Ops.append(UMax->op_begin(), UMax->op_end());
3294       DeletedUMax = true;
3295     }
3296 
3297     if (DeletedUMax)
3298       return getUMaxExpr(Ops);
3299   }
3300 
3301   // Okay, check to see if the same value occurs in the operand list twice.  If
3302   // so, delete one.  Since we sorted the list, these values are required to
3303   // be adjacent.
3304   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3305     //  X umax Y umax Y  -->  X umax Y
3306     //  X umax Y         -->  X, if X is always greater than Y
3307     if (Ops[i] == Ops[i+1] ||
3308         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3309       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3310       --i; --e;
3311     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3312       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3313       --i; --e;
3314     }
3315 
3316   if (Ops.size() == 1) return Ops[0];
3317 
3318   assert(!Ops.empty() && "Reduced umax down to nothing!");
3319 
3320   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3321   // already have one, otherwise create a new one.
3322   FoldingSetNodeID ID;
3323   ID.AddInteger(scUMaxExpr);
3324   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3325     ID.AddPointer(Ops[i]);
3326   void *IP = nullptr;
3327   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3328   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3329   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3330   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3331                                              O, Ops.size());
3332   UniqueSCEVs.InsertNode(S, IP);
3333   return S;
3334 }
3335 
3336 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3337                                          const SCEV *RHS) {
3338   // ~smax(~x, ~y) == smin(x, y).
3339   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3340 }
3341 
3342 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3343                                          const SCEV *RHS) {
3344   // ~umax(~x, ~y) == umin(x, y)
3345   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3346 }
3347 
3348 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3349   // We can bypass creating a target-independent
3350   // constant expression and then folding it back into a ConstantInt.
3351   // This is just a compile-time optimization.
3352   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3353 }
3354 
3355 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3356                                              StructType *STy,
3357                                              unsigned FieldNo) {
3358   // We can bypass creating a target-independent
3359   // constant expression and then folding it back into a ConstantInt.
3360   // This is just a compile-time optimization.
3361   return getConstant(
3362       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3363 }
3364 
3365 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3366   // Don't attempt to do anything other than create a SCEVUnknown object
3367   // here.  createSCEV only calls getUnknown after checking for all other
3368   // interesting possibilities, and any other code that calls getUnknown
3369   // is doing so in order to hide a value from SCEV canonicalization.
3370 
3371   FoldingSetNodeID ID;
3372   ID.AddInteger(scUnknown);
3373   ID.AddPointer(V);
3374   void *IP = nullptr;
3375   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3376     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3377            "Stale SCEVUnknown in uniquing map!");
3378     return S;
3379   }
3380   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3381                                             FirstUnknown);
3382   FirstUnknown = cast<SCEVUnknown>(S);
3383   UniqueSCEVs.InsertNode(S, IP);
3384   return S;
3385 }
3386 
3387 //===----------------------------------------------------------------------===//
3388 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3389 //
3390 
3391 /// Test if values of the given type are analyzable within the SCEV
3392 /// framework. This primarily includes integer types, and it can optionally
3393 /// include pointer types if the ScalarEvolution class has access to
3394 /// target-specific information.
3395 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3396   // Integers and pointers are always SCEVable.
3397   return Ty->isIntegerTy() || Ty->isPointerTy();
3398 }
3399 
3400 /// Return the size in bits of the specified type, for which isSCEVable must
3401 /// return true.
3402 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3403   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3404   return getDataLayout().getTypeSizeInBits(Ty);
3405 }
3406 
3407 /// Return a type with the same bitwidth as the given type and which represents
3408 /// how SCEV will treat the given type, for which isSCEVable must return
3409 /// true. For pointer types, this is the pointer-sized integer type.
3410 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3411   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3412 
3413   if (Ty->isIntegerTy())
3414     return Ty;
3415 
3416   // The only other support type is pointer.
3417   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3418   return getDataLayout().getIntPtrType(Ty);
3419 }
3420 
3421 const SCEV *ScalarEvolution::getCouldNotCompute() {
3422   return CouldNotCompute.get();
3423 }
3424 
3425 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3426   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3427     auto *SU = dyn_cast<SCEVUnknown>(S);
3428     return SU && SU->getValue() == nullptr;
3429   });
3430 
3431   return !ContainsNulls;
3432 }
3433 
3434 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3435   HasRecMapType::iterator I = HasRecMap.find(S);
3436   if (I != HasRecMap.end())
3437     return I->second;
3438 
3439   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3440   HasRecMap.insert({S, FoundAddRec});
3441   return FoundAddRec;
3442 }
3443 
3444 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3445 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3446 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3447 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3448   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3449   if (!Add)
3450     return {S, nullptr};
3451 
3452   if (Add->getNumOperands() != 2)
3453     return {S, nullptr};
3454 
3455   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3456   if (!ConstOp)
3457     return {S, nullptr};
3458 
3459   return {Add->getOperand(1), ConstOp->getValue()};
3460 }
3461 
3462 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3463 /// by the value and offset from any ValueOffsetPair in the set.
3464 SetVector<ScalarEvolution::ValueOffsetPair> *
3465 ScalarEvolution::getSCEVValues(const SCEV *S) {
3466   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3467   if (SI == ExprValueMap.end())
3468     return nullptr;
3469 #ifndef NDEBUG
3470   if (VerifySCEVMap) {
3471     // Check there is no dangling Value in the set returned.
3472     for (const auto &VE : SI->second)
3473       assert(ValueExprMap.count(VE.first));
3474   }
3475 #endif
3476   return &SI->second;
3477 }
3478 
3479 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3480 /// cannot be used separately. eraseValueFromMap should be used to remove
3481 /// V from ValueExprMap and ExprValueMap at the same time.
3482 void ScalarEvolution::eraseValueFromMap(Value *V) {
3483   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3484   if (I != ValueExprMap.end()) {
3485     const SCEV *S = I->second;
3486     // Remove {V, 0} from the set of ExprValueMap[S]
3487     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3488       SV->remove({V, nullptr});
3489 
3490     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3491     const SCEV *Stripped;
3492     ConstantInt *Offset;
3493     std::tie(Stripped, Offset) = splitAddExpr(S);
3494     if (Offset != nullptr) {
3495       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3496         SV->remove({V, Offset});
3497     }
3498     ValueExprMap.erase(V);
3499   }
3500 }
3501 
3502 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3503 /// create a new one.
3504 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3505   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3506 
3507   const SCEV *S = getExistingSCEV(V);
3508   if (S == nullptr) {
3509     S = createSCEV(V);
3510     // During PHI resolution, it is possible to create two SCEVs for the same
3511     // V, so it is needed to double check whether V->S is inserted into
3512     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3513     std::pair<ValueExprMapType::iterator, bool> Pair =
3514         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3515     if (Pair.second) {
3516       ExprValueMap[S].insert({V, nullptr});
3517 
3518       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3519       // ExprValueMap.
3520       const SCEV *Stripped = S;
3521       ConstantInt *Offset = nullptr;
3522       std::tie(Stripped, Offset) = splitAddExpr(S);
3523       // If stripped is SCEVUnknown, don't bother to save
3524       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3525       // increase the complexity of the expansion code.
3526       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3527       // because it may generate add/sub instead of GEP in SCEV expansion.
3528       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3529           !isa<GetElementPtrInst>(V))
3530         ExprValueMap[Stripped].insert({V, Offset});
3531     }
3532   }
3533   return S;
3534 }
3535 
3536 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3537   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3538 
3539   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3540   if (I != ValueExprMap.end()) {
3541     const SCEV *S = I->second;
3542     if (checkValidity(S))
3543       return S;
3544     eraseValueFromMap(V);
3545     forgetMemoizedResults(S);
3546   }
3547   return nullptr;
3548 }
3549 
3550 /// Return a SCEV corresponding to -V = -1*V
3551 ///
3552 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3553                                              SCEV::NoWrapFlags Flags) {
3554   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3555     return getConstant(
3556                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3557 
3558   Type *Ty = V->getType();
3559   Ty = getEffectiveSCEVType(Ty);
3560   return getMulExpr(
3561       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3562 }
3563 
3564 /// Return a SCEV corresponding to ~V = -1-V
3565 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3566   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3567     return getConstant(
3568                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3569 
3570   Type *Ty = V->getType();
3571   Ty = getEffectiveSCEVType(Ty);
3572   const SCEV *AllOnes =
3573                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3574   return getMinusSCEV(AllOnes, V);
3575 }
3576 
3577 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3578                                           SCEV::NoWrapFlags Flags) {
3579   // Fast path: X - X --> 0.
3580   if (LHS == RHS)
3581     return getZero(LHS->getType());
3582 
3583   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3584   // makes it so that we cannot make much use of NUW.
3585   auto AddFlags = SCEV::FlagAnyWrap;
3586   const bool RHSIsNotMinSigned =
3587       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3588   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3589     // Let M be the minimum representable signed value. Then (-1)*RHS
3590     // signed-wraps if and only if RHS is M. That can happen even for
3591     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3592     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3593     // (-1)*RHS, we need to prove that RHS != M.
3594     //
3595     // If LHS is non-negative and we know that LHS - RHS does not
3596     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3597     // either by proving that RHS > M or that LHS >= 0.
3598     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3599       AddFlags = SCEV::FlagNSW;
3600     }
3601   }
3602 
3603   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3604   // RHS is NSW and LHS >= 0.
3605   //
3606   // The difficulty here is that the NSW flag may have been proven
3607   // relative to a loop that is to be found in a recurrence in LHS and
3608   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3609   // larger scope than intended.
3610   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3611 
3612   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3613 }
3614 
3615 const SCEV *
3616 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3617   Type *SrcTy = V->getType();
3618   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3619          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3620          "Cannot truncate or zero extend with non-integer arguments!");
3621   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3622     return V;  // No conversion
3623   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3624     return getTruncateExpr(V, Ty);
3625   return getZeroExtendExpr(V, Ty);
3626 }
3627 
3628 const SCEV *
3629 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3630                                          Type *Ty) {
3631   Type *SrcTy = V->getType();
3632   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3633          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3634          "Cannot truncate or zero extend with non-integer arguments!");
3635   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3636     return V;  // No conversion
3637   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3638     return getTruncateExpr(V, Ty);
3639   return getSignExtendExpr(V, Ty);
3640 }
3641 
3642 const SCEV *
3643 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3644   Type *SrcTy = V->getType();
3645   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3646          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3647          "Cannot noop or zero extend with non-integer arguments!");
3648   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3649          "getNoopOrZeroExtend cannot truncate!");
3650   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3651     return V;  // No conversion
3652   return getZeroExtendExpr(V, Ty);
3653 }
3654 
3655 const SCEV *
3656 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3657   Type *SrcTy = V->getType();
3658   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3659          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3660          "Cannot noop or sign extend with non-integer arguments!");
3661   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3662          "getNoopOrSignExtend cannot truncate!");
3663   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3664     return V;  // No conversion
3665   return getSignExtendExpr(V, Ty);
3666 }
3667 
3668 const SCEV *
3669 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3670   Type *SrcTy = V->getType();
3671   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3672          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3673          "Cannot noop or any extend with non-integer arguments!");
3674   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3675          "getNoopOrAnyExtend cannot truncate!");
3676   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3677     return V;  // No conversion
3678   return getAnyExtendExpr(V, Ty);
3679 }
3680 
3681 const SCEV *
3682 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3683   Type *SrcTy = V->getType();
3684   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3685          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3686          "Cannot truncate or noop with non-integer arguments!");
3687   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3688          "getTruncateOrNoop cannot extend!");
3689   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3690     return V;  // No conversion
3691   return getTruncateExpr(V, Ty);
3692 }
3693 
3694 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3695                                                         const SCEV *RHS) {
3696   const SCEV *PromotedLHS = LHS;
3697   const SCEV *PromotedRHS = RHS;
3698 
3699   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3700     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3701   else
3702     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3703 
3704   return getUMaxExpr(PromotedLHS, PromotedRHS);
3705 }
3706 
3707 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3708                                                         const SCEV *RHS) {
3709   const SCEV *PromotedLHS = LHS;
3710   const SCEV *PromotedRHS = RHS;
3711 
3712   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3713     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3714   else
3715     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3716 
3717   return getUMinExpr(PromotedLHS, PromotedRHS);
3718 }
3719 
3720 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3721   // A pointer operand may evaluate to a nonpointer expression, such as null.
3722   if (!V->getType()->isPointerTy())
3723     return V;
3724 
3725   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3726     return getPointerBase(Cast->getOperand());
3727   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3728     const SCEV *PtrOp = nullptr;
3729     for (const SCEV *NAryOp : NAry->operands()) {
3730       if (NAryOp->getType()->isPointerTy()) {
3731         // Cannot find the base of an expression with multiple pointer operands.
3732         if (PtrOp)
3733           return V;
3734         PtrOp = NAryOp;
3735       }
3736     }
3737     if (!PtrOp)
3738       return V;
3739     return getPointerBase(PtrOp);
3740   }
3741   return V;
3742 }
3743 
3744 /// Push users of the given Instruction onto the given Worklist.
3745 static void
3746 PushDefUseChildren(Instruction *I,
3747                    SmallVectorImpl<Instruction *> &Worklist) {
3748   // Push the def-use children onto the Worklist stack.
3749   for (User *U : I->users())
3750     Worklist.push_back(cast<Instruction>(U));
3751 }
3752 
3753 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3754   SmallVector<Instruction *, 16> Worklist;
3755   PushDefUseChildren(PN, Worklist);
3756 
3757   SmallPtrSet<Instruction *, 8> Visited;
3758   Visited.insert(PN);
3759   while (!Worklist.empty()) {
3760     Instruction *I = Worklist.pop_back_val();
3761     if (!Visited.insert(I).second)
3762       continue;
3763 
3764     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3765     if (It != ValueExprMap.end()) {
3766       const SCEV *Old = It->second;
3767 
3768       // Short-circuit the def-use traversal if the symbolic name
3769       // ceases to appear in expressions.
3770       if (Old != SymName && !hasOperand(Old, SymName))
3771         continue;
3772 
3773       // SCEVUnknown for a PHI either means that it has an unrecognized
3774       // structure, it's a PHI that's in the progress of being computed
3775       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3776       // additional loop trip count information isn't going to change anything.
3777       // In the second case, createNodeForPHI will perform the necessary
3778       // updates on its own when it gets to that point. In the third, we do
3779       // want to forget the SCEVUnknown.
3780       if (!isa<PHINode>(I) ||
3781           !isa<SCEVUnknown>(Old) ||
3782           (I != PN && Old == SymName)) {
3783         eraseValueFromMap(It->first);
3784         forgetMemoizedResults(Old);
3785       }
3786     }
3787 
3788     PushDefUseChildren(I, Worklist);
3789   }
3790 }
3791 
3792 namespace {
3793 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3794 public:
3795   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3796                              ScalarEvolution &SE) {
3797     SCEVInitRewriter Rewriter(L, SE);
3798     const SCEV *Result = Rewriter.visit(S);
3799     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3800   }
3801 
3802   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3803       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3804 
3805   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3806     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3807       Valid = false;
3808     return Expr;
3809   }
3810 
3811   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3812     // Only allow AddRecExprs for this loop.
3813     if (Expr->getLoop() == L)
3814       return Expr->getStart();
3815     Valid = false;
3816     return Expr;
3817   }
3818 
3819   bool isValid() { return Valid; }
3820 
3821 private:
3822   const Loop *L;
3823   bool Valid;
3824 };
3825 
3826 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3827 public:
3828   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3829                              ScalarEvolution &SE) {
3830     SCEVShiftRewriter Rewriter(L, SE);
3831     const SCEV *Result = Rewriter.visit(S);
3832     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3833   }
3834 
3835   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3836       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3837 
3838   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3839     // Only allow AddRecExprs for this loop.
3840     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3841       Valid = false;
3842     return Expr;
3843   }
3844 
3845   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3846     if (Expr->getLoop() == L && Expr->isAffine())
3847       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3848     Valid = false;
3849     return Expr;
3850   }
3851   bool isValid() { return Valid; }
3852 
3853 private:
3854   const Loop *L;
3855   bool Valid;
3856 };
3857 } // end anonymous namespace
3858 
3859 SCEV::NoWrapFlags
3860 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3861   if (!AR->isAffine())
3862     return SCEV::FlagAnyWrap;
3863 
3864   typedef OverflowingBinaryOperator OBO;
3865   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3866 
3867   if (!AR->hasNoSignedWrap()) {
3868     ConstantRange AddRecRange = getSignedRange(AR);
3869     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3870 
3871     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3872         Instruction::Add, IncRange, OBO::NoSignedWrap);
3873     if (NSWRegion.contains(AddRecRange))
3874       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3875   }
3876 
3877   if (!AR->hasNoUnsignedWrap()) {
3878     ConstantRange AddRecRange = getUnsignedRange(AR);
3879     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3880 
3881     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3882         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3883     if (NUWRegion.contains(AddRecRange))
3884       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3885   }
3886 
3887   return Result;
3888 }
3889 
3890 namespace {
3891 /// Represents an abstract binary operation.  This may exist as a
3892 /// normal instruction or constant expression, or may have been
3893 /// derived from an expression tree.
3894 struct BinaryOp {
3895   unsigned Opcode;
3896   Value *LHS;
3897   Value *RHS;
3898   bool IsNSW;
3899   bool IsNUW;
3900 
3901   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3902   /// constant expression.
3903   Operator *Op;
3904 
3905   explicit BinaryOp(Operator *Op)
3906       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3907         IsNSW(false), IsNUW(false), Op(Op) {
3908     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3909       IsNSW = OBO->hasNoSignedWrap();
3910       IsNUW = OBO->hasNoUnsignedWrap();
3911     }
3912   }
3913 
3914   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3915                     bool IsNUW = false)
3916       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3917         Op(nullptr) {}
3918 };
3919 }
3920 
3921 
3922 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3923 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3924   auto *Op = dyn_cast<Operator>(V);
3925   if (!Op)
3926     return None;
3927 
3928   // Implementation detail: all the cleverness here should happen without
3929   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3930   // SCEV expressions when possible, and we should not break that.
3931 
3932   switch (Op->getOpcode()) {
3933   case Instruction::Add:
3934   case Instruction::Sub:
3935   case Instruction::Mul:
3936   case Instruction::UDiv:
3937   case Instruction::And:
3938   case Instruction::Or:
3939   case Instruction::AShr:
3940   case Instruction::Shl:
3941     return BinaryOp(Op);
3942 
3943   case Instruction::Xor:
3944     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3945       // If the RHS of the xor is a signbit, then this is just an add.
3946       // Instcombine turns add of signbit into xor as a strength reduction step.
3947       if (RHSC->getValue().isSignBit())
3948         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3949     return BinaryOp(Op);
3950 
3951   case Instruction::LShr:
3952     // Turn logical shift right of a constant into a unsigned divide.
3953     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3954       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3955 
3956       // If the shift count is not less than the bitwidth, the result of
3957       // the shift is undefined. Don't try to analyze it, because the
3958       // resolution chosen here may differ from the resolution chosen in
3959       // other parts of the compiler.
3960       if (SA->getValue().ult(BitWidth)) {
3961         Constant *X =
3962             ConstantInt::get(SA->getContext(),
3963                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3964         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3965       }
3966     }
3967     return BinaryOp(Op);
3968 
3969   case Instruction::ExtractValue: {
3970     auto *EVI = cast<ExtractValueInst>(Op);
3971     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3972       break;
3973 
3974     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3975     if (!CI)
3976       break;
3977 
3978     if (auto *F = CI->getCalledFunction())
3979       switch (F->getIntrinsicID()) {
3980       case Intrinsic::sadd_with_overflow:
3981       case Intrinsic::uadd_with_overflow: {
3982         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3983           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3984                           CI->getArgOperand(1));
3985 
3986         // Now that we know that all uses of the arithmetic-result component of
3987         // CI are guarded by the overflow check, we can go ahead and pretend
3988         // that the arithmetic is non-overflowing.
3989         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3990           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3991                           CI->getArgOperand(1), /* IsNSW = */ true,
3992                           /* IsNUW = */ false);
3993         else
3994           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3995                           CI->getArgOperand(1), /* IsNSW = */ false,
3996                           /* IsNUW*/ true);
3997       }
3998 
3999       case Intrinsic::ssub_with_overflow:
4000       case Intrinsic::usub_with_overflow:
4001         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4002                         CI->getArgOperand(1));
4003 
4004       case Intrinsic::smul_with_overflow:
4005       case Intrinsic::umul_with_overflow:
4006         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4007                         CI->getArgOperand(1));
4008       default:
4009         break;
4010       }
4011   }
4012 
4013   default:
4014     break;
4015   }
4016 
4017   return None;
4018 }
4019 
4020 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4021   const Loop *L = LI.getLoopFor(PN->getParent());
4022   if (!L || L->getHeader() != PN->getParent())
4023     return nullptr;
4024 
4025   // The loop may have multiple entrances or multiple exits; we can analyze
4026   // this phi as an addrec if it has a unique entry value and a unique
4027   // backedge value.
4028   Value *BEValueV = nullptr, *StartValueV = nullptr;
4029   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4030     Value *V = PN->getIncomingValue(i);
4031     if (L->contains(PN->getIncomingBlock(i))) {
4032       if (!BEValueV) {
4033         BEValueV = V;
4034       } else if (BEValueV != V) {
4035         BEValueV = nullptr;
4036         break;
4037       }
4038     } else if (!StartValueV) {
4039       StartValueV = V;
4040     } else if (StartValueV != V) {
4041       StartValueV = nullptr;
4042       break;
4043     }
4044   }
4045   if (BEValueV && StartValueV) {
4046     // While we are analyzing this PHI node, handle its value symbolically.
4047     const SCEV *SymbolicName = getUnknown(PN);
4048     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4049            "PHI node already processed?");
4050     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4051 
4052     // Using this symbolic name for the PHI, analyze the value coming around
4053     // the back-edge.
4054     const SCEV *BEValue = getSCEV(BEValueV);
4055 
4056     // NOTE: If BEValue is loop invariant, we know that the PHI node just
4057     // has a special value for the first iteration of the loop.
4058 
4059     // If the value coming around the backedge is an add with the symbolic
4060     // value we just inserted, then we found a simple induction variable!
4061     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4062       // If there is a single occurrence of the symbolic value, replace it
4063       // with a recurrence.
4064       unsigned FoundIndex = Add->getNumOperands();
4065       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4066         if (Add->getOperand(i) == SymbolicName)
4067           if (FoundIndex == e) {
4068             FoundIndex = i;
4069             break;
4070           }
4071 
4072       if (FoundIndex != Add->getNumOperands()) {
4073         // Create an add with everything but the specified operand.
4074         SmallVector<const SCEV *, 8> Ops;
4075         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4076           if (i != FoundIndex)
4077             Ops.push_back(Add->getOperand(i));
4078         const SCEV *Accum = getAddExpr(Ops);
4079 
4080         // This is not a valid addrec if the step amount is varying each
4081         // loop iteration, but is not itself an addrec in this loop.
4082         if (isLoopInvariant(Accum, L) ||
4083             (isa<SCEVAddRecExpr>(Accum) &&
4084              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4085           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4086 
4087           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4088             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4089               if (BO->IsNUW)
4090                 Flags = setFlags(Flags, SCEV::FlagNUW);
4091               if (BO->IsNSW)
4092                 Flags = setFlags(Flags, SCEV::FlagNSW);
4093             }
4094           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4095             // If the increment is an inbounds GEP, then we know the address
4096             // space cannot be wrapped around. We cannot make any guarantee
4097             // about signed or unsigned overflow because pointers are
4098             // unsigned but we may have a negative index from the base
4099             // pointer. We can guarantee that no unsigned wrap occurs if the
4100             // indices form a positive value.
4101             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4102               Flags = setFlags(Flags, SCEV::FlagNW);
4103 
4104               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4105               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4106                 Flags = setFlags(Flags, SCEV::FlagNUW);
4107             }
4108 
4109             // We cannot transfer nuw and nsw flags from subtraction
4110             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4111             // for instance.
4112           }
4113 
4114           const SCEV *StartVal = getSCEV(StartValueV);
4115           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4116 
4117           // Okay, for the entire analysis of this edge we assumed the PHI
4118           // to be symbolic.  We now need to go back and purge all of the
4119           // entries for the scalars that use the symbolic expression.
4120           forgetSymbolicName(PN, SymbolicName);
4121           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4122 
4123           // We can add Flags to the post-inc expression only if we
4124           // know that it us *undefined behavior* for BEValueV to
4125           // overflow.
4126           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4127             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4128               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4129 
4130           return PHISCEV;
4131         }
4132       }
4133     } else {
4134       // Otherwise, this could be a loop like this:
4135       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4136       // In this case, j = {1,+,1}  and BEValue is j.
4137       // Because the other in-value of i (0) fits the evolution of BEValue
4138       // i really is an addrec evolution.
4139       //
4140       // We can generalize this saying that i is the shifted value of BEValue
4141       // by one iteration:
4142       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4143       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4144       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4145       if (Shifted != getCouldNotCompute() &&
4146           Start != getCouldNotCompute()) {
4147         const SCEV *StartVal = getSCEV(StartValueV);
4148         if (Start == StartVal) {
4149           // Okay, for the entire analysis of this edge we assumed the PHI
4150           // to be symbolic.  We now need to go back and purge all of the
4151           // entries for the scalars that use the symbolic expression.
4152           forgetSymbolicName(PN, SymbolicName);
4153           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4154           return Shifted;
4155         }
4156       }
4157     }
4158 
4159     // Remove the temporary PHI node SCEV that has been inserted while intending
4160     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4161     // as it will prevent later (possibly simpler) SCEV expressions to be added
4162     // to the ValueExprMap.
4163     eraseValueFromMap(PN);
4164   }
4165 
4166   return nullptr;
4167 }
4168 
4169 // Checks if the SCEV S is available at BB.  S is considered available at BB
4170 // if S can be materialized at BB without introducing a fault.
4171 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4172                                BasicBlock *BB) {
4173   struct CheckAvailable {
4174     bool TraversalDone = false;
4175     bool Available = true;
4176 
4177     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4178     BasicBlock *BB = nullptr;
4179     DominatorTree &DT;
4180 
4181     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4182       : L(L), BB(BB), DT(DT) {}
4183 
4184     bool setUnavailable() {
4185       TraversalDone = true;
4186       Available = false;
4187       return false;
4188     }
4189 
4190     bool follow(const SCEV *S) {
4191       switch (S->getSCEVType()) {
4192       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4193       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4194         // These expressions are available if their operand(s) is/are.
4195         return true;
4196 
4197       case scAddRecExpr: {
4198         // We allow add recurrences that are on the loop BB is in, or some
4199         // outer loop.  This guarantees availability because the value of the
4200         // add recurrence at BB is simply the "current" value of the induction
4201         // variable.  We can relax this in the future; for instance an add
4202         // recurrence on a sibling dominating loop is also available at BB.
4203         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4204         if (L && (ARLoop == L || ARLoop->contains(L)))
4205           return true;
4206 
4207         return setUnavailable();
4208       }
4209 
4210       case scUnknown: {
4211         // For SCEVUnknown, we check for simple dominance.
4212         const auto *SU = cast<SCEVUnknown>(S);
4213         Value *V = SU->getValue();
4214 
4215         if (isa<Argument>(V))
4216           return false;
4217 
4218         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4219           return false;
4220 
4221         return setUnavailable();
4222       }
4223 
4224       case scUDivExpr:
4225       case scCouldNotCompute:
4226         // We do not try to smart about these at all.
4227         return setUnavailable();
4228       }
4229       llvm_unreachable("switch should be fully covered!");
4230     }
4231 
4232     bool isDone() { return TraversalDone; }
4233   };
4234 
4235   CheckAvailable CA(L, BB, DT);
4236   SCEVTraversal<CheckAvailable> ST(CA);
4237 
4238   ST.visitAll(S);
4239   return CA.Available;
4240 }
4241 
4242 // Try to match a control flow sequence that branches out at BI and merges back
4243 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4244 // match.
4245 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4246                           Value *&C, Value *&LHS, Value *&RHS) {
4247   C = BI->getCondition();
4248 
4249   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4250   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4251 
4252   if (!LeftEdge.isSingleEdge())
4253     return false;
4254 
4255   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4256 
4257   Use &LeftUse = Merge->getOperandUse(0);
4258   Use &RightUse = Merge->getOperandUse(1);
4259 
4260   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4261     LHS = LeftUse;
4262     RHS = RightUse;
4263     return true;
4264   }
4265 
4266   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4267     LHS = RightUse;
4268     RHS = LeftUse;
4269     return true;
4270   }
4271 
4272   return false;
4273 }
4274 
4275 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4276   auto IsReachable =
4277       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4278   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4279     const Loop *L = LI.getLoopFor(PN->getParent());
4280 
4281     // We don't want to break LCSSA, even in a SCEV expression tree.
4282     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4283       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4284         return nullptr;
4285 
4286     // Try to match
4287     //
4288     //  br %cond, label %left, label %right
4289     // left:
4290     //  br label %merge
4291     // right:
4292     //  br label %merge
4293     // merge:
4294     //  V = phi [ %x, %left ], [ %y, %right ]
4295     //
4296     // as "select %cond, %x, %y"
4297 
4298     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4299     assert(IDom && "At least the entry block should dominate PN");
4300 
4301     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4302     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4303 
4304     if (BI && BI->isConditional() &&
4305         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4306         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4307         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4308       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4309   }
4310 
4311   return nullptr;
4312 }
4313 
4314 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4315   if (const SCEV *S = createAddRecFromPHI(PN))
4316     return S;
4317 
4318   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4319     return S;
4320 
4321   // If the PHI has a single incoming value, follow that value, unless the
4322   // PHI's incoming blocks are in a different loop, in which case doing so
4323   // risks breaking LCSSA form. Instcombine would normally zap these, but
4324   // it doesn't have DominatorTree information, so it may miss cases.
4325   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4326     if (LI.replacementPreservesLCSSAForm(PN, V))
4327       return getSCEV(V);
4328 
4329   // If it's not a loop phi, we can't handle it yet.
4330   return getUnknown(PN);
4331 }
4332 
4333 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4334                                                       Value *Cond,
4335                                                       Value *TrueVal,
4336                                                       Value *FalseVal) {
4337   // Handle "constant" branch or select. This can occur for instance when a
4338   // loop pass transforms an inner loop and moves on to process the outer loop.
4339   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4340     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4341 
4342   // Try to match some simple smax or umax patterns.
4343   auto *ICI = dyn_cast<ICmpInst>(Cond);
4344   if (!ICI)
4345     return getUnknown(I);
4346 
4347   Value *LHS = ICI->getOperand(0);
4348   Value *RHS = ICI->getOperand(1);
4349 
4350   switch (ICI->getPredicate()) {
4351   case ICmpInst::ICMP_SLT:
4352   case ICmpInst::ICMP_SLE:
4353     std::swap(LHS, RHS);
4354     LLVM_FALLTHROUGH;
4355   case ICmpInst::ICMP_SGT:
4356   case ICmpInst::ICMP_SGE:
4357     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4358     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4359     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4360       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4361       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4362       const SCEV *LA = getSCEV(TrueVal);
4363       const SCEV *RA = getSCEV(FalseVal);
4364       const SCEV *LDiff = getMinusSCEV(LA, LS);
4365       const SCEV *RDiff = getMinusSCEV(RA, RS);
4366       if (LDiff == RDiff)
4367         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4368       LDiff = getMinusSCEV(LA, RS);
4369       RDiff = getMinusSCEV(RA, LS);
4370       if (LDiff == RDiff)
4371         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4372     }
4373     break;
4374   case ICmpInst::ICMP_ULT:
4375   case ICmpInst::ICMP_ULE:
4376     std::swap(LHS, RHS);
4377     LLVM_FALLTHROUGH;
4378   case ICmpInst::ICMP_UGT:
4379   case ICmpInst::ICMP_UGE:
4380     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4381     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4382     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4383       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4384       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4385       const SCEV *LA = getSCEV(TrueVal);
4386       const SCEV *RA = getSCEV(FalseVal);
4387       const SCEV *LDiff = getMinusSCEV(LA, LS);
4388       const SCEV *RDiff = getMinusSCEV(RA, RS);
4389       if (LDiff == RDiff)
4390         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4391       LDiff = getMinusSCEV(LA, RS);
4392       RDiff = getMinusSCEV(RA, LS);
4393       if (LDiff == RDiff)
4394         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4395     }
4396     break;
4397   case ICmpInst::ICMP_NE:
4398     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4399     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4400         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4401       const SCEV *One = getOne(I->getType());
4402       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4403       const SCEV *LA = getSCEV(TrueVal);
4404       const SCEV *RA = getSCEV(FalseVal);
4405       const SCEV *LDiff = getMinusSCEV(LA, LS);
4406       const SCEV *RDiff = getMinusSCEV(RA, One);
4407       if (LDiff == RDiff)
4408         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4409     }
4410     break;
4411   case ICmpInst::ICMP_EQ:
4412     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4413     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4414         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4415       const SCEV *One = getOne(I->getType());
4416       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4417       const SCEV *LA = getSCEV(TrueVal);
4418       const SCEV *RA = getSCEV(FalseVal);
4419       const SCEV *LDiff = getMinusSCEV(LA, One);
4420       const SCEV *RDiff = getMinusSCEV(RA, LS);
4421       if (LDiff == RDiff)
4422         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4423     }
4424     break;
4425   default:
4426     break;
4427   }
4428 
4429   return getUnknown(I);
4430 }
4431 
4432 /// Expand GEP instructions into add and multiply operations. This allows them
4433 /// to be analyzed by regular SCEV code.
4434 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4435   // Don't attempt to analyze GEPs over unsized objects.
4436   if (!GEP->getSourceElementType()->isSized())
4437     return getUnknown(GEP);
4438 
4439   SmallVector<const SCEV *, 4> IndexExprs;
4440   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4441     IndexExprs.push_back(getSCEV(*Index));
4442   return getGEPExpr(GEP, IndexExprs);
4443 }
4444 
4445 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4446   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4447     return C->getAPInt().countTrailingZeros();
4448 
4449   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4450     return std::min(GetMinTrailingZeros(T->getOperand()),
4451                     (uint32_t)getTypeSizeInBits(T->getType()));
4452 
4453   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4454     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4455     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4456                ? getTypeSizeInBits(E->getType())
4457                : OpRes;
4458   }
4459 
4460   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4461     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4462     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4463                ? getTypeSizeInBits(E->getType())
4464                : OpRes;
4465   }
4466 
4467   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4468     // The result is the min of all operands results.
4469     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4470     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4471       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4472     return MinOpRes;
4473   }
4474 
4475   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4476     // The result is the sum of all operands results.
4477     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4478     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4479     for (unsigned i = 1, e = M->getNumOperands();
4480          SumOpRes != BitWidth && i != e; ++i)
4481       SumOpRes =
4482           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4483     return SumOpRes;
4484   }
4485 
4486   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4487     // The result is the min of all operands results.
4488     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4489     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4490       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4491     return MinOpRes;
4492   }
4493 
4494   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4495     // The result is the min of all operands results.
4496     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4497     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4498       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4499     return MinOpRes;
4500   }
4501 
4502   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4503     // The result is the min of all operands results.
4504     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4505     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4506       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4507     return MinOpRes;
4508   }
4509 
4510   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4511     // For a SCEVUnknown, ask ValueTracking.
4512     unsigned BitWidth = getTypeSizeInBits(U->getType());
4513     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4514     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4515                      nullptr, &DT);
4516     return Zeros.countTrailingOnes();
4517   }
4518 
4519   // SCEVUDivExpr
4520   return 0;
4521 }
4522 
4523 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4524   auto I = MinTrailingZerosCache.find(S);
4525   if (I != MinTrailingZerosCache.end())
4526     return I->second;
4527 
4528   uint32_t Result = GetMinTrailingZerosImpl(S);
4529   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4530   assert(InsertPair.second && "Should insert a new key");
4531   return InsertPair.first->second;
4532 }
4533 
4534 /// Helper method to assign a range to V from metadata present in the IR.
4535 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4536   if (Instruction *I = dyn_cast<Instruction>(V))
4537     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4538       return getConstantRangeFromMetadata(*MD);
4539 
4540   return None;
4541 }
4542 
4543 /// Determine the range for a particular SCEV.  If SignHint is
4544 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4545 /// with a "cleaner" unsigned (resp. signed) representation.
4546 ConstantRange
4547 ScalarEvolution::getRange(const SCEV *S,
4548                           ScalarEvolution::RangeSignHint SignHint) {
4549   DenseMap<const SCEV *, ConstantRange> &Cache =
4550       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4551                                                        : SignedRanges;
4552 
4553   // See if we've computed this range already.
4554   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4555   if (I != Cache.end())
4556     return I->second;
4557 
4558   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4559     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4560 
4561   unsigned BitWidth = getTypeSizeInBits(S->getType());
4562   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4563 
4564   // If the value has known zeros, the maximum value will have those known zeros
4565   // as well.
4566   uint32_t TZ = GetMinTrailingZeros(S);
4567   if (TZ != 0) {
4568     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4569       ConservativeResult =
4570           ConstantRange(APInt::getMinValue(BitWidth),
4571                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4572     else
4573       ConservativeResult = ConstantRange(
4574           APInt::getSignedMinValue(BitWidth),
4575           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4576   }
4577 
4578   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4579     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4580     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4581       X = X.add(getRange(Add->getOperand(i), SignHint));
4582     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4583   }
4584 
4585   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4586     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4587     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4588       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4589     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4590   }
4591 
4592   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4593     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4594     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4595       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4596     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4597   }
4598 
4599   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4600     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4601     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4602       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4603     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4604   }
4605 
4606   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4607     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4608     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4609     return setRange(UDiv, SignHint,
4610                     ConservativeResult.intersectWith(X.udiv(Y)));
4611   }
4612 
4613   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4614     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4615     return setRange(ZExt, SignHint,
4616                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4617   }
4618 
4619   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4620     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4621     return setRange(SExt, SignHint,
4622                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4623   }
4624 
4625   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4626     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4627     return setRange(Trunc, SignHint,
4628                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4629   }
4630 
4631   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4632     // If there's no unsigned wrap, the value will never be less than its
4633     // initial value.
4634     if (AddRec->hasNoUnsignedWrap())
4635       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4636         if (!C->getValue()->isZero())
4637           ConservativeResult = ConservativeResult.intersectWith(
4638               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4639 
4640     // If there's no signed wrap, and all the operands have the same sign or
4641     // zero, the value won't ever change sign.
4642     if (AddRec->hasNoSignedWrap()) {
4643       bool AllNonNeg = true;
4644       bool AllNonPos = true;
4645       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4646         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4647         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4648       }
4649       if (AllNonNeg)
4650         ConservativeResult = ConservativeResult.intersectWith(
4651           ConstantRange(APInt(BitWidth, 0),
4652                         APInt::getSignedMinValue(BitWidth)));
4653       else if (AllNonPos)
4654         ConservativeResult = ConservativeResult.intersectWith(
4655           ConstantRange(APInt::getSignedMinValue(BitWidth),
4656                         APInt(BitWidth, 1)));
4657     }
4658 
4659     // TODO: non-affine addrec
4660     if (AddRec->isAffine()) {
4661       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4662       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4663           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4664         auto RangeFromAffine = getRangeForAffineAR(
4665             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4666             BitWidth);
4667         if (!RangeFromAffine.isFullSet())
4668           ConservativeResult =
4669               ConservativeResult.intersectWith(RangeFromAffine);
4670 
4671         auto RangeFromFactoring = getRangeViaFactoring(
4672             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4673             BitWidth);
4674         if (!RangeFromFactoring.isFullSet())
4675           ConservativeResult =
4676               ConservativeResult.intersectWith(RangeFromFactoring);
4677       }
4678     }
4679 
4680     return setRange(AddRec, SignHint, ConservativeResult);
4681   }
4682 
4683   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4684     // Check if the IR explicitly contains !range metadata.
4685     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4686     if (MDRange.hasValue())
4687       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4688 
4689     // Split here to avoid paying the compile-time cost of calling both
4690     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4691     // if needed.
4692     const DataLayout &DL = getDataLayout();
4693     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4694       // For a SCEVUnknown, ask ValueTracking.
4695       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4696       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4697       if (Ones != ~Zeros + 1)
4698         ConservativeResult =
4699             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4700     } else {
4701       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4702              "generalize as needed!");
4703       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4704       if (NS > 1)
4705         ConservativeResult = ConservativeResult.intersectWith(
4706             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4707                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4708     }
4709 
4710     return setRange(U, SignHint, ConservativeResult);
4711   }
4712 
4713   return setRange(S, SignHint, ConservativeResult);
4714 }
4715 
4716 // Given a StartRange, Step and MaxBECount for an expression compute a range of
4717 // values that the expression can take. Initially, the expression has a value
4718 // from StartRange and then is changed by Step up to MaxBECount times. Signed
4719 // argument defines if we treat Step as signed or unsigned.
4720 static ConstantRange getRangeForAffineARHelper(APInt Step,
4721                                                ConstantRange StartRange,
4722                                                APInt MaxBECount,
4723                                                unsigned BitWidth, bool Signed) {
4724   // If either Step or MaxBECount is 0, then the expression won't change, and we
4725   // just need to return the initial range.
4726   if (Step == 0 || MaxBECount == 0)
4727     return StartRange;
4728 
4729   // If we don't know anything about the inital value (i.e. StartRange is
4730   // FullRange), then we don't know anything about the final range either.
4731   // Return FullRange.
4732   if (StartRange.isFullSet())
4733     return ConstantRange(BitWidth, /* isFullSet = */ true);
4734 
4735   // If Step is signed and negative, then we use its absolute value, but we also
4736   // note that we're moving in the opposite direction.
4737   bool Descending = Signed && Step.isNegative();
4738 
4739   if (Signed)
4740     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4741     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4742     // This equations hold true due to the well-defined wrap-around behavior of
4743     // APInt.
4744     Step = Step.abs();
4745 
4746   // Check if Offset is more than full span of BitWidth. If it is, the
4747   // expression is guaranteed to overflow.
4748   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4749     return ConstantRange(BitWidth, /* isFullSet = */ true);
4750 
4751   // Offset is by how much the expression can change. Checks above guarantee no
4752   // overflow here.
4753   APInt Offset = Step * MaxBECount;
4754 
4755   // Minimum value of the final range will match the minimal value of StartRange
4756   // if the expression is increasing and will be decreased by Offset otherwise.
4757   // Maximum value of the final range will match the maximal value of StartRange
4758   // if the expression is decreasing and will be increased by Offset otherwise.
4759   APInt StartLower = StartRange.getLower();
4760   APInt StartUpper = StartRange.getUpper() - 1;
4761   APInt MovedBoundary =
4762       Descending ? (StartLower - Offset) : (StartUpper + Offset);
4763 
4764   // It's possible that the new minimum/maximum value will fall into the initial
4765   // range (due to wrap around). This means that the expression can take any
4766   // value in this bitwidth, and we have to return full range.
4767   if (StartRange.contains(MovedBoundary))
4768     return ConstantRange(BitWidth, /* isFullSet = */ true);
4769 
4770   APInt NewLower, NewUpper;
4771   if (Descending) {
4772     NewLower = MovedBoundary;
4773     NewUpper = StartUpper;
4774   } else {
4775     NewLower = StartLower;
4776     NewUpper = MovedBoundary;
4777   }
4778 
4779   // If we end up with full range, return a proper full range.
4780   if (NewLower == NewUpper + 1)
4781     return ConstantRange(BitWidth, /* isFullSet = */ true);
4782 
4783   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4784   return ConstantRange(NewLower, NewUpper + 1);
4785 }
4786 
4787 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4788                                                    const SCEV *Step,
4789                                                    const SCEV *MaxBECount,
4790                                                    unsigned BitWidth) {
4791   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4792          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4793          "Precondition!");
4794 
4795   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4796   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4797   APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4798 
4799   // First, consider step signed.
4800   ConstantRange StartSRange = getSignedRange(Start);
4801   ConstantRange StepSRange = getSignedRange(Step);
4802 
4803   // If Step can be both positive and negative, we need to find ranges for the
4804   // maximum absolute step values in both directions and union them.
4805   ConstantRange SR =
4806       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4807                                 MaxBECountValue, BitWidth, /* Signed = */ true);
4808   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4809                                               StartSRange, MaxBECountValue,
4810                                               BitWidth, /* Signed = */ true));
4811 
4812   // Next, consider step unsigned.
4813   ConstantRange UR = getRangeForAffineARHelper(
4814       getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4815       MaxBECountValue, BitWidth, /* Signed = */ false);
4816 
4817   // Finally, intersect signed and unsigned ranges.
4818   return SR.intersectWith(UR);
4819 }
4820 
4821 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4822                                                     const SCEV *Step,
4823                                                     const SCEV *MaxBECount,
4824                                                     unsigned BitWidth) {
4825   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4826   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4827 
4828   struct SelectPattern {
4829     Value *Condition = nullptr;
4830     APInt TrueValue;
4831     APInt FalseValue;
4832 
4833     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4834                            const SCEV *S) {
4835       Optional<unsigned> CastOp;
4836       APInt Offset(BitWidth, 0);
4837 
4838       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4839              "Should be!");
4840 
4841       // Peel off a constant offset:
4842       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4843         // In the future we could consider being smarter here and handle
4844         // {Start+Step,+,Step} too.
4845         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4846           return;
4847 
4848         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4849         S = SA->getOperand(1);
4850       }
4851 
4852       // Peel off a cast operation
4853       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4854         CastOp = SCast->getSCEVType();
4855         S = SCast->getOperand();
4856       }
4857 
4858       using namespace llvm::PatternMatch;
4859 
4860       auto *SU = dyn_cast<SCEVUnknown>(S);
4861       const APInt *TrueVal, *FalseVal;
4862       if (!SU ||
4863           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4864                                           m_APInt(FalseVal)))) {
4865         Condition = nullptr;
4866         return;
4867       }
4868 
4869       TrueValue = *TrueVal;
4870       FalseValue = *FalseVal;
4871 
4872       // Re-apply the cast we peeled off earlier
4873       if (CastOp.hasValue())
4874         switch (*CastOp) {
4875         default:
4876           llvm_unreachable("Unknown SCEV cast type!");
4877 
4878         case scTruncate:
4879           TrueValue = TrueValue.trunc(BitWidth);
4880           FalseValue = FalseValue.trunc(BitWidth);
4881           break;
4882         case scZeroExtend:
4883           TrueValue = TrueValue.zext(BitWidth);
4884           FalseValue = FalseValue.zext(BitWidth);
4885           break;
4886         case scSignExtend:
4887           TrueValue = TrueValue.sext(BitWidth);
4888           FalseValue = FalseValue.sext(BitWidth);
4889           break;
4890         }
4891 
4892       // Re-apply the constant offset we peeled off earlier
4893       TrueValue += Offset;
4894       FalseValue += Offset;
4895     }
4896 
4897     bool isRecognized() { return Condition != nullptr; }
4898   };
4899 
4900   SelectPattern StartPattern(*this, BitWidth, Start);
4901   if (!StartPattern.isRecognized())
4902     return ConstantRange(BitWidth, /* isFullSet = */ true);
4903 
4904   SelectPattern StepPattern(*this, BitWidth, Step);
4905   if (!StepPattern.isRecognized())
4906     return ConstantRange(BitWidth, /* isFullSet = */ true);
4907 
4908   if (StartPattern.Condition != StepPattern.Condition) {
4909     // We don't handle this case today; but we could, by considering four
4910     // possibilities below instead of two. I'm not sure if there are cases where
4911     // that will help over what getRange already does, though.
4912     return ConstantRange(BitWidth, /* isFullSet = */ true);
4913   }
4914 
4915   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4916   // construct arbitrary general SCEV expressions here.  This function is called
4917   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4918   // say) can end up caching a suboptimal value.
4919 
4920   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4921   // C2352 and C2512 (otherwise it isn't needed).
4922 
4923   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4924   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4925   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4926   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4927 
4928   ConstantRange TrueRange =
4929       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4930   ConstantRange FalseRange =
4931       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4932 
4933   return TrueRange.unionWith(FalseRange);
4934 }
4935 
4936 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4937   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4938   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4939 
4940   // Return early if there are no flags to propagate to the SCEV.
4941   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4942   if (BinOp->hasNoUnsignedWrap())
4943     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4944   if (BinOp->hasNoSignedWrap())
4945     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4946   if (Flags == SCEV::FlagAnyWrap)
4947     return SCEV::FlagAnyWrap;
4948 
4949   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4950 }
4951 
4952 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4953   // Here we check that I is in the header of the innermost loop containing I,
4954   // since we only deal with instructions in the loop header. The actual loop we
4955   // need to check later will come from an add recurrence, but getting that
4956   // requires computing the SCEV of the operands, which can be expensive. This
4957   // check we can do cheaply to rule out some cases early.
4958   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
4959   if (InnermostContainingLoop == nullptr ||
4960       InnermostContainingLoop->getHeader() != I->getParent())
4961     return false;
4962 
4963   // Only proceed if we can prove that I does not yield poison.
4964   if (!isKnownNotFullPoison(I)) return false;
4965 
4966   // At this point we know that if I is executed, then it does not wrap
4967   // according to at least one of NSW or NUW. If I is not executed, then we do
4968   // not know if the calculation that I represents would wrap. Multiple
4969   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
4970   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4971   // derived from other instructions that map to the same SCEV. We cannot make
4972   // that guarantee for cases where I is not executed. So we need to find the
4973   // loop that I is considered in relation to and prove that I is executed for
4974   // every iteration of that loop. That implies that the value that I
4975   // calculates does not wrap anywhere in the loop, so then we can apply the
4976   // flags to the SCEV.
4977   //
4978   // We check isLoopInvariant to disambiguate in case we are adding recurrences
4979   // from different loops, so that we know which loop to prove that I is
4980   // executed in.
4981   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4982     // I could be an extractvalue from a call to an overflow intrinsic.
4983     // TODO: We can do better here in some cases.
4984     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4985       return false;
4986     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
4987     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4988       bool AllOtherOpsLoopInvariant = true;
4989       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4990            ++OtherOpIndex) {
4991         if (OtherOpIndex != OpIndex) {
4992           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4993           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4994             AllOtherOpsLoopInvariant = false;
4995             break;
4996           }
4997         }
4998       }
4999       if (AllOtherOpsLoopInvariant &&
5000           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5001         return true;
5002     }
5003   }
5004   return false;
5005 }
5006 
5007 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5008   // If we know that \c I can never be poison period, then that's enough.
5009   if (isSCEVExprNeverPoison(I))
5010     return true;
5011 
5012   // For an add recurrence specifically, we assume that infinite loops without
5013   // side effects are undefined behavior, and then reason as follows:
5014   //
5015   // If the add recurrence is poison in any iteration, it is poison on all
5016   // future iterations (since incrementing poison yields poison). If the result
5017   // of the add recurrence is fed into the loop latch condition and the loop
5018   // does not contain any throws or exiting blocks other than the latch, we now
5019   // have the ability to "choose" whether the backedge is taken or not (by
5020   // choosing a sufficiently evil value for the poison feeding into the branch)
5021   // for every iteration including and after the one in which \p I first became
5022   // poison.  There are two possibilities (let's call the iteration in which \p
5023   // I first became poison as K):
5024   //
5025   //  1. In the set of iterations including and after K, the loop body executes
5026   //     no side effects.  In this case executing the backege an infinte number
5027   //     of times will yield undefined behavior.
5028   //
5029   //  2. In the set of iterations including and after K, the loop body executes
5030   //     at least one side effect.  In this case, that specific instance of side
5031   //     effect is control dependent on poison, which also yields undefined
5032   //     behavior.
5033 
5034   auto *ExitingBB = L->getExitingBlock();
5035   auto *LatchBB = L->getLoopLatch();
5036   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5037     return false;
5038 
5039   SmallPtrSet<const Instruction *, 16> Pushed;
5040   SmallVector<const Instruction *, 8> PoisonStack;
5041 
5042   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5043   // things that are known to be fully poison under that assumption go on the
5044   // PoisonStack.
5045   Pushed.insert(I);
5046   PoisonStack.push_back(I);
5047 
5048   bool LatchControlDependentOnPoison = false;
5049   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5050     const Instruction *Poison = PoisonStack.pop_back_val();
5051 
5052     for (auto *PoisonUser : Poison->users()) {
5053       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5054         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5055           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5056       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5057         assert(BI->isConditional() && "Only possibility!");
5058         if (BI->getParent() == LatchBB) {
5059           LatchControlDependentOnPoison = true;
5060           break;
5061         }
5062       }
5063     }
5064   }
5065 
5066   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5067 }
5068 
5069 ScalarEvolution::LoopProperties
5070 ScalarEvolution::getLoopProperties(const Loop *L) {
5071   typedef ScalarEvolution::LoopProperties LoopProperties;
5072 
5073   auto Itr = LoopPropertiesCache.find(L);
5074   if (Itr == LoopPropertiesCache.end()) {
5075     auto HasSideEffects = [](Instruction *I) {
5076       if (auto *SI = dyn_cast<StoreInst>(I))
5077         return !SI->isSimple();
5078 
5079       return I->mayHaveSideEffects();
5080     };
5081 
5082     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5083                          /*HasNoSideEffects*/ true};
5084 
5085     for (auto *BB : L->getBlocks())
5086       for (auto &I : *BB) {
5087         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5088           LP.HasNoAbnormalExits = false;
5089         if (HasSideEffects(&I))
5090           LP.HasNoSideEffects = false;
5091         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5092           break; // We're already as pessimistic as we can get.
5093       }
5094 
5095     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5096     assert(InsertPair.second && "We just checked!");
5097     Itr = InsertPair.first;
5098   }
5099 
5100   return Itr->second;
5101 }
5102 
5103 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5104   if (!isSCEVable(V->getType()))
5105     return getUnknown(V);
5106 
5107   if (Instruction *I = dyn_cast<Instruction>(V)) {
5108     // Don't attempt to analyze instructions in blocks that aren't
5109     // reachable. Such instructions don't matter, and they aren't required
5110     // to obey basic rules for definitions dominating uses which this
5111     // analysis depends on.
5112     if (!DT.isReachableFromEntry(I->getParent()))
5113       return getUnknown(V);
5114   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5115     return getConstant(CI);
5116   else if (isa<ConstantPointerNull>(V))
5117     return getZero(V->getType());
5118   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5119     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5120   else if (!isa<ConstantExpr>(V))
5121     return getUnknown(V);
5122 
5123   Operator *U = cast<Operator>(V);
5124   if (auto BO = MatchBinaryOp(U, DT)) {
5125     switch (BO->Opcode) {
5126     case Instruction::Add: {
5127       // The simple thing to do would be to just call getSCEV on both operands
5128       // and call getAddExpr with the result. However if we're looking at a
5129       // bunch of things all added together, this can be quite inefficient,
5130       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5131       // Instead, gather up all the operands and make a single getAddExpr call.
5132       // LLVM IR canonical form means we need only traverse the left operands.
5133       SmallVector<const SCEV *, 4> AddOps;
5134       do {
5135         if (BO->Op) {
5136           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5137             AddOps.push_back(OpSCEV);
5138             break;
5139           }
5140 
5141           // If a NUW or NSW flag can be applied to the SCEV for this
5142           // addition, then compute the SCEV for this addition by itself
5143           // with a separate call to getAddExpr. We need to do that
5144           // instead of pushing the operands of the addition onto AddOps,
5145           // since the flags are only known to apply to this particular
5146           // addition - they may not apply to other additions that can be
5147           // formed with operands from AddOps.
5148           const SCEV *RHS = getSCEV(BO->RHS);
5149           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5150           if (Flags != SCEV::FlagAnyWrap) {
5151             const SCEV *LHS = getSCEV(BO->LHS);
5152             if (BO->Opcode == Instruction::Sub)
5153               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5154             else
5155               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5156             break;
5157           }
5158         }
5159 
5160         if (BO->Opcode == Instruction::Sub)
5161           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5162         else
5163           AddOps.push_back(getSCEV(BO->RHS));
5164 
5165         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5166         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5167                        NewBO->Opcode != Instruction::Sub)) {
5168           AddOps.push_back(getSCEV(BO->LHS));
5169           break;
5170         }
5171         BO = NewBO;
5172       } while (true);
5173 
5174       return getAddExpr(AddOps);
5175     }
5176 
5177     case Instruction::Mul: {
5178       SmallVector<const SCEV *, 4> MulOps;
5179       do {
5180         if (BO->Op) {
5181           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5182             MulOps.push_back(OpSCEV);
5183             break;
5184           }
5185 
5186           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5187           if (Flags != SCEV::FlagAnyWrap) {
5188             MulOps.push_back(
5189                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5190             break;
5191           }
5192         }
5193 
5194         MulOps.push_back(getSCEV(BO->RHS));
5195         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5196         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5197           MulOps.push_back(getSCEV(BO->LHS));
5198           break;
5199         }
5200         BO = NewBO;
5201       } while (true);
5202 
5203       return getMulExpr(MulOps);
5204     }
5205     case Instruction::UDiv:
5206       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5207     case Instruction::Sub: {
5208       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5209       if (BO->Op)
5210         Flags = getNoWrapFlagsFromUB(BO->Op);
5211       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5212     }
5213     case Instruction::And:
5214       // For an expression like x&255 that merely masks off the high bits,
5215       // use zext(trunc(x)) as the SCEV expression.
5216       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5217         if (CI->isNullValue())
5218           return getSCEV(BO->RHS);
5219         if (CI->isAllOnesValue())
5220           return getSCEV(BO->LHS);
5221         const APInt &A = CI->getValue();
5222 
5223         // Instcombine's ShrinkDemandedConstant may strip bits out of
5224         // constants, obscuring what would otherwise be a low-bits mask.
5225         // Use computeKnownBits to compute what ShrinkDemandedConstant
5226         // knew about to reconstruct a low-bits mask value.
5227         unsigned LZ = A.countLeadingZeros();
5228         unsigned TZ = A.countTrailingZeros();
5229         unsigned BitWidth = A.getBitWidth();
5230         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5231         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5232                          0, &AC, nullptr, &DT);
5233 
5234         APInt EffectiveMask =
5235             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5236         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5237           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5238           const SCEV *LHS = getSCEV(BO->LHS);
5239           const SCEV *ShiftedLHS = nullptr;
5240           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5241             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5242               // For an expression like (x * 8) & 8, simplify the multiply.
5243               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5244               unsigned GCD = std::min(MulZeros, TZ);
5245               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5246               SmallVector<const SCEV*, 4> MulOps;
5247               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5248               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5249               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5250               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5251             }
5252           }
5253           if (!ShiftedLHS)
5254             ShiftedLHS = getUDivExpr(LHS, MulCount);
5255           return getMulExpr(
5256               getZeroExtendExpr(
5257                   getTruncateExpr(ShiftedLHS,
5258                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5259                   BO->LHS->getType()),
5260               MulCount);
5261         }
5262       }
5263       break;
5264 
5265     case Instruction::Or:
5266       // If the RHS of the Or is a constant, we may have something like:
5267       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5268       // optimizations will transparently handle this case.
5269       //
5270       // In order for this transformation to be safe, the LHS must be of the
5271       // form X*(2^n) and the Or constant must be less than 2^n.
5272       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5273         const SCEV *LHS = getSCEV(BO->LHS);
5274         const APInt &CIVal = CI->getValue();
5275         if (GetMinTrailingZeros(LHS) >=
5276             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5277           // Build a plain add SCEV.
5278           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5279           // If the LHS of the add was an addrec and it has no-wrap flags,
5280           // transfer the no-wrap flags, since an or won't introduce a wrap.
5281           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5282             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5283             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5284                 OldAR->getNoWrapFlags());
5285           }
5286           return S;
5287         }
5288       }
5289       break;
5290 
5291     case Instruction::Xor:
5292       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5293         // If the RHS of xor is -1, then this is a not operation.
5294         if (CI->isAllOnesValue())
5295           return getNotSCEV(getSCEV(BO->LHS));
5296 
5297         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5298         // This is a variant of the check for xor with -1, and it handles
5299         // the case where instcombine has trimmed non-demanded bits out
5300         // of an xor with -1.
5301         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5302           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5303             if (LBO->getOpcode() == Instruction::And &&
5304                 LCI->getValue() == CI->getValue())
5305               if (const SCEVZeroExtendExpr *Z =
5306                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5307                 Type *UTy = BO->LHS->getType();
5308                 const SCEV *Z0 = Z->getOperand();
5309                 Type *Z0Ty = Z0->getType();
5310                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5311 
5312                 // If C is a low-bits mask, the zero extend is serving to
5313                 // mask off the high bits. Complement the operand and
5314                 // re-apply the zext.
5315                 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5316                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5317 
5318                 // If C is a single bit, it may be in the sign-bit position
5319                 // before the zero-extend. In this case, represent the xor
5320                 // using an add, which is equivalent, and re-apply the zext.
5321                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5322                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5323                     Trunc.isSignBit())
5324                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5325                                            UTy);
5326               }
5327       }
5328       break;
5329 
5330   case Instruction::Shl:
5331     // Turn shift left of a constant amount into a multiply.
5332     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5333       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5334 
5335       // If the shift count is not less than the bitwidth, the result of
5336       // the shift is undefined. Don't try to analyze it, because the
5337       // resolution chosen here may differ from the resolution chosen in
5338       // other parts of the compiler.
5339       if (SA->getValue().uge(BitWidth))
5340         break;
5341 
5342       // It is currently not resolved how to interpret NSW for left
5343       // shift by BitWidth - 1, so we avoid applying flags in that
5344       // case. Remove this check (or this comment) once the situation
5345       // is resolved. See
5346       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5347       // and http://reviews.llvm.org/D8890 .
5348       auto Flags = SCEV::FlagAnyWrap;
5349       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5350         Flags = getNoWrapFlagsFromUB(BO->Op);
5351 
5352       Constant *X = ConstantInt::get(getContext(),
5353         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5354       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5355     }
5356     break;
5357 
5358     case Instruction::AShr:
5359       // AShr X, C, where C is a constant.
5360       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5361       if (!CI)
5362         break;
5363 
5364       Type *OuterTy = BO->LHS->getType();
5365       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5366       // If the shift count is not less than the bitwidth, the result of
5367       // the shift is undefined. Don't try to analyze it, because the
5368       // resolution chosen here may differ from the resolution chosen in
5369       // other parts of the compiler.
5370       if (CI->getValue().uge(BitWidth))
5371         break;
5372 
5373       if (CI->isNullValue())
5374         return getSCEV(BO->LHS); // shift by zero --> noop
5375 
5376       uint64_t AShrAmt = CI->getZExtValue();
5377       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5378 
5379       Operator *L = dyn_cast<Operator>(BO->LHS);
5380       if (L && L->getOpcode() == Instruction::Shl) {
5381         // X = Shl A, n
5382         // Y = AShr X, m
5383         // Both n and m are constant.
5384 
5385         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5386         if (L->getOperand(1) == BO->RHS)
5387           // For a two-shift sext-inreg, i.e. n = m,
5388           // use sext(trunc(x)) as the SCEV expression.
5389           return getSignExtendExpr(
5390               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5391 
5392         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5393         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5394           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5395           if (ShlAmt > AShrAmt) {
5396             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5397             // expression. We already checked that ShlAmt < BitWidth, so
5398             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5399             // ShlAmt - AShrAmt < Amt.
5400             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5401                                             ShlAmt - AShrAmt);
5402             return getSignExtendExpr(
5403                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5404                 getConstant(Mul)), OuterTy);
5405           }
5406         }
5407       }
5408       break;
5409     }
5410   }
5411 
5412   switch (U->getOpcode()) {
5413   case Instruction::Trunc:
5414     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5415 
5416   case Instruction::ZExt:
5417     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5418 
5419   case Instruction::SExt:
5420     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5421 
5422   case Instruction::BitCast:
5423     // BitCasts are no-op casts so we just eliminate the cast.
5424     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5425       return getSCEV(U->getOperand(0));
5426     break;
5427 
5428   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5429   // lead to pointer expressions which cannot safely be expanded to GEPs,
5430   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5431   // simplifying integer expressions.
5432 
5433   case Instruction::GetElementPtr:
5434     return createNodeForGEP(cast<GEPOperator>(U));
5435 
5436   case Instruction::PHI:
5437     return createNodeForPHI(cast<PHINode>(U));
5438 
5439   case Instruction::Select:
5440     // U can also be a select constant expr, which let fall through.  Since
5441     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5442     // constant expressions cannot have instructions as operands, we'd have
5443     // returned getUnknown for a select constant expressions anyway.
5444     if (isa<Instruction>(U))
5445       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5446                                       U->getOperand(1), U->getOperand(2));
5447     break;
5448 
5449   case Instruction::Call:
5450   case Instruction::Invoke:
5451     if (Value *RV = CallSite(U).getReturnedArgOperand())
5452       return getSCEV(RV);
5453     break;
5454   }
5455 
5456   return getUnknown(V);
5457 }
5458 
5459 
5460 
5461 //===----------------------------------------------------------------------===//
5462 //                   Iteration Count Computation Code
5463 //
5464 
5465 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5466   if (!ExitCount)
5467     return 0;
5468 
5469   ConstantInt *ExitConst = ExitCount->getValue();
5470 
5471   // Guard against huge trip counts.
5472   if (ExitConst->getValue().getActiveBits() > 32)
5473     return 0;
5474 
5475   // In case of integer overflow, this returns 0, which is correct.
5476   return ((unsigned)ExitConst->getZExtValue()) + 1;
5477 }
5478 
5479 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5480   if (BasicBlock *ExitingBB = L->getExitingBlock())
5481     return getSmallConstantTripCount(L, ExitingBB);
5482 
5483   // No trip count information for multiple exits.
5484   return 0;
5485 }
5486 
5487 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5488                                                     BasicBlock *ExitingBlock) {
5489   assert(ExitingBlock && "Must pass a non-null exiting block!");
5490   assert(L->isLoopExiting(ExitingBlock) &&
5491          "Exiting block must actually branch out of the loop!");
5492   const SCEVConstant *ExitCount =
5493       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5494   return getConstantTripCount(ExitCount);
5495 }
5496 
5497 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5498   const auto *MaxExitCount =
5499       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5500   return getConstantTripCount(MaxExitCount);
5501 }
5502 
5503 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5504   if (BasicBlock *ExitingBB = L->getExitingBlock())
5505     return getSmallConstantTripMultiple(L, ExitingBB);
5506 
5507   // No trip multiple information for multiple exits.
5508   return 0;
5509 }
5510 
5511 /// Returns the largest constant divisor of the trip count of this loop as a
5512 /// normal unsigned value, if possible. This means that the actual trip count is
5513 /// always a multiple of the returned value (don't forget the trip count could
5514 /// very well be zero as well!).
5515 ///
5516 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5517 /// multiple of a constant (which is also the case if the trip count is simply
5518 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5519 /// if the trip count is very large (>= 2^32).
5520 ///
5521 /// As explained in the comments for getSmallConstantTripCount, this assumes
5522 /// that control exits the loop via ExitingBlock.
5523 unsigned
5524 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5525                                               BasicBlock *ExitingBlock) {
5526   assert(ExitingBlock && "Must pass a non-null exiting block!");
5527   assert(L->isLoopExiting(ExitingBlock) &&
5528          "Exiting block must actually branch out of the loop!");
5529   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5530   if (ExitCount == getCouldNotCompute())
5531     return 1;
5532 
5533   // Get the trip count from the BE count by adding 1.
5534   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5535 
5536   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5537   if (!TC)
5538     // Attempt to factor more general cases. Returns the greatest power of
5539     // two divisor. If overflow happens, the trip count expression is still
5540     // divisible by the greatest power of 2 divisor returned.
5541     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5542 
5543   ConstantInt *Result = TC->getValue();
5544 
5545   // Guard against huge trip counts (this requires checking
5546   // for zero to handle the case where the trip count == -1 and the
5547   // addition wraps).
5548   if (!Result || Result->getValue().getActiveBits() > 32 ||
5549       Result->getValue().getActiveBits() == 0)
5550     return 1;
5551 
5552   return (unsigned)Result->getZExtValue();
5553 }
5554 
5555 /// Get the expression for the number of loop iterations for which this loop is
5556 /// guaranteed not to exit via ExitingBlock. Otherwise return
5557 /// SCEVCouldNotCompute.
5558 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5559                                           BasicBlock *ExitingBlock) {
5560   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5561 }
5562 
5563 const SCEV *
5564 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5565                                                  SCEVUnionPredicate &Preds) {
5566   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5567 }
5568 
5569 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5570   return getBackedgeTakenInfo(L).getExact(this);
5571 }
5572 
5573 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5574 /// known never to be less than the actual backedge taken count.
5575 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5576   return getBackedgeTakenInfo(L).getMax(this);
5577 }
5578 
5579 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5580   return getBackedgeTakenInfo(L).isMaxOrZero(this);
5581 }
5582 
5583 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5584 static void
5585 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5586   BasicBlock *Header = L->getHeader();
5587 
5588   // Push all Loop-header PHIs onto the Worklist stack.
5589   for (BasicBlock::iterator I = Header->begin();
5590        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5591     Worklist.push_back(PN);
5592 }
5593 
5594 const ScalarEvolution::BackedgeTakenInfo &
5595 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5596   auto &BTI = getBackedgeTakenInfo(L);
5597   if (BTI.hasFullInfo())
5598     return BTI;
5599 
5600   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5601 
5602   if (!Pair.second)
5603     return Pair.first->second;
5604 
5605   BackedgeTakenInfo Result =
5606       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5607 
5608   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5609 }
5610 
5611 const ScalarEvolution::BackedgeTakenInfo &
5612 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5613   // Initially insert an invalid entry for this loop. If the insertion
5614   // succeeds, proceed to actually compute a backedge-taken count and
5615   // update the value. The temporary CouldNotCompute value tells SCEV
5616   // code elsewhere that it shouldn't attempt to request a new
5617   // backedge-taken count, which could result in infinite recursion.
5618   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5619       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5620   if (!Pair.second)
5621     return Pair.first->second;
5622 
5623   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5624   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5625   // must be cleared in this scope.
5626   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5627 
5628   if (Result.getExact(this) != getCouldNotCompute()) {
5629     assert(isLoopInvariant(Result.getExact(this), L) &&
5630            isLoopInvariant(Result.getMax(this), L) &&
5631            "Computed backedge-taken count isn't loop invariant for loop!");
5632     ++NumTripCountsComputed;
5633   }
5634   else if (Result.getMax(this) == getCouldNotCompute() &&
5635            isa<PHINode>(L->getHeader()->begin())) {
5636     // Only count loops that have phi nodes as not being computable.
5637     ++NumTripCountsNotComputed;
5638   }
5639 
5640   // Now that we know more about the trip count for this loop, forget any
5641   // existing SCEV values for PHI nodes in this loop since they are only
5642   // conservative estimates made without the benefit of trip count
5643   // information. This is similar to the code in forgetLoop, except that
5644   // it handles SCEVUnknown PHI nodes specially.
5645   if (Result.hasAnyInfo()) {
5646     SmallVector<Instruction *, 16> Worklist;
5647     PushLoopPHIs(L, Worklist);
5648 
5649     SmallPtrSet<Instruction *, 8> Visited;
5650     while (!Worklist.empty()) {
5651       Instruction *I = Worklist.pop_back_val();
5652       if (!Visited.insert(I).second)
5653         continue;
5654 
5655       ValueExprMapType::iterator It =
5656         ValueExprMap.find_as(static_cast<Value *>(I));
5657       if (It != ValueExprMap.end()) {
5658         const SCEV *Old = It->second;
5659 
5660         // SCEVUnknown for a PHI either means that it has an unrecognized
5661         // structure, or it's a PHI that's in the progress of being computed
5662         // by createNodeForPHI.  In the former case, additional loop trip
5663         // count information isn't going to change anything. In the later
5664         // case, createNodeForPHI will perform the necessary updates on its
5665         // own when it gets to that point.
5666         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5667           eraseValueFromMap(It->first);
5668           forgetMemoizedResults(Old);
5669         }
5670         if (PHINode *PN = dyn_cast<PHINode>(I))
5671           ConstantEvolutionLoopExitValue.erase(PN);
5672       }
5673 
5674       PushDefUseChildren(I, Worklist);
5675     }
5676   }
5677 
5678   // Re-lookup the insert position, since the call to
5679   // computeBackedgeTakenCount above could result in a
5680   // recusive call to getBackedgeTakenInfo (on a different
5681   // loop), which would invalidate the iterator computed
5682   // earlier.
5683   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5684 }
5685 
5686 void ScalarEvolution::forgetLoop(const Loop *L) {
5687   // Drop any stored trip count value.
5688   auto RemoveLoopFromBackedgeMap =
5689       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5690         auto BTCPos = Map.find(L);
5691         if (BTCPos != Map.end()) {
5692           BTCPos->second.clear();
5693           Map.erase(BTCPos);
5694         }
5695       };
5696 
5697   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5698   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5699 
5700   // Drop information about expressions based on loop-header PHIs.
5701   SmallVector<Instruction *, 16> Worklist;
5702   PushLoopPHIs(L, Worklist);
5703 
5704   SmallPtrSet<Instruction *, 8> Visited;
5705   while (!Worklist.empty()) {
5706     Instruction *I = Worklist.pop_back_val();
5707     if (!Visited.insert(I).second)
5708       continue;
5709 
5710     ValueExprMapType::iterator It =
5711       ValueExprMap.find_as(static_cast<Value *>(I));
5712     if (It != ValueExprMap.end()) {
5713       eraseValueFromMap(It->first);
5714       forgetMemoizedResults(It->second);
5715       if (PHINode *PN = dyn_cast<PHINode>(I))
5716         ConstantEvolutionLoopExitValue.erase(PN);
5717     }
5718 
5719     PushDefUseChildren(I, Worklist);
5720   }
5721 
5722   // Forget all contained loops too, to avoid dangling entries in the
5723   // ValuesAtScopes map.
5724   for (Loop *I : *L)
5725     forgetLoop(I);
5726 
5727   LoopPropertiesCache.erase(L);
5728 }
5729 
5730 void ScalarEvolution::forgetValue(Value *V) {
5731   Instruction *I = dyn_cast<Instruction>(V);
5732   if (!I) return;
5733 
5734   // Drop information about expressions based on loop-header PHIs.
5735   SmallVector<Instruction *, 16> Worklist;
5736   Worklist.push_back(I);
5737 
5738   SmallPtrSet<Instruction *, 8> Visited;
5739   while (!Worklist.empty()) {
5740     I = Worklist.pop_back_val();
5741     if (!Visited.insert(I).second)
5742       continue;
5743 
5744     ValueExprMapType::iterator It =
5745       ValueExprMap.find_as(static_cast<Value *>(I));
5746     if (It != ValueExprMap.end()) {
5747       eraseValueFromMap(It->first);
5748       forgetMemoizedResults(It->second);
5749       if (PHINode *PN = dyn_cast<PHINode>(I))
5750         ConstantEvolutionLoopExitValue.erase(PN);
5751     }
5752 
5753     PushDefUseChildren(I, Worklist);
5754   }
5755 }
5756 
5757 /// Get the exact loop backedge taken count considering all loop exits. A
5758 /// computable result can only be returned for loops with a single exit.
5759 /// Returning the minimum taken count among all exits is incorrect because one
5760 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5761 /// the limit of each loop test is never skipped. This is a valid assumption as
5762 /// long as the loop exits via that test. For precise results, it is the
5763 /// caller's responsibility to specify the relevant loop exit using
5764 /// getExact(ExitingBlock, SE).
5765 const SCEV *
5766 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5767                                              SCEVUnionPredicate *Preds) const {
5768   // If any exits were not computable, the loop is not computable.
5769   if (!isComplete() || ExitNotTaken.empty())
5770     return SE->getCouldNotCompute();
5771 
5772   const SCEV *BECount = nullptr;
5773   for (auto &ENT : ExitNotTaken) {
5774     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5775 
5776     if (!BECount)
5777       BECount = ENT.ExactNotTaken;
5778     else if (BECount != ENT.ExactNotTaken)
5779       return SE->getCouldNotCompute();
5780     if (Preds && !ENT.hasAlwaysTruePredicate())
5781       Preds->add(ENT.Predicate.get());
5782 
5783     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5784            "Predicate should be always true!");
5785   }
5786 
5787   assert(BECount && "Invalid not taken count for loop exit");
5788   return BECount;
5789 }
5790 
5791 /// Get the exact not taken count for this loop exit.
5792 const SCEV *
5793 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5794                                              ScalarEvolution *SE) const {
5795   for (auto &ENT : ExitNotTaken)
5796     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5797       return ENT.ExactNotTaken;
5798 
5799   return SE->getCouldNotCompute();
5800 }
5801 
5802 /// getMax - Get the max backedge taken count for the loop.
5803 const SCEV *
5804 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5805   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5806     return !ENT.hasAlwaysTruePredicate();
5807   };
5808 
5809   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5810     return SE->getCouldNotCompute();
5811 
5812   return getMax();
5813 }
5814 
5815 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5816   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5817     return !ENT.hasAlwaysTruePredicate();
5818   };
5819   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5820 }
5821 
5822 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5823                                                     ScalarEvolution *SE) const {
5824   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5825       SE->hasOperand(getMax(), S))
5826     return true;
5827 
5828   for (auto &ENT : ExitNotTaken)
5829     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5830         SE->hasOperand(ENT.ExactNotTaken, S))
5831       return true;
5832 
5833   return false;
5834 }
5835 
5836 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5837 /// computable exit into a persistent ExitNotTakenInfo array.
5838 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5839     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5840         &&ExitCounts,
5841     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5842     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5843   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5844   ExitNotTaken.reserve(ExitCounts.size());
5845   std::transform(
5846       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5847       [&](const EdgeExitInfo &EEI) {
5848         BasicBlock *ExitBB = EEI.first;
5849         const ExitLimit &EL = EEI.second;
5850         if (EL.Predicates.empty())
5851           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5852 
5853         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5854         for (auto *Pred : EL.Predicates)
5855           Predicate->add(Pred);
5856 
5857         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5858       });
5859 }
5860 
5861 /// Invalidate this result and free the ExitNotTakenInfo array.
5862 void ScalarEvolution::BackedgeTakenInfo::clear() {
5863   ExitNotTaken.clear();
5864 }
5865 
5866 /// Compute the number of times the backedge of the specified loop will execute.
5867 ScalarEvolution::BackedgeTakenInfo
5868 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5869                                            bool AllowPredicates) {
5870   SmallVector<BasicBlock *, 8> ExitingBlocks;
5871   L->getExitingBlocks(ExitingBlocks);
5872 
5873   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5874 
5875   SmallVector<EdgeExitInfo, 4> ExitCounts;
5876   bool CouldComputeBECount = true;
5877   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5878   const SCEV *MustExitMaxBECount = nullptr;
5879   const SCEV *MayExitMaxBECount = nullptr;
5880   bool MustExitMaxOrZero = false;
5881 
5882   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5883   // and compute maxBECount.
5884   // Do a union of all the predicates here.
5885   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5886     BasicBlock *ExitBB = ExitingBlocks[i];
5887     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5888 
5889     assert((AllowPredicates || EL.Predicates.empty()) &&
5890            "Predicated exit limit when predicates are not allowed!");
5891 
5892     // 1. For each exit that can be computed, add an entry to ExitCounts.
5893     // CouldComputeBECount is true only if all exits can be computed.
5894     if (EL.ExactNotTaken == getCouldNotCompute())
5895       // We couldn't compute an exact value for this exit, so
5896       // we won't be able to compute an exact value for the loop.
5897       CouldComputeBECount = false;
5898     else
5899       ExitCounts.emplace_back(ExitBB, EL);
5900 
5901     // 2. Derive the loop's MaxBECount from each exit's max number of
5902     // non-exiting iterations. Partition the loop exits into two kinds:
5903     // LoopMustExits and LoopMayExits.
5904     //
5905     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5906     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5907     // MaxBECount is the minimum EL.MaxNotTaken of computable
5908     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5909     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5910     // computable EL.MaxNotTaken.
5911     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5912         DT.dominates(ExitBB, Latch)) {
5913       if (!MustExitMaxBECount) {
5914         MustExitMaxBECount = EL.MaxNotTaken;
5915         MustExitMaxOrZero = EL.MaxOrZero;
5916       } else {
5917         MustExitMaxBECount =
5918             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5919       }
5920     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5921       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5922         MayExitMaxBECount = EL.MaxNotTaken;
5923       else {
5924         MayExitMaxBECount =
5925             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5926       }
5927     }
5928   }
5929   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5930     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5931   // The loop backedge will be taken the maximum or zero times if there's
5932   // a single exit that must be taken the maximum or zero times.
5933   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
5934   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5935                            MaxBECount, MaxOrZero);
5936 }
5937 
5938 ScalarEvolution::ExitLimit
5939 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5940                                   bool AllowPredicates) {
5941 
5942   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5943   // at this block and remember the exit block and whether all other targets
5944   // lead to the loop header.
5945   bool MustExecuteLoopHeader = true;
5946   BasicBlock *Exit = nullptr;
5947   for (auto *SBB : successors(ExitingBlock))
5948     if (!L->contains(SBB)) {
5949       if (Exit) // Multiple exit successors.
5950         return getCouldNotCompute();
5951       Exit = SBB;
5952     } else if (SBB != L->getHeader()) {
5953       MustExecuteLoopHeader = false;
5954     }
5955 
5956   // At this point, we know we have a conditional branch that determines whether
5957   // the loop is exited.  However, we don't know if the branch is executed each
5958   // time through the loop.  If not, then the execution count of the branch will
5959   // not be equal to the trip count of the loop.
5960   //
5961   // Currently we check for this by checking to see if the Exit branch goes to
5962   // the loop header.  If so, we know it will always execute the same number of
5963   // times as the loop.  We also handle the case where the exit block *is* the
5964   // loop header.  This is common for un-rotated loops.
5965   //
5966   // If both of those tests fail, walk up the unique predecessor chain to the
5967   // header, stopping if there is an edge that doesn't exit the loop. If the
5968   // header is reached, the execution count of the branch will be equal to the
5969   // trip count of the loop.
5970   //
5971   //  More extensive analysis could be done to handle more cases here.
5972   //
5973   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5974     // The simple checks failed, try climbing the unique predecessor chain
5975     // up to the header.
5976     bool Ok = false;
5977     for (BasicBlock *BB = ExitingBlock; BB; ) {
5978       BasicBlock *Pred = BB->getUniquePredecessor();
5979       if (!Pred)
5980         return getCouldNotCompute();
5981       TerminatorInst *PredTerm = Pred->getTerminator();
5982       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5983         if (PredSucc == BB)
5984           continue;
5985         // If the predecessor has a successor that isn't BB and isn't
5986         // outside the loop, assume the worst.
5987         if (L->contains(PredSucc))
5988           return getCouldNotCompute();
5989       }
5990       if (Pred == L->getHeader()) {
5991         Ok = true;
5992         break;
5993       }
5994       BB = Pred;
5995     }
5996     if (!Ok)
5997       return getCouldNotCompute();
5998   }
5999 
6000   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6001   TerminatorInst *Term = ExitingBlock->getTerminator();
6002   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6003     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6004     // Proceed to the next level to examine the exit condition expression.
6005     return computeExitLimitFromCond(
6006         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6007         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6008   }
6009 
6010   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6011     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6012                                                 /*ControlsExit=*/IsOnlyExit);
6013 
6014   return getCouldNotCompute();
6015 }
6016 
6017 ScalarEvolution::ExitLimit
6018 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
6019                                           Value *ExitCond,
6020                                           BasicBlock *TBB,
6021                                           BasicBlock *FBB,
6022                                           bool ControlsExit,
6023                                           bool AllowPredicates) {
6024   // Check if the controlling expression for this loop is an And or Or.
6025   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6026     if (BO->getOpcode() == Instruction::And) {
6027       // Recurse on the operands of the and.
6028       bool EitherMayExit = L->contains(TBB);
6029       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
6030                                                ControlsExit && !EitherMayExit,
6031                                                AllowPredicates);
6032       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
6033                                                ControlsExit && !EitherMayExit,
6034                                                AllowPredicates);
6035       const SCEV *BECount = getCouldNotCompute();
6036       const SCEV *MaxBECount = getCouldNotCompute();
6037       if (EitherMayExit) {
6038         // Both conditions must be true for the loop to continue executing.
6039         // Choose the less conservative count.
6040         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6041             EL1.ExactNotTaken == getCouldNotCompute())
6042           BECount = getCouldNotCompute();
6043         else
6044           BECount =
6045               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6046         if (EL0.MaxNotTaken == getCouldNotCompute())
6047           MaxBECount = EL1.MaxNotTaken;
6048         else if (EL1.MaxNotTaken == getCouldNotCompute())
6049           MaxBECount = EL0.MaxNotTaken;
6050         else
6051           MaxBECount =
6052               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6053       } else {
6054         // Both conditions must be true at the same time for the loop to exit.
6055         // For now, be conservative.
6056         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6057         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6058           MaxBECount = EL0.MaxNotTaken;
6059         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6060           BECount = EL0.ExactNotTaken;
6061       }
6062 
6063       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6064       // to be more aggressive when computing BECount than when computing
6065       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6066       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6067       // to not.
6068       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6069           !isa<SCEVCouldNotCompute>(BECount))
6070         MaxBECount = BECount;
6071 
6072       return ExitLimit(BECount, MaxBECount, false,
6073                        {&EL0.Predicates, &EL1.Predicates});
6074     }
6075     if (BO->getOpcode() == Instruction::Or) {
6076       // Recurse on the operands of the or.
6077       bool EitherMayExit = L->contains(FBB);
6078       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
6079                                                ControlsExit && !EitherMayExit,
6080                                                AllowPredicates);
6081       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
6082                                                ControlsExit && !EitherMayExit,
6083                                                AllowPredicates);
6084       const SCEV *BECount = getCouldNotCompute();
6085       const SCEV *MaxBECount = getCouldNotCompute();
6086       if (EitherMayExit) {
6087         // Both conditions must be false for the loop to continue executing.
6088         // Choose the less conservative count.
6089         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6090             EL1.ExactNotTaken == getCouldNotCompute())
6091           BECount = getCouldNotCompute();
6092         else
6093           BECount =
6094               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6095         if (EL0.MaxNotTaken == getCouldNotCompute())
6096           MaxBECount = EL1.MaxNotTaken;
6097         else if (EL1.MaxNotTaken == getCouldNotCompute())
6098           MaxBECount = EL0.MaxNotTaken;
6099         else
6100           MaxBECount =
6101               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6102       } else {
6103         // Both conditions must be false at the same time for the loop to exit.
6104         // For now, be conservative.
6105         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6106         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6107           MaxBECount = EL0.MaxNotTaken;
6108         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6109           BECount = EL0.ExactNotTaken;
6110       }
6111 
6112       return ExitLimit(BECount, MaxBECount, false,
6113                        {&EL0.Predicates, &EL1.Predicates});
6114     }
6115   }
6116 
6117   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6118   // Proceed to the next level to examine the icmp.
6119   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6120     ExitLimit EL =
6121         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6122     if (EL.hasFullInfo() || !AllowPredicates)
6123       return EL;
6124 
6125     // Try again, but use SCEV predicates this time.
6126     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6127                                     /*AllowPredicates=*/true);
6128   }
6129 
6130   // Check for a constant condition. These are normally stripped out by
6131   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6132   // preserve the CFG and is temporarily leaving constant conditions
6133   // in place.
6134   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6135     if (L->contains(FBB) == !CI->getZExtValue())
6136       // The backedge is always taken.
6137       return getCouldNotCompute();
6138     else
6139       // The backedge is never taken.
6140       return getZero(CI->getType());
6141   }
6142 
6143   // If it's not an integer or pointer comparison then compute it the hard way.
6144   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6145 }
6146 
6147 ScalarEvolution::ExitLimit
6148 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6149                                           ICmpInst *ExitCond,
6150                                           BasicBlock *TBB,
6151                                           BasicBlock *FBB,
6152                                           bool ControlsExit,
6153                                           bool AllowPredicates) {
6154 
6155   // If the condition was exit on true, convert the condition to exit on false
6156   ICmpInst::Predicate Cond;
6157   if (!L->contains(FBB))
6158     Cond = ExitCond->getPredicate();
6159   else
6160     Cond = ExitCond->getInversePredicate();
6161 
6162   // Handle common loops like: for (X = "string"; *X; ++X)
6163   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6164     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6165       ExitLimit ItCnt =
6166         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6167       if (ItCnt.hasAnyInfo())
6168         return ItCnt;
6169     }
6170 
6171   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6172   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6173 
6174   // Try to evaluate any dependencies out of the loop.
6175   LHS = getSCEVAtScope(LHS, L);
6176   RHS = getSCEVAtScope(RHS, L);
6177 
6178   // At this point, we would like to compute how many iterations of the
6179   // loop the predicate will return true for these inputs.
6180   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6181     // If there is a loop-invariant, force it into the RHS.
6182     std::swap(LHS, RHS);
6183     Cond = ICmpInst::getSwappedPredicate(Cond);
6184   }
6185 
6186   // Simplify the operands before analyzing them.
6187   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6188 
6189   // If we have a comparison of a chrec against a constant, try to use value
6190   // ranges to answer this query.
6191   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6192     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6193       if (AddRec->getLoop() == L) {
6194         // Form the constant range.
6195         ConstantRange CompRange =
6196             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6197 
6198         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6199         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6200       }
6201 
6202   switch (Cond) {
6203   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6204     // Convert to: while (X-Y != 0)
6205     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6206                                 AllowPredicates);
6207     if (EL.hasAnyInfo()) return EL;
6208     break;
6209   }
6210   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6211     // Convert to: while (X-Y == 0)
6212     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6213     if (EL.hasAnyInfo()) return EL;
6214     break;
6215   }
6216   case ICmpInst::ICMP_SLT:
6217   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6218     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6219     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6220                                     AllowPredicates);
6221     if (EL.hasAnyInfo()) return EL;
6222     break;
6223   }
6224   case ICmpInst::ICMP_SGT:
6225   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6226     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6227     ExitLimit EL =
6228         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6229                             AllowPredicates);
6230     if (EL.hasAnyInfo()) return EL;
6231     break;
6232   }
6233   default:
6234     break;
6235   }
6236 
6237   auto *ExhaustiveCount =
6238       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6239 
6240   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6241     return ExhaustiveCount;
6242 
6243   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6244                                       ExitCond->getOperand(1), L, Cond);
6245 }
6246 
6247 ScalarEvolution::ExitLimit
6248 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6249                                                       SwitchInst *Switch,
6250                                                       BasicBlock *ExitingBlock,
6251                                                       bool ControlsExit) {
6252   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6253 
6254   // Give up if the exit is the default dest of a switch.
6255   if (Switch->getDefaultDest() == ExitingBlock)
6256     return getCouldNotCompute();
6257 
6258   assert(L->contains(Switch->getDefaultDest()) &&
6259          "Default case must not exit the loop!");
6260   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6261   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6262 
6263   // while (X != Y) --> while (X-Y != 0)
6264   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6265   if (EL.hasAnyInfo())
6266     return EL;
6267 
6268   return getCouldNotCompute();
6269 }
6270 
6271 static ConstantInt *
6272 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6273                                 ScalarEvolution &SE) {
6274   const SCEV *InVal = SE.getConstant(C);
6275   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6276   assert(isa<SCEVConstant>(Val) &&
6277          "Evaluation of SCEV at constant didn't fold correctly?");
6278   return cast<SCEVConstant>(Val)->getValue();
6279 }
6280 
6281 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6282 /// compute the backedge execution count.
6283 ScalarEvolution::ExitLimit
6284 ScalarEvolution::computeLoadConstantCompareExitLimit(
6285   LoadInst *LI,
6286   Constant *RHS,
6287   const Loop *L,
6288   ICmpInst::Predicate predicate) {
6289 
6290   if (LI->isVolatile()) return getCouldNotCompute();
6291 
6292   // Check to see if the loaded pointer is a getelementptr of a global.
6293   // TODO: Use SCEV instead of manually grubbing with GEPs.
6294   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6295   if (!GEP) return getCouldNotCompute();
6296 
6297   // Make sure that it is really a constant global we are gepping, with an
6298   // initializer, and make sure the first IDX is really 0.
6299   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6300   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6301       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6302       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6303     return getCouldNotCompute();
6304 
6305   // Okay, we allow one non-constant index into the GEP instruction.
6306   Value *VarIdx = nullptr;
6307   std::vector<Constant*> Indexes;
6308   unsigned VarIdxNum = 0;
6309   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6310     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6311       Indexes.push_back(CI);
6312     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6313       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6314       VarIdx = GEP->getOperand(i);
6315       VarIdxNum = i-2;
6316       Indexes.push_back(nullptr);
6317     }
6318 
6319   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6320   if (!VarIdx)
6321     return getCouldNotCompute();
6322 
6323   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6324   // Check to see if X is a loop variant variable value now.
6325   const SCEV *Idx = getSCEV(VarIdx);
6326   Idx = getSCEVAtScope(Idx, L);
6327 
6328   // We can only recognize very limited forms of loop index expressions, in
6329   // particular, only affine AddRec's like {C1,+,C2}.
6330   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6331   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6332       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6333       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6334     return getCouldNotCompute();
6335 
6336   unsigned MaxSteps = MaxBruteForceIterations;
6337   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6338     ConstantInt *ItCst = ConstantInt::get(
6339                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6340     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6341 
6342     // Form the GEP offset.
6343     Indexes[VarIdxNum] = Val;
6344 
6345     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6346                                                          Indexes);
6347     if (!Result) break;  // Cannot compute!
6348 
6349     // Evaluate the condition for this iteration.
6350     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6351     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6352     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6353       ++NumArrayLenItCounts;
6354       return getConstant(ItCst);   // Found terminating iteration!
6355     }
6356   }
6357   return getCouldNotCompute();
6358 }
6359 
6360 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6361     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6362   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6363   if (!RHS)
6364     return getCouldNotCompute();
6365 
6366   const BasicBlock *Latch = L->getLoopLatch();
6367   if (!Latch)
6368     return getCouldNotCompute();
6369 
6370   const BasicBlock *Predecessor = L->getLoopPredecessor();
6371   if (!Predecessor)
6372     return getCouldNotCompute();
6373 
6374   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6375   // Return LHS in OutLHS and shift_opt in OutOpCode.
6376   auto MatchPositiveShift =
6377       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6378 
6379     using namespace PatternMatch;
6380 
6381     ConstantInt *ShiftAmt;
6382     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6383       OutOpCode = Instruction::LShr;
6384     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6385       OutOpCode = Instruction::AShr;
6386     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6387       OutOpCode = Instruction::Shl;
6388     else
6389       return false;
6390 
6391     return ShiftAmt->getValue().isStrictlyPositive();
6392   };
6393 
6394   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6395   //
6396   // loop:
6397   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6398   //   %iv.shifted = lshr i32 %iv, <positive constant>
6399   //
6400   // Return true on a successful match.  Return the corresponding PHI node (%iv
6401   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6402   auto MatchShiftRecurrence =
6403       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6404     Optional<Instruction::BinaryOps> PostShiftOpCode;
6405 
6406     {
6407       Instruction::BinaryOps OpC;
6408       Value *V;
6409 
6410       // If we encounter a shift instruction, "peel off" the shift operation,
6411       // and remember that we did so.  Later when we inspect %iv's backedge
6412       // value, we will make sure that the backedge value uses the same
6413       // operation.
6414       //
6415       // Note: the peeled shift operation does not have to be the same
6416       // instruction as the one feeding into the PHI's backedge value.  We only
6417       // really care about it being the same *kind* of shift instruction --
6418       // that's all that is required for our later inferences to hold.
6419       if (MatchPositiveShift(LHS, V, OpC)) {
6420         PostShiftOpCode = OpC;
6421         LHS = V;
6422       }
6423     }
6424 
6425     PNOut = dyn_cast<PHINode>(LHS);
6426     if (!PNOut || PNOut->getParent() != L->getHeader())
6427       return false;
6428 
6429     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6430     Value *OpLHS;
6431 
6432     return
6433         // The backedge value for the PHI node must be a shift by a positive
6434         // amount
6435         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6436 
6437         // of the PHI node itself
6438         OpLHS == PNOut &&
6439 
6440         // and the kind of shift should be match the kind of shift we peeled
6441         // off, if any.
6442         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6443   };
6444 
6445   PHINode *PN;
6446   Instruction::BinaryOps OpCode;
6447   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6448     return getCouldNotCompute();
6449 
6450   const DataLayout &DL = getDataLayout();
6451 
6452   // The key rationale for this optimization is that for some kinds of shift
6453   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6454   // within a finite number of iterations.  If the condition guarding the
6455   // backedge (in the sense that the backedge is taken if the condition is true)
6456   // is false for the value the shift recurrence stabilizes to, then we know
6457   // that the backedge is taken only a finite number of times.
6458 
6459   ConstantInt *StableValue = nullptr;
6460   switch (OpCode) {
6461   default:
6462     llvm_unreachable("Impossible case!");
6463 
6464   case Instruction::AShr: {
6465     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6466     // bitwidth(K) iterations.
6467     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6468     bool KnownZero, KnownOne;
6469     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6470                    Predecessor->getTerminator(), &DT);
6471     auto *Ty = cast<IntegerType>(RHS->getType());
6472     if (KnownZero)
6473       StableValue = ConstantInt::get(Ty, 0);
6474     else if (KnownOne)
6475       StableValue = ConstantInt::get(Ty, -1, true);
6476     else
6477       return getCouldNotCompute();
6478 
6479     break;
6480   }
6481   case Instruction::LShr:
6482   case Instruction::Shl:
6483     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6484     // stabilize to 0 in at most bitwidth(K) iterations.
6485     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6486     break;
6487   }
6488 
6489   auto *Result =
6490       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6491   assert(Result->getType()->isIntegerTy(1) &&
6492          "Otherwise cannot be an operand to a branch instruction");
6493 
6494   if (Result->isZeroValue()) {
6495     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6496     const SCEV *UpperBound =
6497         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6498     return ExitLimit(getCouldNotCompute(), UpperBound, false);
6499   }
6500 
6501   return getCouldNotCompute();
6502 }
6503 
6504 /// Return true if we can constant fold an instruction of the specified type,
6505 /// assuming that all operands were constants.
6506 static bool CanConstantFold(const Instruction *I) {
6507   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6508       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6509       isa<LoadInst>(I))
6510     return true;
6511 
6512   if (const CallInst *CI = dyn_cast<CallInst>(I))
6513     if (const Function *F = CI->getCalledFunction())
6514       return canConstantFoldCallTo(F);
6515   return false;
6516 }
6517 
6518 /// Determine whether this instruction can constant evolve within this loop
6519 /// assuming its operands can all constant evolve.
6520 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6521   // An instruction outside of the loop can't be derived from a loop PHI.
6522   if (!L->contains(I)) return false;
6523 
6524   if (isa<PHINode>(I)) {
6525     // We don't currently keep track of the control flow needed to evaluate
6526     // PHIs, so we cannot handle PHIs inside of loops.
6527     return L->getHeader() == I->getParent();
6528   }
6529 
6530   // If we won't be able to constant fold this expression even if the operands
6531   // are constants, bail early.
6532   return CanConstantFold(I);
6533 }
6534 
6535 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6536 /// recursing through each instruction operand until reaching a loop header phi.
6537 static PHINode *
6538 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6539                                DenseMap<Instruction *, PHINode *> &PHIMap,
6540                                unsigned Depth) {
6541   if (Depth > MaxConstantEvolvingDepth)
6542     return nullptr;
6543 
6544   // Otherwise, we can evaluate this instruction if all of its operands are
6545   // constant or derived from a PHI node themselves.
6546   PHINode *PHI = nullptr;
6547   for (Value *Op : UseInst->operands()) {
6548     if (isa<Constant>(Op)) continue;
6549 
6550     Instruction *OpInst = dyn_cast<Instruction>(Op);
6551     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6552 
6553     PHINode *P = dyn_cast<PHINode>(OpInst);
6554     if (!P)
6555       // If this operand is already visited, reuse the prior result.
6556       // We may have P != PHI if this is the deepest point at which the
6557       // inconsistent paths meet.
6558       P = PHIMap.lookup(OpInst);
6559     if (!P) {
6560       // Recurse and memoize the results, whether a phi is found or not.
6561       // This recursive call invalidates pointers into PHIMap.
6562       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6563       PHIMap[OpInst] = P;
6564     }
6565     if (!P)
6566       return nullptr;  // Not evolving from PHI
6567     if (PHI && PHI != P)
6568       return nullptr;  // Evolving from multiple different PHIs.
6569     PHI = P;
6570   }
6571   // This is a expression evolving from a constant PHI!
6572   return PHI;
6573 }
6574 
6575 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6576 /// in the loop that V is derived from.  We allow arbitrary operations along the
6577 /// way, but the operands of an operation must either be constants or a value
6578 /// derived from a constant PHI.  If this expression does not fit with these
6579 /// constraints, return null.
6580 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6581   Instruction *I = dyn_cast<Instruction>(V);
6582   if (!I || !canConstantEvolve(I, L)) return nullptr;
6583 
6584   if (PHINode *PN = dyn_cast<PHINode>(I))
6585     return PN;
6586 
6587   // Record non-constant instructions contained by the loop.
6588   DenseMap<Instruction *, PHINode *> PHIMap;
6589   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6590 }
6591 
6592 /// EvaluateExpression - Given an expression that passes the
6593 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6594 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6595 /// reason, return null.
6596 static Constant *EvaluateExpression(Value *V, const Loop *L,
6597                                     DenseMap<Instruction *, Constant *> &Vals,
6598                                     const DataLayout &DL,
6599                                     const TargetLibraryInfo *TLI) {
6600   // Convenient constant check, but redundant for recursive calls.
6601   if (Constant *C = dyn_cast<Constant>(V)) return C;
6602   Instruction *I = dyn_cast<Instruction>(V);
6603   if (!I) return nullptr;
6604 
6605   if (Constant *C = Vals.lookup(I)) return C;
6606 
6607   // An instruction inside the loop depends on a value outside the loop that we
6608   // weren't given a mapping for, or a value such as a call inside the loop.
6609   if (!canConstantEvolve(I, L)) return nullptr;
6610 
6611   // An unmapped PHI can be due to a branch or another loop inside this loop,
6612   // or due to this not being the initial iteration through a loop where we
6613   // couldn't compute the evolution of this particular PHI last time.
6614   if (isa<PHINode>(I)) return nullptr;
6615 
6616   std::vector<Constant*> Operands(I->getNumOperands());
6617 
6618   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6619     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6620     if (!Operand) {
6621       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6622       if (!Operands[i]) return nullptr;
6623       continue;
6624     }
6625     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6626     Vals[Operand] = C;
6627     if (!C) return nullptr;
6628     Operands[i] = C;
6629   }
6630 
6631   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6632     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6633                                            Operands[1], DL, TLI);
6634   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6635     if (!LI->isVolatile())
6636       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6637   }
6638   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6639 }
6640 
6641 
6642 // If every incoming value to PN except the one for BB is a specific Constant,
6643 // return that, else return nullptr.
6644 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6645   Constant *IncomingVal = nullptr;
6646 
6647   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6648     if (PN->getIncomingBlock(i) == BB)
6649       continue;
6650 
6651     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6652     if (!CurrentVal)
6653       return nullptr;
6654 
6655     if (IncomingVal != CurrentVal) {
6656       if (IncomingVal)
6657         return nullptr;
6658       IncomingVal = CurrentVal;
6659     }
6660   }
6661 
6662   return IncomingVal;
6663 }
6664 
6665 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6666 /// in the header of its containing loop, we know the loop executes a
6667 /// constant number of times, and the PHI node is just a recurrence
6668 /// involving constants, fold it.
6669 Constant *
6670 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6671                                                    const APInt &BEs,
6672                                                    const Loop *L) {
6673   auto I = ConstantEvolutionLoopExitValue.find(PN);
6674   if (I != ConstantEvolutionLoopExitValue.end())
6675     return I->second;
6676 
6677   if (BEs.ugt(MaxBruteForceIterations))
6678     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6679 
6680   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6681 
6682   DenseMap<Instruction *, Constant *> CurrentIterVals;
6683   BasicBlock *Header = L->getHeader();
6684   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6685 
6686   BasicBlock *Latch = L->getLoopLatch();
6687   if (!Latch)
6688     return nullptr;
6689 
6690   for (auto &I : *Header) {
6691     PHINode *PHI = dyn_cast<PHINode>(&I);
6692     if (!PHI) break;
6693     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6694     if (!StartCST) continue;
6695     CurrentIterVals[PHI] = StartCST;
6696   }
6697   if (!CurrentIterVals.count(PN))
6698     return RetVal = nullptr;
6699 
6700   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6701 
6702   // Execute the loop symbolically to determine the exit value.
6703   if (BEs.getActiveBits() >= 32)
6704     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6705 
6706   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6707   unsigned IterationNum = 0;
6708   const DataLayout &DL = getDataLayout();
6709   for (; ; ++IterationNum) {
6710     if (IterationNum == NumIterations)
6711       return RetVal = CurrentIterVals[PN];  // Got exit value!
6712 
6713     // Compute the value of the PHIs for the next iteration.
6714     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6715     DenseMap<Instruction *, Constant *> NextIterVals;
6716     Constant *NextPHI =
6717         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6718     if (!NextPHI)
6719       return nullptr;        // Couldn't evaluate!
6720     NextIterVals[PN] = NextPHI;
6721 
6722     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6723 
6724     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6725     // cease to be able to evaluate one of them or if they stop evolving,
6726     // because that doesn't necessarily prevent us from computing PN.
6727     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6728     for (const auto &I : CurrentIterVals) {
6729       PHINode *PHI = dyn_cast<PHINode>(I.first);
6730       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6731       PHIsToCompute.emplace_back(PHI, I.second);
6732     }
6733     // We use two distinct loops because EvaluateExpression may invalidate any
6734     // iterators into CurrentIterVals.
6735     for (const auto &I : PHIsToCompute) {
6736       PHINode *PHI = I.first;
6737       Constant *&NextPHI = NextIterVals[PHI];
6738       if (!NextPHI) {   // Not already computed.
6739         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6740         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6741       }
6742       if (NextPHI != I.second)
6743         StoppedEvolving = false;
6744     }
6745 
6746     // If all entries in CurrentIterVals == NextIterVals then we can stop
6747     // iterating, the loop can't continue to change.
6748     if (StoppedEvolving)
6749       return RetVal = CurrentIterVals[PN];
6750 
6751     CurrentIterVals.swap(NextIterVals);
6752   }
6753 }
6754 
6755 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6756                                                           Value *Cond,
6757                                                           bool ExitWhen) {
6758   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6759   if (!PN) return getCouldNotCompute();
6760 
6761   // If the loop is canonicalized, the PHI will have exactly two entries.
6762   // That's the only form we support here.
6763   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6764 
6765   DenseMap<Instruction *, Constant *> CurrentIterVals;
6766   BasicBlock *Header = L->getHeader();
6767   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6768 
6769   BasicBlock *Latch = L->getLoopLatch();
6770   assert(Latch && "Should follow from NumIncomingValues == 2!");
6771 
6772   for (auto &I : *Header) {
6773     PHINode *PHI = dyn_cast<PHINode>(&I);
6774     if (!PHI)
6775       break;
6776     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6777     if (!StartCST) continue;
6778     CurrentIterVals[PHI] = StartCST;
6779   }
6780   if (!CurrentIterVals.count(PN))
6781     return getCouldNotCompute();
6782 
6783   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6784   // the loop symbolically to determine when the condition gets a value of
6785   // "ExitWhen".
6786   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6787   const DataLayout &DL = getDataLayout();
6788   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6789     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6790         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6791 
6792     // Couldn't symbolically evaluate.
6793     if (!CondVal) return getCouldNotCompute();
6794 
6795     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6796       ++NumBruteForceTripCountsComputed;
6797       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6798     }
6799 
6800     // Update all the PHI nodes for the next iteration.
6801     DenseMap<Instruction *, Constant *> NextIterVals;
6802 
6803     // Create a list of which PHIs we need to compute. We want to do this before
6804     // calling EvaluateExpression on them because that may invalidate iterators
6805     // into CurrentIterVals.
6806     SmallVector<PHINode *, 8> PHIsToCompute;
6807     for (const auto &I : CurrentIterVals) {
6808       PHINode *PHI = dyn_cast<PHINode>(I.first);
6809       if (!PHI || PHI->getParent() != Header) continue;
6810       PHIsToCompute.push_back(PHI);
6811     }
6812     for (PHINode *PHI : PHIsToCompute) {
6813       Constant *&NextPHI = NextIterVals[PHI];
6814       if (NextPHI) continue;    // Already computed!
6815 
6816       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6817       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6818     }
6819     CurrentIterVals.swap(NextIterVals);
6820   }
6821 
6822   // Too many iterations were needed to evaluate.
6823   return getCouldNotCompute();
6824 }
6825 
6826 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6827   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6828       ValuesAtScopes[V];
6829   // Check to see if we've folded this expression at this loop before.
6830   for (auto &LS : Values)
6831     if (LS.first == L)
6832       return LS.second ? LS.second : V;
6833 
6834   Values.emplace_back(L, nullptr);
6835 
6836   // Otherwise compute it.
6837   const SCEV *C = computeSCEVAtScope(V, L);
6838   for (auto &LS : reverse(ValuesAtScopes[V]))
6839     if (LS.first == L) {
6840       LS.second = C;
6841       break;
6842     }
6843   return C;
6844 }
6845 
6846 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6847 /// will return Constants for objects which aren't represented by a
6848 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6849 /// Returns NULL if the SCEV isn't representable as a Constant.
6850 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6851   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6852     case scCouldNotCompute:
6853     case scAddRecExpr:
6854       break;
6855     case scConstant:
6856       return cast<SCEVConstant>(V)->getValue();
6857     case scUnknown:
6858       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6859     case scSignExtend: {
6860       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6861       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6862         return ConstantExpr::getSExt(CastOp, SS->getType());
6863       break;
6864     }
6865     case scZeroExtend: {
6866       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6867       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6868         return ConstantExpr::getZExt(CastOp, SZ->getType());
6869       break;
6870     }
6871     case scTruncate: {
6872       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6873       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6874         return ConstantExpr::getTrunc(CastOp, ST->getType());
6875       break;
6876     }
6877     case scAddExpr: {
6878       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6879       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6880         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6881           unsigned AS = PTy->getAddressSpace();
6882           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6883           C = ConstantExpr::getBitCast(C, DestPtrTy);
6884         }
6885         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6886           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6887           if (!C2) return nullptr;
6888 
6889           // First pointer!
6890           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6891             unsigned AS = C2->getType()->getPointerAddressSpace();
6892             std::swap(C, C2);
6893             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6894             // The offsets have been converted to bytes.  We can add bytes to an
6895             // i8* by GEP with the byte count in the first index.
6896             C = ConstantExpr::getBitCast(C, DestPtrTy);
6897           }
6898 
6899           // Don't bother trying to sum two pointers. We probably can't
6900           // statically compute a load that results from it anyway.
6901           if (C2->getType()->isPointerTy())
6902             return nullptr;
6903 
6904           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6905             if (PTy->getElementType()->isStructTy())
6906               C2 = ConstantExpr::getIntegerCast(
6907                   C2, Type::getInt32Ty(C->getContext()), true);
6908             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6909           } else
6910             C = ConstantExpr::getAdd(C, C2);
6911         }
6912         return C;
6913       }
6914       break;
6915     }
6916     case scMulExpr: {
6917       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6918       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6919         // Don't bother with pointers at all.
6920         if (C->getType()->isPointerTy()) return nullptr;
6921         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6922           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6923           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6924           C = ConstantExpr::getMul(C, C2);
6925         }
6926         return C;
6927       }
6928       break;
6929     }
6930     case scUDivExpr: {
6931       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6932       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6933         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6934           if (LHS->getType() == RHS->getType())
6935             return ConstantExpr::getUDiv(LHS, RHS);
6936       break;
6937     }
6938     case scSMaxExpr:
6939     case scUMaxExpr:
6940       break; // TODO: smax, umax.
6941   }
6942   return nullptr;
6943 }
6944 
6945 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6946   if (isa<SCEVConstant>(V)) return V;
6947 
6948   // If this instruction is evolved from a constant-evolving PHI, compute the
6949   // exit value from the loop without using SCEVs.
6950   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6951     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6952       const Loop *LI = this->LI[I->getParent()];
6953       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6954         if (PHINode *PN = dyn_cast<PHINode>(I))
6955           if (PN->getParent() == LI->getHeader()) {
6956             // Okay, there is no closed form solution for the PHI node.  Check
6957             // to see if the loop that contains it has a known backedge-taken
6958             // count.  If so, we may be able to force computation of the exit
6959             // value.
6960             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6961             if (const SCEVConstant *BTCC =
6962                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6963               // Okay, we know how many times the containing loop executes.  If
6964               // this is a constant evolving PHI node, get the final value at
6965               // the specified iteration number.
6966               Constant *RV =
6967                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
6968               if (RV) return getSCEV(RV);
6969             }
6970           }
6971 
6972       // Okay, this is an expression that we cannot symbolically evaluate
6973       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6974       // the arguments into constants, and if so, try to constant propagate the
6975       // result.  This is particularly useful for computing loop exit values.
6976       if (CanConstantFold(I)) {
6977         SmallVector<Constant *, 4> Operands;
6978         bool MadeImprovement = false;
6979         for (Value *Op : I->operands()) {
6980           if (Constant *C = dyn_cast<Constant>(Op)) {
6981             Operands.push_back(C);
6982             continue;
6983           }
6984 
6985           // If any of the operands is non-constant and if they are
6986           // non-integer and non-pointer, don't even try to analyze them
6987           // with scev techniques.
6988           if (!isSCEVable(Op->getType()))
6989             return V;
6990 
6991           const SCEV *OrigV = getSCEV(Op);
6992           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6993           MadeImprovement |= OrigV != OpV;
6994 
6995           Constant *C = BuildConstantFromSCEV(OpV);
6996           if (!C) return V;
6997           if (C->getType() != Op->getType())
6998             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6999                                                               Op->getType(),
7000                                                               false),
7001                                       C, Op->getType());
7002           Operands.push_back(C);
7003         }
7004 
7005         // Check to see if getSCEVAtScope actually made an improvement.
7006         if (MadeImprovement) {
7007           Constant *C = nullptr;
7008           const DataLayout &DL = getDataLayout();
7009           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7010             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7011                                                 Operands[1], DL, &TLI);
7012           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7013             if (!LI->isVolatile())
7014               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7015           } else
7016             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7017           if (!C) return V;
7018           return getSCEV(C);
7019         }
7020       }
7021     }
7022 
7023     // This is some other type of SCEVUnknown, just return it.
7024     return V;
7025   }
7026 
7027   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7028     // Avoid performing the look-up in the common case where the specified
7029     // expression has no loop-variant portions.
7030     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7031       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7032       if (OpAtScope != Comm->getOperand(i)) {
7033         // Okay, at least one of these operands is loop variant but might be
7034         // foldable.  Build a new instance of the folded commutative expression.
7035         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7036                                             Comm->op_begin()+i);
7037         NewOps.push_back(OpAtScope);
7038 
7039         for (++i; i != e; ++i) {
7040           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7041           NewOps.push_back(OpAtScope);
7042         }
7043         if (isa<SCEVAddExpr>(Comm))
7044           return getAddExpr(NewOps);
7045         if (isa<SCEVMulExpr>(Comm))
7046           return getMulExpr(NewOps);
7047         if (isa<SCEVSMaxExpr>(Comm))
7048           return getSMaxExpr(NewOps);
7049         if (isa<SCEVUMaxExpr>(Comm))
7050           return getUMaxExpr(NewOps);
7051         llvm_unreachable("Unknown commutative SCEV type!");
7052       }
7053     }
7054     // If we got here, all operands are loop invariant.
7055     return Comm;
7056   }
7057 
7058   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7059     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7060     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7061     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7062       return Div;   // must be loop invariant
7063     return getUDivExpr(LHS, RHS);
7064   }
7065 
7066   // If this is a loop recurrence for a loop that does not contain L, then we
7067   // are dealing with the final value computed by the loop.
7068   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7069     // First, attempt to evaluate each operand.
7070     // Avoid performing the look-up in the common case where the specified
7071     // expression has no loop-variant portions.
7072     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7073       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7074       if (OpAtScope == AddRec->getOperand(i))
7075         continue;
7076 
7077       // Okay, at least one of these operands is loop variant but might be
7078       // foldable.  Build a new instance of the folded commutative expression.
7079       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7080                                           AddRec->op_begin()+i);
7081       NewOps.push_back(OpAtScope);
7082       for (++i; i != e; ++i)
7083         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7084 
7085       const SCEV *FoldedRec =
7086         getAddRecExpr(NewOps, AddRec->getLoop(),
7087                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7088       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7089       // The addrec may be folded to a nonrecurrence, for example, if the
7090       // induction variable is multiplied by zero after constant folding. Go
7091       // ahead and return the folded value.
7092       if (!AddRec)
7093         return FoldedRec;
7094       break;
7095     }
7096 
7097     // If the scope is outside the addrec's loop, evaluate it by using the
7098     // loop exit value of the addrec.
7099     if (!AddRec->getLoop()->contains(L)) {
7100       // To evaluate this recurrence, we need to know how many times the AddRec
7101       // loop iterates.  Compute this now.
7102       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7103       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7104 
7105       // Then, evaluate the AddRec.
7106       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7107     }
7108 
7109     return AddRec;
7110   }
7111 
7112   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7113     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7114     if (Op == Cast->getOperand())
7115       return Cast;  // must be loop invariant
7116     return getZeroExtendExpr(Op, Cast->getType());
7117   }
7118 
7119   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7120     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7121     if (Op == Cast->getOperand())
7122       return Cast;  // must be loop invariant
7123     return getSignExtendExpr(Op, Cast->getType());
7124   }
7125 
7126   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7127     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7128     if (Op == Cast->getOperand())
7129       return Cast;  // must be loop invariant
7130     return getTruncateExpr(Op, Cast->getType());
7131   }
7132 
7133   llvm_unreachable("Unknown SCEV type!");
7134 }
7135 
7136 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7137   return getSCEVAtScope(getSCEV(V), L);
7138 }
7139 
7140 /// Finds the minimum unsigned root of the following equation:
7141 ///
7142 ///     A * X = B (mod N)
7143 ///
7144 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7145 /// A and B isn't important.
7146 ///
7147 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7148 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7149                                                ScalarEvolution &SE) {
7150   uint32_t BW = A.getBitWidth();
7151   assert(BW == SE.getTypeSizeInBits(B->getType()));
7152   assert(A != 0 && "A must be non-zero.");
7153 
7154   // 1. D = gcd(A, N)
7155   //
7156   // The gcd of A and N may have only one prime factor: 2. The number of
7157   // trailing zeros in A is its multiplicity
7158   uint32_t Mult2 = A.countTrailingZeros();
7159   // D = 2^Mult2
7160 
7161   // 2. Check if B is divisible by D.
7162   //
7163   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7164   // is not less than multiplicity of this prime factor for D.
7165   if (SE.GetMinTrailingZeros(B) < Mult2)
7166     return SE.getCouldNotCompute();
7167 
7168   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7169   // modulo (N / D).
7170   //
7171   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7172   // (N / D) in general. The inverse itself always fits into BW bits, though,
7173   // so we immediately truncate it.
7174   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7175   APInt Mod(BW + 1, 0);
7176   Mod.setBit(BW - Mult2);  // Mod = N / D
7177   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7178 
7179   // 4. Compute the minimum unsigned root of the equation:
7180   // I * (B / D) mod (N / D)
7181   // To simplify the computation, we factor out the divide by D:
7182   // (I * B mod N) / D
7183   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7184   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7185 }
7186 
7187 /// Find the roots of the quadratic equation for the given quadratic chrec
7188 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7189 /// two SCEVCouldNotCompute objects.
7190 ///
7191 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7192 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7193   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7194   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7195   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7196   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7197 
7198   // We currently can only solve this if the coefficients are constants.
7199   if (!LC || !MC || !NC)
7200     return None;
7201 
7202   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7203   const APInt &L = LC->getAPInt();
7204   const APInt &M = MC->getAPInt();
7205   const APInt &N = NC->getAPInt();
7206   APInt Two(BitWidth, 2);
7207   APInt Four(BitWidth, 4);
7208 
7209   {
7210     using namespace APIntOps;
7211     const APInt& C = L;
7212     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7213     // The B coefficient is M-N/2
7214     APInt B(M);
7215     B -= sdiv(N,Two);
7216 
7217     // The A coefficient is N/2
7218     APInt A(N.sdiv(Two));
7219 
7220     // Compute the B^2-4ac term.
7221     APInt SqrtTerm(B);
7222     SqrtTerm *= B;
7223     SqrtTerm -= Four * (A * C);
7224 
7225     if (SqrtTerm.isNegative()) {
7226       // The loop is provably infinite.
7227       return None;
7228     }
7229 
7230     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7231     // integer value or else APInt::sqrt() will assert.
7232     APInt SqrtVal(SqrtTerm.sqrt());
7233 
7234     // Compute the two solutions for the quadratic formula.
7235     // The divisions must be performed as signed divisions.
7236     APInt NegB(-B);
7237     APInt TwoA(A << 1);
7238     if (TwoA.isMinValue())
7239       return None;
7240 
7241     LLVMContext &Context = SE.getContext();
7242 
7243     ConstantInt *Solution1 =
7244       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7245     ConstantInt *Solution2 =
7246       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7247 
7248     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7249                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7250   } // end APIntOps namespace
7251 }
7252 
7253 ScalarEvolution::ExitLimit
7254 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7255                               bool AllowPredicates) {
7256 
7257   // This is only used for loops with a "x != y" exit test. The exit condition
7258   // is now expressed as a single expression, V = x-y. So the exit test is
7259   // effectively V != 0.  We know and take advantage of the fact that this
7260   // expression only being used in a comparison by zero context.
7261 
7262   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7263   // If the value is a constant
7264   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7265     // If the value is already zero, the branch will execute zero times.
7266     if (C->getValue()->isZero()) return C;
7267     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7268   }
7269 
7270   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7271   if (!AddRec && AllowPredicates)
7272     // Try to make this an AddRec using runtime tests, in the first X
7273     // iterations of this loop, where X is the SCEV expression found by the
7274     // algorithm below.
7275     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7276 
7277   if (!AddRec || AddRec->getLoop() != L)
7278     return getCouldNotCompute();
7279 
7280   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7281   // the quadratic equation to solve it.
7282   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7283     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7284       const SCEVConstant *R1 = Roots->first;
7285       const SCEVConstant *R2 = Roots->second;
7286       // Pick the smallest positive root value.
7287       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7288               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7289         if (!CB->getZExtValue())
7290           std::swap(R1, R2); // R1 is the minimum root now.
7291 
7292         // We can only use this value if the chrec ends up with an exact zero
7293         // value at this index.  When solving for "X*X != 5", for example, we
7294         // should not accept a root of 2.
7295         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7296         if (Val->isZero())
7297           // We found a quadratic root!
7298           return ExitLimit(R1, R1, false, Predicates);
7299       }
7300     }
7301     return getCouldNotCompute();
7302   }
7303 
7304   // Otherwise we can only handle this if it is affine.
7305   if (!AddRec->isAffine())
7306     return getCouldNotCompute();
7307 
7308   // If this is an affine expression, the execution count of this branch is
7309   // the minimum unsigned root of the following equation:
7310   //
7311   //     Start + Step*N = 0 (mod 2^BW)
7312   //
7313   // equivalent to:
7314   //
7315   //             Step*N = -Start (mod 2^BW)
7316   //
7317   // where BW is the common bit width of Start and Step.
7318 
7319   // Get the initial value for the loop.
7320   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7321   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7322 
7323   // For now we handle only constant steps.
7324   //
7325   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7326   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7327   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7328   // We have not yet seen any such cases.
7329   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7330   if (!StepC || StepC->getValue()->equalsInt(0))
7331     return getCouldNotCompute();
7332 
7333   // For positive steps (counting up until unsigned overflow):
7334   //   N = -Start/Step (as unsigned)
7335   // For negative steps (counting down to zero):
7336   //   N = Start/-Step
7337   // First compute the unsigned distance from zero in the direction of Step.
7338   bool CountDown = StepC->getAPInt().isNegative();
7339   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7340 
7341   // Handle unitary steps, which cannot wraparound.
7342   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7343   //   N = Distance (as unsigned)
7344   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7345     APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7346 
7347     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7348     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7349     // case, and see if we can improve the bound.
7350     //
7351     // Explicitly handling this here is necessary because getUnsignedRange
7352     // isn't context-sensitive; it doesn't know that we only care about the
7353     // range inside the loop.
7354     const SCEV *Zero = getZero(Distance->getType());
7355     const SCEV *One = getOne(Distance->getType());
7356     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7357     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7358       // If Distance + 1 doesn't overflow, we can compute the maximum distance
7359       // as "unsigned_max(Distance + 1) - 1".
7360       ConstantRange CR = getUnsignedRange(DistancePlusOne);
7361       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7362     }
7363     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7364   }
7365 
7366   // If the condition controls loop exit (the loop exits only if the expression
7367   // is true) and the addition is no-wrap we can use unsigned divide to
7368   // compute the backedge count.  In this case, the step may not divide the
7369   // distance, but we don't care because if the condition is "missed" the loop
7370   // will have undefined behavior due to wrapping.
7371   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7372       loopHasNoAbnormalExits(AddRec->getLoop())) {
7373     const SCEV *Exact =
7374         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7375     return ExitLimit(Exact, Exact, false, Predicates);
7376   }
7377 
7378   // Solve the general equation.
7379   const SCEV *E = SolveLinEquationWithOverflow(
7380       StepC->getAPInt(), getNegativeSCEV(Start), *this);
7381   return ExitLimit(E, E, false, Predicates);
7382 }
7383 
7384 ScalarEvolution::ExitLimit
7385 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7386   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7387   // handle them yet except for the trivial case.  This could be expanded in the
7388   // future as needed.
7389 
7390   // If the value is a constant, check to see if it is known to be non-zero
7391   // already.  If so, the backedge will execute zero times.
7392   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7393     if (!C->getValue()->isNullValue())
7394       return getZero(C->getType());
7395     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7396   }
7397 
7398   // We could implement others, but I really doubt anyone writes loops like
7399   // this, and if they did, they would already be constant folded.
7400   return getCouldNotCompute();
7401 }
7402 
7403 std::pair<BasicBlock *, BasicBlock *>
7404 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7405   // If the block has a unique predecessor, then there is no path from the
7406   // predecessor to the block that does not go through the direct edge
7407   // from the predecessor to the block.
7408   if (BasicBlock *Pred = BB->getSinglePredecessor())
7409     return {Pred, BB};
7410 
7411   // A loop's header is defined to be a block that dominates the loop.
7412   // If the header has a unique predecessor outside the loop, it must be
7413   // a block that has exactly one successor that can reach the loop.
7414   if (Loop *L = LI.getLoopFor(BB))
7415     return {L->getLoopPredecessor(), L->getHeader()};
7416 
7417   return {nullptr, nullptr};
7418 }
7419 
7420 /// SCEV structural equivalence is usually sufficient for testing whether two
7421 /// expressions are equal, however for the purposes of looking for a condition
7422 /// guarding a loop, it can be useful to be a little more general, since a
7423 /// front-end may have replicated the controlling expression.
7424 ///
7425 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7426   // Quick check to see if they are the same SCEV.
7427   if (A == B) return true;
7428 
7429   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7430     // Not all instructions that are "identical" compute the same value.  For
7431     // instance, two distinct alloca instructions allocating the same type are
7432     // identical and do not read memory; but compute distinct values.
7433     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7434   };
7435 
7436   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7437   // two different instructions with the same value. Check for this case.
7438   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7439     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7440       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7441         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7442           if (ComputesEqualValues(AI, BI))
7443             return true;
7444 
7445   // Otherwise assume they may have a different value.
7446   return false;
7447 }
7448 
7449 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7450                                            const SCEV *&LHS, const SCEV *&RHS,
7451                                            unsigned Depth) {
7452   bool Changed = false;
7453 
7454   // If we hit the max recursion limit bail out.
7455   if (Depth >= 3)
7456     return false;
7457 
7458   // Canonicalize a constant to the right side.
7459   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7460     // Check for both operands constant.
7461     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7462       if (ConstantExpr::getICmp(Pred,
7463                                 LHSC->getValue(),
7464                                 RHSC->getValue())->isNullValue())
7465         goto trivially_false;
7466       else
7467         goto trivially_true;
7468     }
7469     // Otherwise swap the operands to put the constant on the right.
7470     std::swap(LHS, RHS);
7471     Pred = ICmpInst::getSwappedPredicate(Pred);
7472     Changed = true;
7473   }
7474 
7475   // If we're comparing an addrec with a value which is loop-invariant in the
7476   // addrec's loop, put the addrec on the left. Also make a dominance check,
7477   // as both operands could be addrecs loop-invariant in each other's loop.
7478   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7479     const Loop *L = AR->getLoop();
7480     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7481       std::swap(LHS, RHS);
7482       Pred = ICmpInst::getSwappedPredicate(Pred);
7483       Changed = true;
7484     }
7485   }
7486 
7487   // If there's a constant operand, canonicalize comparisons with boundary
7488   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7489   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7490     const APInt &RA = RC->getAPInt();
7491 
7492     bool SimplifiedByConstantRange = false;
7493 
7494     if (!ICmpInst::isEquality(Pred)) {
7495       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7496       if (ExactCR.isFullSet())
7497         goto trivially_true;
7498       else if (ExactCR.isEmptySet())
7499         goto trivially_false;
7500 
7501       APInt NewRHS;
7502       CmpInst::Predicate NewPred;
7503       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7504           ICmpInst::isEquality(NewPred)) {
7505         // We were able to convert an inequality to an equality.
7506         Pred = NewPred;
7507         RHS = getConstant(NewRHS);
7508         Changed = SimplifiedByConstantRange = true;
7509       }
7510     }
7511 
7512     if (!SimplifiedByConstantRange) {
7513       switch (Pred) {
7514       default:
7515         break;
7516       case ICmpInst::ICMP_EQ:
7517       case ICmpInst::ICMP_NE:
7518         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7519         if (!RA)
7520           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7521             if (const SCEVMulExpr *ME =
7522                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7523               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7524                   ME->getOperand(0)->isAllOnesValue()) {
7525                 RHS = AE->getOperand(1);
7526                 LHS = ME->getOperand(1);
7527                 Changed = true;
7528               }
7529         break;
7530 
7531 
7532         // The "Should have been caught earlier!" messages refer to the fact
7533         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7534         // should have fired on the corresponding cases, and canonicalized the
7535         // check to trivially_true or trivially_false.
7536 
7537       case ICmpInst::ICMP_UGE:
7538         assert(!RA.isMinValue() && "Should have been caught earlier!");
7539         Pred = ICmpInst::ICMP_UGT;
7540         RHS = getConstant(RA - 1);
7541         Changed = true;
7542         break;
7543       case ICmpInst::ICMP_ULE:
7544         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7545         Pred = ICmpInst::ICMP_ULT;
7546         RHS = getConstant(RA + 1);
7547         Changed = true;
7548         break;
7549       case ICmpInst::ICMP_SGE:
7550         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7551         Pred = ICmpInst::ICMP_SGT;
7552         RHS = getConstant(RA - 1);
7553         Changed = true;
7554         break;
7555       case ICmpInst::ICMP_SLE:
7556         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7557         Pred = ICmpInst::ICMP_SLT;
7558         RHS = getConstant(RA + 1);
7559         Changed = true;
7560         break;
7561       }
7562     }
7563   }
7564 
7565   // Check for obvious equality.
7566   if (HasSameValue(LHS, RHS)) {
7567     if (ICmpInst::isTrueWhenEqual(Pred))
7568       goto trivially_true;
7569     if (ICmpInst::isFalseWhenEqual(Pred))
7570       goto trivially_false;
7571   }
7572 
7573   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7574   // adding or subtracting 1 from one of the operands.
7575   switch (Pred) {
7576   case ICmpInst::ICMP_SLE:
7577     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7578       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7579                        SCEV::FlagNSW);
7580       Pred = ICmpInst::ICMP_SLT;
7581       Changed = true;
7582     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7583       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7584                        SCEV::FlagNSW);
7585       Pred = ICmpInst::ICMP_SLT;
7586       Changed = true;
7587     }
7588     break;
7589   case ICmpInst::ICMP_SGE:
7590     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7591       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7592                        SCEV::FlagNSW);
7593       Pred = ICmpInst::ICMP_SGT;
7594       Changed = true;
7595     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7596       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7597                        SCEV::FlagNSW);
7598       Pred = ICmpInst::ICMP_SGT;
7599       Changed = true;
7600     }
7601     break;
7602   case ICmpInst::ICMP_ULE:
7603     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7604       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7605                        SCEV::FlagNUW);
7606       Pred = ICmpInst::ICMP_ULT;
7607       Changed = true;
7608     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7609       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7610       Pred = ICmpInst::ICMP_ULT;
7611       Changed = true;
7612     }
7613     break;
7614   case ICmpInst::ICMP_UGE:
7615     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7616       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7617       Pred = ICmpInst::ICMP_UGT;
7618       Changed = true;
7619     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7620       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7621                        SCEV::FlagNUW);
7622       Pred = ICmpInst::ICMP_UGT;
7623       Changed = true;
7624     }
7625     break;
7626   default:
7627     break;
7628   }
7629 
7630   // TODO: More simplifications are possible here.
7631 
7632   // Recursively simplify until we either hit a recursion limit or nothing
7633   // changes.
7634   if (Changed)
7635     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7636 
7637   return Changed;
7638 
7639 trivially_true:
7640   // Return 0 == 0.
7641   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7642   Pred = ICmpInst::ICMP_EQ;
7643   return true;
7644 
7645 trivially_false:
7646   // Return 0 != 0.
7647   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7648   Pred = ICmpInst::ICMP_NE;
7649   return true;
7650 }
7651 
7652 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7653   return getSignedRange(S).getSignedMax().isNegative();
7654 }
7655 
7656 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7657   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7658 }
7659 
7660 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7661   return !getSignedRange(S).getSignedMin().isNegative();
7662 }
7663 
7664 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7665   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7666 }
7667 
7668 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7669   return isKnownNegative(S) || isKnownPositive(S);
7670 }
7671 
7672 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7673                                        const SCEV *LHS, const SCEV *RHS) {
7674   // Canonicalize the inputs first.
7675   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7676 
7677   // If LHS or RHS is an addrec, check to see if the condition is true in
7678   // every iteration of the loop.
7679   // If LHS and RHS are both addrec, both conditions must be true in
7680   // every iteration of the loop.
7681   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7682   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7683   bool LeftGuarded = false;
7684   bool RightGuarded = false;
7685   if (LAR) {
7686     const Loop *L = LAR->getLoop();
7687     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7688         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7689       if (!RAR) return true;
7690       LeftGuarded = true;
7691     }
7692   }
7693   if (RAR) {
7694     const Loop *L = RAR->getLoop();
7695     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7696         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7697       if (!LAR) return true;
7698       RightGuarded = true;
7699     }
7700   }
7701   if (LeftGuarded && RightGuarded)
7702     return true;
7703 
7704   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7705     return true;
7706 
7707   // Otherwise see what can be done with known constant ranges.
7708   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7709 }
7710 
7711 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7712                                            ICmpInst::Predicate Pred,
7713                                            bool &Increasing) {
7714   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7715 
7716 #ifndef NDEBUG
7717   // Verify an invariant: inverting the predicate should turn a monotonically
7718   // increasing change to a monotonically decreasing one, and vice versa.
7719   bool IncreasingSwapped;
7720   bool ResultSwapped = isMonotonicPredicateImpl(
7721       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7722 
7723   assert(Result == ResultSwapped && "should be able to analyze both!");
7724   if (ResultSwapped)
7725     assert(Increasing == !IncreasingSwapped &&
7726            "monotonicity should flip as we flip the predicate");
7727 #endif
7728 
7729   return Result;
7730 }
7731 
7732 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7733                                                ICmpInst::Predicate Pred,
7734                                                bool &Increasing) {
7735 
7736   // A zero step value for LHS means the induction variable is essentially a
7737   // loop invariant value. We don't really depend on the predicate actually
7738   // flipping from false to true (for increasing predicates, and the other way
7739   // around for decreasing predicates), all we care about is that *if* the
7740   // predicate changes then it only changes from false to true.
7741   //
7742   // A zero step value in itself is not very useful, but there may be places
7743   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7744   // as general as possible.
7745 
7746   switch (Pred) {
7747   default:
7748     return false; // Conservative answer
7749 
7750   case ICmpInst::ICMP_UGT:
7751   case ICmpInst::ICMP_UGE:
7752   case ICmpInst::ICMP_ULT:
7753   case ICmpInst::ICMP_ULE:
7754     if (!LHS->hasNoUnsignedWrap())
7755       return false;
7756 
7757     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7758     return true;
7759 
7760   case ICmpInst::ICMP_SGT:
7761   case ICmpInst::ICMP_SGE:
7762   case ICmpInst::ICMP_SLT:
7763   case ICmpInst::ICMP_SLE: {
7764     if (!LHS->hasNoSignedWrap())
7765       return false;
7766 
7767     const SCEV *Step = LHS->getStepRecurrence(*this);
7768 
7769     if (isKnownNonNegative(Step)) {
7770       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7771       return true;
7772     }
7773 
7774     if (isKnownNonPositive(Step)) {
7775       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7776       return true;
7777     }
7778 
7779     return false;
7780   }
7781 
7782   }
7783 
7784   llvm_unreachable("switch has default clause!");
7785 }
7786 
7787 bool ScalarEvolution::isLoopInvariantPredicate(
7788     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7789     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7790     const SCEV *&InvariantRHS) {
7791 
7792   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7793   if (!isLoopInvariant(RHS, L)) {
7794     if (!isLoopInvariant(LHS, L))
7795       return false;
7796 
7797     std::swap(LHS, RHS);
7798     Pred = ICmpInst::getSwappedPredicate(Pred);
7799   }
7800 
7801   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7802   if (!ArLHS || ArLHS->getLoop() != L)
7803     return false;
7804 
7805   bool Increasing;
7806   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7807     return false;
7808 
7809   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7810   // true as the loop iterates, and the backedge is control dependent on
7811   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7812   //
7813   //   * if the predicate was false in the first iteration then the predicate
7814   //     is never evaluated again, since the loop exits without taking the
7815   //     backedge.
7816   //   * if the predicate was true in the first iteration then it will
7817   //     continue to be true for all future iterations since it is
7818   //     monotonically increasing.
7819   //
7820   // For both the above possibilities, we can replace the loop varying
7821   // predicate with its value on the first iteration of the loop (which is
7822   // loop invariant).
7823   //
7824   // A similar reasoning applies for a monotonically decreasing predicate, by
7825   // replacing true with false and false with true in the above two bullets.
7826 
7827   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7828 
7829   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7830     return false;
7831 
7832   InvariantPred = Pred;
7833   InvariantLHS = ArLHS->getStart();
7834   InvariantRHS = RHS;
7835   return true;
7836 }
7837 
7838 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7839     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7840   if (HasSameValue(LHS, RHS))
7841     return ICmpInst::isTrueWhenEqual(Pred);
7842 
7843   // This code is split out from isKnownPredicate because it is called from
7844   // within isLoopEntryGuardedByCond.
7845 
7846   auto CheckRanges =
7847       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7848     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7849         .contains(RangeLHS);
7850   };
7851 
7852   // The check at the top of the function catches the case where the values are
7853   // known to be equal.
7854   if (Pred == CmpInst::ICMP_EQ)
7855     return false;
7856 
7857   if (Pred == CmpInst::ICMP_NE)
7858     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7859            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7860            isKnownNonZero(getMinusSCEV(LHS, RHS));
7861 
7862   if (CmpInst::isSigned(Pred))
7863     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7864 
7865   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7866 }
7867 
7868 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7869                                                     const SCEV *LHS,
7870                                                     const SCEV *RHS) {
7871 
7872   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7873   // Return Y via OutY.
7874   auto MatchBinaryAddToConst =
7875       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7876              SCEV::NoWrapFlags ExpectedFlags) {
7877     const SCEV *NonConstOp, *ConstOp;
7878     SCEV::NoWrapFlags FlagsPresent;
7879 
7880     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7881         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7882       return false;
7883 
7884     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7885     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7886   };
7887 
7888   APInt C;
7889 
7890   switch (Pred) {
7891   default:
7892     break;
7893 
7894   case ICmpInst::ICMP_SGE:
7895     std::swap(LHS, RHS);
7896   case ICmpInst::ICMP_SLE:
7897     // X s<= (X + C)<nsw> if C >= 0
7898     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7899       return true;
7900 
7901     // (X + C)<nsw> s<= X if C <= 0
7902     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7903         !C.isStrictlyPositive())
7904       return true;
7905     break;
7906 
7907   case ICmpInst::ICMP_SGT:
7908     std::swap(LHS, RHS);
7909   case ICmpInst::ICMP_SLT:
7910     // X s< (X + C)<nsw> if C > 0
7911     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7912         C.isStrictlyPositive())
7913       return true;
7914 
7915     // (X + C)<nsw> s< X if C < 0
7916     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7917       return true;
7918     break;
7919   }
7920 
7921   return false;
7922 }
7923 
7924 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7925                                                    const SCEV *LHS,
7926                                                    const SCEV *RHS) {
7927   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7928     return false;
7929 
7930   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7931   // the stack can result in exponential time complexity.
7932   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7933 
7934   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7935   //
7936   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7937   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7938   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7939   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7940   // use isKnownPredicate later if needed.
7941   return isKnownNonNegative(RHS) &&
7942          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7943          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7944 }
7945 
7946 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7947                                         ICmpInst::Predicate Pred,
7948                                         const SCEV *LHS, const SCEV *RHS) {
7949   // No need to even try if we know the module has no guards.
7950   if (!HasGuards)
7951     return false;
7952 
7953   return any_of(*BB, [&](Instruction &I) {
7954     using namespace llvm::PatternMatch;
7955 
7956     Value *Condition;
7957     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7958                          m_Value(Condition))) &&
7959            isImpliedCond(Pred, LHS, RHS, Condition, false);
7960   });
7961 }
7962 
7963 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7964 /// protected by a conditional between LHS and RHS.  This is used to
7965 /// to eliminate casts.
7966 bool
7967 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7968                                              ICmpInst::Predicate Pred,
7969                                              const SCEV *LHS, const SCEV *RHS) {
7970   // Interpret a null as meaning no loop, where there is obviously no guard
7971   // (interprocedural conditions notwithstanding).
7972   if (!L) return true;
7973 
7974   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7975     return true;
7976 
7977   BasicBlock *Latch = L->getLoopLatch();
7978   if (!Latch)
7979     return false;
7980 
7981   BranchInst *LoopContinuePredicate =
7982     dyn_cast<BranchInst>(Latch->getTerminator());
7983   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7984       isImpliedCond(Pred, LHS, RHS,
7985                     LoopContinuePredicate->getCondition(),
7986                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7987     return true;
7988 
7989   // We don't want more than one activation of the following loops on the stack
7990   // -- that can lead to O(n!) time complexity.
7991   if (WalkingBEDominatingConds)
7992     return false;
7993 
7994   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7995 
7996   // See if we can exploit a trip count to prove the predicate.
7997   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7998   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7999   if (LatchBECount != getCouldNotCompute()) {
8000     // We know that Latch branches back to the loop header exactly
8001     // LatchBECount times.  This means the backdege condition at Latch is
8002     // equivalent to  "{0,+,1} u< LatchBECount".
8003     Type *Ty = LatchBECount->getType();
8004     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8005     const SCEV *LoopCounter =
8006       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8007     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8008                       LatchBECount))
8009       return true;
8010   }
8011 
8012   // Check conditions due to any @llvm.assume intrinsics.
8013   for (auto &AssumeVH : AC.assumptions()) {
8014     if (!AssumeVH)
8015       continue;
8016     auto *CI = cast<CallInst>(AssumeVH);
8017     if (!DT.dominates(CI, Latch->getTerminator()))
8018       continue;
8019 
8020     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8021       return true;
8022   }
8023 
8024   // If the loop is not reachable from the entry block, we risk running into an
8025   // infinite loop as we walk up into the dom tree.  These loops do not matter
8026   // anyway, so we just return a conservative answer when we see them.
8027   if (!DT.isReachableFromEntry(L->getHeader()))
8028     return false;
8029 
8030   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8031     return true;
8032 
8033   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8034        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8035 
8036     assert(DTN && "should reach the loop header before reaching the root!");
8037 
8038     BasicBlock *BB = DTN->getBlock();
8039     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8040       return true;
8041 
8042     BasicBlock *PBB = BB->getSinglePredecessor();
8043     if (!PBB)
8044       continue;
8045 
8046     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8047     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8048       continue;
8049 
8050     Value *Condition = ContinuePredicate->getCondition();
8051 
8052     // If we have an edge `E` within the loop body that dominates the only
8053     // latch, the condition guarding `E` also guards the backedge.  This
8054     // reasoning works only for loops with a single latch.
8055 
8056     BasicBlockEdge DominatingEdge(PBB, BB);
8057     if (DominatingEdge.isSingleEdge()) {
8058       // We're constructively (and conservatively) enumerating edges within the
8059       // loop body that dominate the latch.  The dominator tree better agree
8060       // with us on this:
8061       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8062 
8063       if (isImpliedCond(Pred, LHS, RHS, Condition,
8064                         BB != ContinuePredicate->getSuccessor(0)))
8065         return true;
8066     }
8067   }
8068 
8069   return false;
8070 }
8071 
8072 bool
8073 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8074                                           ICmpInst::Predicate Pred,
8075                                           const SCEV *LHS, const SCEV *RHS) {
8076   // Interpret a null as meaning no loop, where there is obviously no guard
8077   // (interprocedural conditions notwithstanding).
8078   if (!L) return false;
8079 
8080   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8081     return true;
8082 
8083   // Starting at the loop predecessor, climb up the predecessor chain, as long
8084   // as there are predecessors that can be found that have unique successors
8085   // leading to the original header.
8086   for (std::pair<BasicBlock *, BasicBlock *>
8087          Pair(L->getLoopPredecessor(), L->getHeader());
8088        Pair.first;
8089        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8090 
8091     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8092       return true;
8093 
8094     BranchInst *LoopEntryPredicate =
8095       dyn_cast<BranchInst>(Pair.first->getTerminator());
8096     if (!LoopEntryPredicate ||
8097         LoopEntryPredicate->isUnconditional())
8098       continue;
8099 
8100     if (isImpliedCond(Pred, LHS, RHS,
8101                       LoopEntryPredicate->getCondition(),
8102                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8103       return true;
8104   }
8105 
8106   // Check conditions due to any @llvm.assume intrinsics.
8107   for (auto &AssumeVH : AC.assumptions()) {
8108     if (!AssumeVH)
8109       continue;
8110     auto *CI = cast<CallInst>(AssumeVH);
8111     if (!DT.dominates(CI, L->getHeader()))
8112       continue;
8113 
8114     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8115       return true;
8116   }
8117 
8118   return false;
8119 }
8120 
8121 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8122                                     const SCEV *LHS, const SCEV *RHS,
8123                                     Value *FoundCondValue,
8124                                     bool Inverse) {
8125   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8126     return false;
8127 
8128   auto ClearOnExit =
8129       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8130 
8131   // Recursively handle And and Or conditions.
8132   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8133     if (BO->getOpcode() == Instruction::And) {
8134       if (!Inverse)
8135         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8136                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8137     } else if (BO->getOpcode() == Instruction::Or) {
8138       if (Inverse)
8139         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8140                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8141     }
8142   }
8143 
8144   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8145   if (!ICI) return false;
8146 
8147   // Now that we found a conditional branch that dominates the loop or controls
8148   // the loop latch. Check to see if it is the comparison we are looking for.
8149   ICmpInst::Predicate FoundPred;
8150   if (Inverse)
8151     FoundPred = ICI->getInversePredicate();
8152   else
8153     FoundPred = ICI->getPredicate();
8154 
8155   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8156   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8157 
8158   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8159 }
8160 
8161 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8162                                     const SCEV *RHS,
8163                                     ICmpInst::Predicate FoundPred,
8164                                     const SCEV *FoundLHS,
8165                                     const SCEV *FoundRHS) {
8166   // Balance the types.
8167   if (getTypeSizeInBits(LHS->getType()) <
8168       getTypeSizeInBits(FoundLHS->getType())) {
8169     if (CmpInst::isSigned(Pred)) {
8170       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8171       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8172     } else {
8173       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8174       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8175     }
8176   } else if (getTypeSizeInBits(LHS->getType()) >
8177       getTypeSizeInBits(FoundLHS->getType())) {
8178     if (CmpInst::isSigned(FoundPred)) {
8179       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8180       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8181     } else {
8182       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8183       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8184     }
8185   }
8186 
8187   // Canonicalize the query to match the way instcombine will have
8188   // canonicalized the comparison.
8189   if (SimplifyICmpOperands(Pred, LHS, RHS))
8190     if (LHS == RHS)
8191       return CmpInst::isTrueWhenEqual(Pred);
8192   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8193     if (FoundLHS == FoundRHS)
8194       return CmpInst::isFalseWhenEqual(FoundPred);
8195 
8196   // Check to see if we can make the LHS or RHS match.
8197   if (LHS == FoundRHS || RHS == FoundLHS) {
8198     if (isa<SCEVConstant>(RHS)) {
8199       std::swap(FoundLHS, FoundRHS);
8200       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8201     } else {
8202       std::swap(LHS, RHS);
8203       Pred = ICmpInst::getSwappedPredicate(Pred);
8204     }
8205   }
8206 
8207   // Check whether the found predicate is the same as the desired predicate.
8208   if (FoundPred == Pred)
8209     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8210 
8211   // Check whether swapping the found predicate makes it the same as the
8212   // desired predicate.
8213   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8214     if (isa<SCEVConstant>(RHS))
8215       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8216     else
8217       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8218                                    RHS, LHS, FoundLHS, FoundRHS);
8219   }
8220 
8221   // Unsigned comparison is the same as signed comparison when both the operands
8222   // are non-negative.
8223   if (CmpInst::isUnsigned(FoundPred) &&
8224       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8225       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8226     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8227 
8228   // Check if we can make progress by sharpening ranges.
8229   if (FoundPred == ICmpInst::ICMP_NE &&
8230       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8231 
8232     const SCEVConstant *C = nullptr;
8233     const SCEV *V = nullptr;
8234 
8235     if (isa<SCEVConstant>(FoundLHS)) {
8236       C = cast<SCEVConstant>(FoundLHS);
8237       V = FoundRHS;
8238     } else {
8239       C = cast<SCEVConstant>(FoundRHS);
8240       V = FoundLHS;
8241     }
8242 
8243     // The guarding predicate tells us that C != V. If the known range
8244     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8245     // range we consider has to correspond to same signedness as the
8246     // predicate we're interested in folding.
8247 
8248     APInt Min = ICmpInst::isSigned(Pred) ?
8249         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8250 
8251     if (Min == C->getAPInt()) {
8252       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8253       // This is true even if (Min + 1) wraps around -- in case of
8254       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8255 
8256       APInt SharperMin = Min + 1;
8257 
8258       switch (Pred) {
8259         case ICmpInst::ICMP_SGE:
8260         case ICmpInst::ICMP_UGE:
8261           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8262           // RHS, we're done.
8263           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8264                                     getConstant(SharperMin)))
8265             return true;
8266 
8267         case ICmpInst::ICMP_SGT:
8268         case ICmpInst::ICMP_UGT:
8269           // We know from the range information that (V `Pred` Min ||
8270           // V == Min).  We know from the guarding condition that !(V
8271           // == Min).  This gives us
8272           //
8273           //       V `Pred` Min || V == Min && !(V == Min)
8274           //   =>  V `Pred` Min
8275           //
8276           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8277 
8278           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8279             return true;
8280 
8281         default:
8282           // No change
8283           break;
8284       }
8285     }
8286   }
8287 
8288   // Check whether the actual condition is beyond sufficient.
8289   if (FoundPred == ICmpInst::ICMP_EQ)
8290     if (ICmpInst::isTrueWhenEqual(Pred))
8291       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8292         return true;
8293   if (Pred == ICmpInst::ICMP_NE)
8294     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8295       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8296         return true;
8297 
8298   // Otherwise assume the worst.
8299   return false;
8300 }
8301 
8302 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8303                                      const SCEV *&L, const SCEV *&R,
8304                                      SCEV::NoWrapFlags &Flags) {
8305   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8306   if (!AE || AE->getNumOperands() != 2)
8307     return false;
8308 
8309   L = AE->getOperand(0);
8310   R = AE->getOperand(1);
8311   Flags = AE->getNoWrapFlags();
8312   return true;
8313 }
8314 
8315 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8316                                                            const SCEV *Less) {
8317   // We avoid subtracting expressions here because this function is usually
8318   // fairly deep in the call stack (i.e. is called many times).
8319 
8320   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8321     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8322     const auto *MAR = cast<SCEVAddRecExpr>(More);
8323 
8324     if (LAR->getLoop() != MAR->getLoop())
8325       return None;
8326 
8327     // We look at affine expressions only; not for correctness but to keep
8328     // getStepRecurrence cheap.
8329     if (!LAR->isAffine() || !MAR->isAffine())
8330       return None;
8331 
8332     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8333       return None;
8334 
8335     Less = LAR->getStart();
8336     More = MAR->getStart();
8337 
8338     // fall through
8339   }
8340 
8341   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8342     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8343     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8344     return M - L;
8345   }
8346 
8347   const SCEV *L, *R;
8348   SCEV::NoWrapFlags Flags;
8349   if (splitBinaryAdd(Less, L, R, Flags))
8350     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8351       if (R == More)
8352         return -(LC->getAPInt());
8353 
8354   if (splitBinaryAdd(More, L, R, Flags))
8355     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8356       if (R == Less)
8357         return LC->getAPInt();
8358 
8359   return None;
8360 }
8361 
8362 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8363     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8364     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8365   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8366     return false;
8367 
8368   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8369   if (!AddRecLHS)
8370     return false;
8371 
8372   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8373   if (!AddRecFoundLHS)
8374     return false;
8375 
8376   // We'd like to let SCEV reason about control dependencies, so we constrain
8377   // both the inequalities to be about add recurrences on the same loop.  This
8378   // way we can use isLoopEntryGuardedByCond later.
8379 
8380   const Loop *L = AddRecFoundLHS->getLoop();
8381   if (L != AddRecLHS->getLoop())
8382     return false;
8383 
8384   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8385   //
8386   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8387   //                                                                  ... (2)
8388   //
8389   // Informal proof for (2), assuming (1) [*]:
8390   //
8391   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8392   //
8393   // Then
8394   //
8395   //       FoundLHS s< FoundRHS s< INT_MIN - C
8396   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8397   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8398   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8399   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8400   // <=>  FoundLHS + C s< FoundRHS + C
8401   //
8402   // [*]: (1) can be proved by ruling out overflow.
8403   //
8404   // [**]: This can be proved by analyzing all the four possibilities:
8405   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8406   //    (A s>= 0, B s>= 0).
8407   //
8408   // Note:
8409   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8410   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8411   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8412   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8413   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8414   // C)".
8415 
8416   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8417   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8418   if (!LDiff || !RDiff || *LDiff != *RDiff)
8419     return false;
8420 
8421   if (LDiff->isMinValue())
8422     return true;
8423 
8424   APInt FoundRHSLimit;
8425 
8426   if (Pred == CmpInst::ICMP_ULT) {
8427     FoundRHSLimit = -(*RDiff);
8428   } else {
8429     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8430     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8431   }
8432 
8433   // Try to prove (1) or (2), as needed.
8434   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8435                                   getConstant(FoundRHSLimit));
8436 }
8437 
8438 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8439                                             const SCEV *LHS, const SCEV *RHS,
8440                                             const SCEV *FoundLHS,
8441                                             const SCEV *FoundRHS) {
8442   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8443     return true;
8444 
8445   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8446     return true;
8447 
8448   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8449                                      FoundLHS, FoundRHS) ||
8450          // ~x < ~y --> x > y
8451          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8452                                      getNotSCEV(FoundRHS),
8453                                      getNotSCEV(FoundLHS));
8454 }
8455 
8456 
8457 /// If Expr computes ~A, return A else return nullptr
8458 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8459   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8460   if (!Add || Add->getNumOperands() != 2 ||
8461       !Add->getOperand(0)->isAllOnesValue())
8462     return nullptr;
8463 
8464   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8465   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8466       !AddRHS->getOperand(0)->isAllOnesValue())
8467     return nullptr;
8468 
8469   return AddRHS->getOperand(1);
8470 }
8471 
8472 
8473 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8474 template<typename MaxExprType>
8475 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8476                               const SCEV *Candidate) {
8477   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8478   if (!MaxExpr) return false;
8479 
8480   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8481 }
8482 
8483 
8484 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8485 template<typename MaxExprType>
8486 static bool IsMinConsistingOf(ScalarEvolution &SE,
8487                               const SCEV *MaybeMinExpr,
8488                               const SCEV *Candidate) {
8489   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8490   if (!MaybeMaxExpr)
8491     return false;
8492 
8493   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8494 }
8495 
8496 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8497                                            ICmpInst::Predicate Pred,
8498                                            const SCEV *LHS, const SCEV *RHS) {
8499 
8500   // If both sides are affine addrecs for the same loop, with equal
8501   // steps, and we know the recurrences don't wrap, then we only
8502   // need to check the predicate on the starting values.
8503 
8504   if (!ICmpInst::isRelational(Pred))
8505     return false;
8506 
8507   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8508   if (!LAR)
8509     return false;
8510   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8511   if (!RAR)
8512     return false;
8513   if (LAR->getLoop() != RAR->getLoop())
8514     return false;
8515   if (!LAR->isAffine() || !RAR->isAffine())
8516     return false;
8517 
8518   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8519     return false;
8520 
8521   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8522                          SCEV::FlagNSW : SCEV::FlagNUW;
8523   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8524     return false;
8525 
8526   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8527 }
8528 
8529 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8530 /// expression?
8531 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8532                                         ICmpInst::Predicate Pred,
8533                                         const SCEV *LHS, const SCEV *RHS) {
8534   switch (Pred) {
8535   default:
8536     return false;
8537 
8538   case ICmpInst::ICMP_SGE:
8539     std::swap(LHS, RHS);
8540     LLVM_FALLTHROUGH;
8541   case ICmpInst::ICMP_SLE:
8542     return
8543       // min(A, ...) <= A
8544       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8545       // A <= max(A, ...)
8546       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8547 
8548   case ICmpInst::ICMP_UGE:
8549     std::swap(LHS, RHS);
8550     LLVM_FALLTHROUGH;
8551   case ICmpInst::ICMP_ULE:
8552     return
8553       // min(A, ...) <= A
8554       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8555       // A <= max(A, ...)
8556       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8557   }
8558 
8559   llvm_unreachable("covered switch fell through?!");
8560 }
8561 
8562 bool
8563 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8564                                              const SCEV *LHS, const SCEV *RHS,
8565                                              const SCEV *FoundLHS,
8566                                              const SCEV *FoundRHS) {
8567   auto IsKnownPredicateFull =
8568       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8569     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8570            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8571            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8572            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8573   };
8574 
8575   switch (Pred) {
8576   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8577   case ICmpInst::ICMP_EQ:
8578   case ICmpInst::ICMP_NE:
8579     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8580       return true;
8581     break;
8582   case ICmpInst::ICMP_SLT:
8583   case ICmpInst::ICMP_SLE:
8584     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8585         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8586       return true;
8587     break;
8588   case ICmpInst::ICMP_SGT:
8589   case ICmpInst::ICMP_SGE:
8590     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8591         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8592       return true;
8593     break;
8594   case ICmpInst::ICMP_ULT:
8595   case ICmpInst::ICMP_ULE:
8596     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8597         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8598       return true;
8599     break;
8600   case ICmpInst::ICMP_UGT:
8601   case ICmpInst::ICMP_UGE:
8602     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8603         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8604       return true;
8605     break;
8606   }
8607 
8608   return false;
8609 }
8610 
8611 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8612                                                      const SCEV *LHS,
8613                                                      const SCEV *RHS,
8614                                                      const SCEV *FoundLHS,
8615                                                      const SCEV *FoundRHS) {
8616   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8617     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8618     // reduce the compile time impact of this optimization.
8619     return false;
8620 
8621   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8622   if (!Addend)
8623     return false;
8624 
8625   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8626 
8627   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8628   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8629   ConstantRange FoundLHSRange =
8630       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8631 
8632   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8633   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8634 
8635   // We can also compute the range of values for `LHS` that satisfy the
8636   // consequent, "`LHS` `Pred` `RHS`":
8637   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8638   ConstantRange SatisfyingLHSRange =
8639       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8640 
8641   // The antecedent implies the consequent if every value of `LHS` that
8642   // satisfies the antecedent also satisfies the consequent.
8643   return SatisfyingLHSRange.contains(LHSRange);
8644 }
8645 
8646 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8647                                          bool IsSigned, bool NoWrap) {
8648   assert(isKnownPositive(Stride) && "Positive stride expected!");
8649 
8650   if (NoWrap) return false;
8651 
8652   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8653   const SCEV *One = getOne(Stride->getType());
8654 
8655   if (IsSigned) {
8656     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8657     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8658     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8659                                 .getSignedMax();
8660 
8661     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8662     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8663   }
8664 
8665   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8666   APInt MaxValue = APInt::getMaxValue(BitWidth);
8667   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8668                               .getUnsignedMax();
8669 
8670   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8671   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8672 }
8673 
8674 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8675                                          bool IsSigned, bool NoWrap) {
8676   if (NoWrap) return false;
8677 
8678   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8679   const SCEV *One = getOne(Stride->getType());
8680 
8681   if (IsSigned) {
8682     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8683     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8684     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8685                                .getSignedMax();
8686 
8687     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8688     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8689   }
8690 
8691   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8692   APInt MinValue = APInt::getMinValue(BitWidth);
8693   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8694                             .getUnsignedMax();
8695 
8696   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8697   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8698 }
8699 
8700 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8701                                             bool Equality) {
8702   const SCEV *One = getOne(Step->getType());
8703   Delta = Equality ? getAddExpr(Delta, Step)
8704                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8705   return getUDivExpr(Delta, Step);
8706 }
8707 
8708 ScalarEvolution::ExitLimit
8709 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8710                                   const Loop *L, bool IsSigned,
8711                                   bool ControlsExit, bool AllowPredicates) {
8712   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8713   // We handle only IV < Invariant
8714   if (!isLoopInvariant(RHS, L))
8715     return getCouldNotCompute();
8716 
8717   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8718   bool PredicatedIV = false;
8719 
8720   if (!IV && AllowPredicates) {
8721     // Try to make this an AddRec using runtime tests, in the first X
8722     // iterations of this loop, where X is the SCEV expression found by the
8723     // algorithm below.
8724     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8725     PredicatedIV = true;
8726   }
8727 
8728   // Avoid weird loops
8729   if (!IV || IV->getLoop() != L || !IV->isAffine())
8730     return getCouldNotCompute();
8731 
8732   bool NoWrap = ControlsExit &&
8733                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8734 
8735   const SCEV *Stride = IV->getStepRecurrence(*this);
8736 
8737   bool PositiveStride = isKnownPositive(Stride);
8738 
8739   // Avoid negative or zero stride values.
8740   if (!PositiveStride) {
8741     // We can compute the correct backedge taken count for loops with unknown
8742     // strides if we can prove that the loop is not an infinite loop with side
8743     // effects. Here's the loop structure we are trying to handle -
8744     //
8745     // i = start
8746     // do {
8747     //   A[i] = i;
8748     //   i += s;
8749     // } while (i < end);
8750     //
8751     // The backedge taken count for such loops is evaluated as -
8752     // (max(end, start + stride) - start - 1) /u stride
8753     //
8754     // The additional preconditions that we need to check to prove correctness
8755     // of the above formula is as follows -
8756     //
8757     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8758     //    NoWrap flag).
8759     // b) loop is single exit with no side effects.
8760     //
8761     //
8762     // Precondition a) implies that if the stride is negative, this is a single
8763     // trip loop. The backedge taken count formula reduces to zero in this case.
8764     //
8765     // Precondition b) implies that the unknown stride cannot be zero otherwise
8766     // we have UB.
8767     //
8768     // The positive stride case is the same as isKnownPositive(Stride) returning
8769     // true (original behavior of the function).
8770     //
8771     // We want to make sure that the stride is truly unknown as there are edge
8772     // cases where ScalarEvolution propagates no wrap flags to the
8773     // post-increment/decrement IV even though the increment/decrement operation
8774     // itself is wrapping. The computed backedge taken count may be wrong in
8775     // such cases. This is prevented by checking that the stride is not known to
8776     // be either positive or non-positive. For example, no wrap flags are
8777     // propagated to the post-increment IV of this loop with a trip count of 2 -
8778     //
8779     // unsigned char i;
8780     // for(i=127; i<128; i+=129)
8781     //   A[i] = i;
8782     //
8783     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8784         !loopHasNoSideEffects(L))
8785       return getCouldNotCompute();
8786 
8787   } else if (!Stride->isOne() &&
8788              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8789     // Avoid proven overflow cases: this will ensure that the backedge taken
8790     // count will not generate any unsigned overflow. Relaxed no-overflow
8791     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8792     // undefined behaviors like the case of C language.
8793     return getCouldNotCompute();
8794 
8795   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8796                                       : ICmpInst::ICMP_ULT;
8797   const SCEV *Start = IV->getStart();
8798   const SCEV *End = RHS;
8799   // If the backedge is taken at least once, then it will be taken
8800   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8801   // is the LHS value of the less-than comparison the first time it is evaluated
8802   // and End is the RHS.
8803   const SCEV *BECountIfBackedgeTaken =
8804     computeBECount(getMinusSCEV(End, Start), Stride, false);
8805   // If the loop entry is guarded by the result of the backedge test of the
8806   // first loop iteration, then we know the backedge will be taken at least
8807   // once and so the backedge taken count is as above. If not then we use the
8808   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8809   // as if the backedge is taken at least once max(End,Start) is End and so the
8810   // result is as above, and if not max(End,Start) is Start so we get a backedge
8811   // count of zero.
8812   const SCEV *BECount;
8813   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8814     BECount = BECountIfBackedgeTaken;
8815   else {
8816     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
8817     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8818   }
8819 
8820   const SCEV *MaxBECount;
8821   bool MaxOrZero = false;
8822   if (isa<SCEVConstant>(BECount))
8823     MaxBECount = BECount;
8824   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
8825     // If we know exactly how many times the backedge will be taken if it's
8826     // taken at least once, then the backedge count will either be that or
8827     // zero.
8828     MaxBECount = BECountIfBackedgeTaken;
8829     MaxOrZero = true;
8830   } else {
8831     // Calculate the maximum backedge count based on the range of values
8832     // permitted by Start, End, and Stride.
8833     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8834                               : getUnsignedRange(Start).getUnsignedMin();
8835 
8836     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8837 
8838     APInt StrideForMaxBECount;
8839 
8840     if (PositiveStride)
8841       StrideForMaxBECount =
8842         IsSigned ? getSignedRange(Stride).getSignedMin()
8843                  : getUnsignedRange(Stride).getUnsignedMin();
8844     else
8845       // Using a stride of 1 is safe when computing max backedge taken count for
8846       // a loop with unknown stride.
8847       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8848 
8849     APInt Limit =
8850       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8851                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8852 
8853     // Although End can be a MAX expression we estimate MaxEnd considering only
8854     // the case End = RHS. This is safe because in the other case (End - Start)
8855     // is zero, leading to a zero maximum backedge taken count.
8856     APInt MaxEnd =
8857       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8858                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8859 
8860     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8861                                 getConstant(StrideForMaxBECount), false);
8862   }
8863 
8864   if (isa<SCEVCouldNotCompute>(MaxBECount))
8865     MaxBECount = BECount;
8866 
8867   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
8868 }
8869 
8870 ScalarEvolution::ExitLimit
8871 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8872                                      const Loop *L, bool IsSigned,
8873                                      bool ControlsExit, bool AllowPredicates) {
8874   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8875   // We handle only IV > Invariant
8876   if (!isLoopInvariant(RHS, L))
8877     return getCouldNotCompute();
8878 
8879   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8880   if (!IV && AllowPredicates)
8881     // Try to make this an AddRec using runtime tests, in the first X
8882     // iterations of this loop, where X is the SCEV expression found by the
8883     // algorithm below.
8884     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8885 
8886   // Avoid weird loops
8887   if (!IV || IV->getLoop() != L || !IV->isAffine())
8888     return getCouldNotCompute();
8889 
8890   bool NoWrap = ControlsExit &&
8891                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8892 
8893   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8894 
8895   // Avoid negative or zero stride values
8896   if (!isKnownPositive(Stride))
8897     return getCouldNotCompute();
8898 
8899   // Avoid proven overflow cases: this will ensure that the backedge taken count
8900   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8901   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8902   // behaviors like the case of C language.
8903   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8904     return getCouldNotCompute();
8905 
8906   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8907                                       : ICmpInst::ICMP_UGT;
8908 
8909   const SCEV *Start = IV->getStart();
8910   const SCEV *End = RHS;
8911   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8912     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
8913 
8914   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8915 
8916   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8917                             : getUnsignedRange(Start).getUnsignedMax();
8918 
8919   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8920                              : getUnsignedRange(Stride).getUnsignedMin();
8921 
8922   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8923   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8924                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8925 
8926   // Although End can be a MIN expression we estimate MinEnd considering only
8927   // the case End = RHS. This is safe because in the other case (Start - End)
8928   // is zero, leading to a zero maximum backedge taken count.
8929   APInt MinEnd =
8930     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8931              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8932 
8933 
8934   const SCEV *MaxBECount = getCouldNotCompute();
8935   if (isa<SCEVConstant>(BECount))
8936     MaxBECount = BECount;
8937   else
8938     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8939                                 getConstant(MinStride), false);
8940 
8941   if (isa<SCEVCouldNotCompute>(MaxBECount))
8942     MaxBECount = BECount;
8943 
8944   return ExitLimit(BECount, MaxBECount, false, Predicates);
8945 }
8946 
8947 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
8948                                                     ScalarEvolution &SE) const {
8949   if (Range.isFullSet())  // Infinite loop.
8950     return SE.getCouldNotCompute();
8951 
8952   // If the start is a non-zero constant, shift the range to simplify things.
8953   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8954     if (!SC->getValue()->isZero()) {
8955       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8956       Operands[0] = SE.getZero(SC->getType());
8957       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8958                                              getNoWrapFlags(FlagNW));
8959       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8960         return ShiftedAddRec->getNumIterationsInRange(
8961             Range.subtract(SC->getAPInt()), SE);
8962       // This is strange and shouldn't happen.
8963       return SE.getCouldNotCompute();
8964     }
8965 
8966   // The only time we can solve this is when we have all constant indices.
8967   // Otherwise, we cannot determine the overflow conditions.
8968   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8969     return SE.getCouldNotCompute();
8970 
8971   // Okay at this point we know that all elements of the chrec are constants and
8972   // that the start element is zero.
8973 
8974   // First check to see if the range contains zero.  If not, the first
8975   // iteration exits.
8976   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8977   if (!Range.contains(APInt(BitWidth, 0)))
8978     return SE.getZero(getType());
8979 
8980   if (isAffine()) {
8981     // If this is an affine expression then we have this situation:
8982     //   Solve {0,+,A} in Range  ===  Ax in Range
8983 
8984     // We know that zero is in the range.  If A is positive then we know that
8985     // the upper value of the range must be the first possible exit value.
8986     // If A is negative then the lower of the range is the last possible loop
8987     // value.  Also note that we already checked for a full range.
8988     APInt One(BitWidth,1);
8989     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8990     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8991 
8992     // The exit value should be (End+A)/A.
8993     APInt ExitVal = (End + A).udiv(A);
8994     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8995 
8996     // Evaluate at the exit value.  If we really did fall out of the valid
8997     // range, then we computed our trip count, otherwise wrap around or other
8998     // things must have happened.
8999     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9000     if (Range.contains(Val->getValue()))
9001       return SE.getCouldNotCompute();  // Something strange happened
9002 
9003     // Ensure that the previous value is in the range.  This is a sanity check.
9004     assert(Range.contains(
9005            EvaluateConstantChrecAtConstant(this,
9006            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
9007            "Linear scev computation is off in a bad way!");
9008     return SE.getConstant(ExitValue);
9009   } else if (isQuadratic()) {
9010     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9011     // quadratic equation to solve it.  To do this, we must frame our problem in
9012     // terms of figuring out when zero is crossed, instead of when
9013     // Range.getUpper() is crossed.
9014     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9015     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9016     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9017 
9018     // Next, solve the constructed addrec
9019     if (auto Roots =
9020             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9021       const SCEVConstant *R1 = Roots->first;
9022       const SCEVConstant *R2 = Roots->second;
9023       // Pick the smallest positive root value.
9024       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9025               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9026         if (!CB->getZExtValue())
9027           std::swap(R1, R2); // R1 is the minimum root now.
9028 
9029         // Make sure the root is not off by one.  The returned iteration should
9030         // not be in the range, but the previous one should be.  When solving
9031         // for "X*X < 5", for example, we should not return a root of 2.
9032         ConstantInt *R1Val =
9033             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9034         if (Range.contains(R1Val->getValue())) {
9035           // The next iteration must be out of the range...
9036           ConstantInt *NextVal =
9037               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9038 
9039           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9040           if (!Range.contains(R1Val->getValue()))
9041             return SE.getConstant(NextVal);
9042           return SE.getCouldNotCompute(); // Something strange happened
9043         }
9044 
9045         // If R1 was not in the range, then it is a good return value.  Make
9046         // sure that R1-1 WAS in the range though, just in case.
9047         ConstantInt *NextVal =
9048             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9049         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9050         if (Range.contains(R1Val->getValue()))
9051           return R1;
9052         return SE.getCouldNotCompute(); // Something strange happened
9053       }
9054     }
9055   }
9056 
9057   return SE.getCouldNotCompute();
9058 }
9059 
9060 // Return true when S contains at least an undef value.
9061 static inline bool containsUndefs(const SCEV *S) {
9062   return SCEVExprContains(S, [](const SCEV *S) {
9063     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9064       return isa<UndefValue>(SU->getValue());
9065     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9066       return isa<UndefValue>(SC->getValue());
9067     return false;
9068   });
9069 }
9070 
9071 namespace {
9072 // Collect all steps of SCEV expressions.
9073 struct SCEVCollectStrides {
9074   ScalarEvolution &SE;
9075   SmallVectorImpl<const SCEV *> &Strides;
9076 
9077   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9078       : SE(SE), Strides(S) {}
9079 
9080   bool follow(const SCEV *S) {
9081     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9082       Strides.push_back(AR->getStepRecurrence(SE));
9083     return true;
9084   }
9085   bool isDone() const { return false; }
9086 };
9087 
9088 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9089 struct SCEVCollectTerms {
9090   SmallVectorImpl<const SCEV *> &Terms;
9091 
9092   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9093       : Terms(T) {}
9094 
9095   bool follow(const SCEV *S) {
9096     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9097         isa<SCEVSignExtendExpr>(S)) {
9098       if (!containsUndefs(S))
9099         Terms.push_back(S);
9100 
9101       // Stop recursion: once we collected a term, do not walk its operands.
9102       return false;
9103     }
9104 
9105     // Keep looking.
9106     return true;
9107   }
9108   bool isDone() const { return false; }
9109 };
9110 
9111 // Check if a SCEV contains an AddRecExpr.
9112 struct SCEVHasAddRec {
9113   bool &ContainsAddRec;
9114 
9115   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9116    ContainsAddRec = false;
9117   }
9118 
9119   bool follow(const SCEV *S) {
9120     if (isa<SCEVAddRecExpr>(S)) {
9121       ContainsAddRec = true;
9122 
9123       // Stop recursion: once we collected a term, do not walk its operands.
9124       return false;
9125     }
9126 
9127     // Keep looking.
9128     return true;
9129   }
9130   bool isDone() const { return false; }
9131 };
9132 
9133 // Find factors that are multiplied with an expression that (possibly as a
9134 // subexpression) contains an AddRecExpr. In the expression:
9135 //
9136 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9137 //
9138 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9139 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9140 // parameters as they form a product with an induction variable.
9141 //
9142 // This collector expects all array size parameters to be in the same MulExpr.
9143 // It might be necessary to later add support for collecting parameters that are
9144 // spread over different nested MulExpr.
9145 struct SCEVCollectAddRecMultiplies {
9146   SmallVectorImpl<const SCEV *> &Terms;
9147   ScalarEvolution &SE;
9148 
9149   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9150       : Terms(T), SE(SE) {}
9151 
9152   bool follow(const SCEV *S) {
9153     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9154       bool HasAddRec = false;
9155       SmallVector<const SCEV *, 0> Operands;
9156       for (auto Op : Mul->operands()) {
9157         if (isa<SCEVUnknown>(Op)) {
9158           Operands.push_back(Op);
9159         } else {
9160           bool ContainsAddRec;
9161           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9162           visitAll(Op, ContiansAddRec);
9163           HasAddRec |= ContainsAddRec;
9164         }
9165       }
9166       if (Operands.size() == 0)
9167         return true;
9168 
9169       if (!HasAddRec)
9170         return false;
9171 
9172       Terms.push_back(SE.getMulExpr(Operands));
9173       // Stop recursion: once we collected a term, do not walk its operands.
9174       return false;
9175     }
9176 
9177     // Keep looking.
9178     return true;
9179   }
9180   bool isDone() const { return false; }
9181 };
9182 }
9183 
9184 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9185 /// two places:
9186 ///   1) The strides of AddRec expressions.
9187 ///   2) Unknowns that are multiplied with AddRec expressions.
9188 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9189     SmallVectorImpl<const SCEV *> &Terms) {
9190   SmallVector<const SCEV *, 4> Strides;
9191   SCEVCollectStrides StrideCollector(*this, Strides);
9192   visitAll(Expr, StrideCollector);
9193 
9194   DEBUG({
9195       dbgs() << "Strides:\n";
9196       for (const SCEV *S : Strides)
9197         dbgs() << *S << "\n";
9198     });
9199 
9200   for (const SCEV *S : Strides) {
9201     SCEVCollectTerms TermCollector(Terms);
9202     visitAll(S, TermCollector);
9203   }
9204 
9205   DEBUG({
9206       dbgs() << "Terms:\n";
9207       for (const SCEV *T : Terms)
9208         dbgs() << *T << "\n";
9209     });
9210 
9211   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9212   visitAll(Expr, MulCollector);
9213 }
9214 
9215 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9216                                    SmallVectorImpl<const SCEV *> &Terms,
9217                                    SmallVectorImpl<const SCEV *> &Sizes) {
9218   int Last = Terms.size() - 1;
9219   const SCEV *Step = Terms[Last];
9220 
9221   // End of recursion.
9222   if (Last == 0) {
9223     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9224       SmallVector<const SCEV *, 2> Qs;
9225       for (const SCEV *Op : M->operands())
9226         if (!isa<SCEVConstant>(Op))
9227           Qs.push_back(Op);
9228 
9229       Step = SE.getMulExpr(Qs);
9230     }
9231 
9232     Sizes.push_back(Step);
9233     return true;
9234   }
9235 
9236   for (const SCEV *&Term : Terms) {
9237     // Normalize the terms before the next call to findArrayDimensionsRec.
9238     const SCEV *Q, *R;
9239     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9240 
9241     // Bail out when GCD does not evenly divide one of the terms.
9242     if (!R->isZero())
9243       return false;
9244 
9245     Term = Q;
9246   }
9247 
9248   // Remove all SCEVConstants.
9249   Terms.erase(
9250       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9251       Terms.end());
9252 
9253   if (Terms.size() > 0)
9254     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9255       return false;
9256 
9257   Sizes.push_back(Step);
9258   return true;
9259 }
9260 
9261 
9262 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9263 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9264   for (const SCEV *T : Terms)
9265     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9266       return true;
9267   return false;
9268 }
9269 
9270 // Return the number of product terms in S.
9271 static inline int numberOfTerms(const SCEV *S) {
9272   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9273     return Expr->getNumOperands();
9274   return 1;
9275 }
9276 
9277 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9278   if (isa<SCEVConstant>(T))
9279     return nullptr;
9280 
9281   if (isa<SCEVUnknown>(T))
9282     return T;
9283 
9284   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9285     SmallVector<const SCEV *, 2> Factors;
9286     for (const SCEV *Op : M->operands())
9287       if (!isa<SCEVConstant>(Op))
9288         Factors.push_back(Op);
9289 
9290     return SE.getMulExpr(Factors);
9291   }
9292 
9293   return T;
9294 }
9295 
9296 /// Return the size of an element read or written by Inst.
9297 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9298   Type *Ty;
9299   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9300     Ty = Store->getValueOperand()->getType();
9301   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9302     Ty = Load->getType();
9303   else
9304     return nullptr;
9305 
9306   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9307   return getSizeOfExpr(ETy, Ty);
9308 }
9309 
9310 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9311                                           SmallVectorImpl<const SCEV *> &Sizes,
9312                                           const SCEV *ElementSize) const {
9313   if (Terms.size() < 1 || !ElementSize)
9314     return;
9315 
9316   // Early return when Terms do not contain parameters: we do not delinearize
9317   // non parametric SCEVs.
9318   if (!containsParameters(Terms))
9319     return;
9320 
9321   DEBUG({
9322       dbgs() << "Terms:\n";
9323       for (const SCEV *T : Terms)
9324         dbgs() << *T << "\n";
9325     });
9326 
9327   // Remove duplicates.
9328   std::sort(Terms.begin(), Terms.end());
9329   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9330 
9331   // Put larger terms first.
9332   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9333     return numberOfTerms(LHS) > numberOfTerms(RHS);
9334   });
9335 
9336   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9337 
9338   // Try to divide all terms by the element size. If term is not divisible by
9339   // element size, proceed with the original term.
9340   for (const SCEV *&Term : Terms) {
9341     const SCEV *Q, *R;
9342     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9343     if (!Q->isZero())
9344       Term = Q;
9345   }
9346 
9347   SmallVector<const SCEV *, 4> NewTerms;
9348 
9349   // Remove constant factors.
9350   for (const SCEV *T : Terms)
9351     if (const SCEV *NewT = removeConstantFactors(SE, T))
9352       NewTerms.push_back(NewT);
9353 
9354   DEBUG({
9355       dbgs() << "Terms after sorting:\n";
9356       for (const SCEV *T : NewTerms)
9357         dbgs() << *T << "\n";
9358     });
9359 
9360   if (NewTerms.empty() ||
9361       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9362     Sizes.clear();
9363     return;
9364   }
9365 
9366   // The last element to be pushed into Sizes is the size of an element.
9367   Sizes.push_back(ElementSize);
9368 
9369   DEBUG({
9370       dbgs() << "Sizes:\n";
9371       for (const SCEV *S : Sizes)
9372         dbgs() << *S << "\n";
9373     });
9374 }
9375 
9376 void ScalarEvolution::computeAccessFunctions(
9377     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9378     SmallVectorImpl<const SCEV *> &Sizes) {
9379 
9380   // Early exit in case this SCEV is not an affine multivariate function.
9381   if (Sizes.empty())
9382     return;
9383 
9384   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9385     if (!AR->isAffine())
9386       return;
9387 
9388   const SCEV *Res = Expr;
9389   int Last = Sizes.size() - 1;
9390   for (int i = Last; i >= 0; i--) {
9391     const SCEV *Q, *R;
9392     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9393 
9394     DEBUG({
9395         dbgs() << "Res: " << *Res << "\n";
9396         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9397         dbgs() << "Res divided by Sizes[i]:\n";
9398         dbgs() << "Quotient: " << *Q << "\n";
9399         dbgs() << "Remainder: " << *R << "\n";
9400       });
9401 
9402     Res = Q;
9403 
9404     // Do not record the last subscript corresponding to the size of elements in
9405     // the array.
9406     if (i == Last) {
9407 
9408       // Bail out if the remainder is too complex.
9409       if (isa<SCEVAddRecExpr>(R)) {
9410         Subscripts.clear();
9411         Sizes.clear();
9412         return;
9413       }
9414 
9415       continue;
9416     }
9417 
9418     // Record the access function for the current subscript.
9419     Subscripts.push_back(R);
9420   }
9421 
9422   // Also push in last position the remainder of the last division: it will be
9423   // the access function of the innermost dimension.
9424   Subscripts.push_back(Res);
9425 
9426   std::reverse(Subscripts.begin(), Subscripts.end());
9427 
9428   DEBUG({
9429       dbgs() << "Subscripts:\n";
9430       for (const SCEV *S : Subscripts)
9431         dbgs() << *S << "\n";
9432     });
9433 }
9434 
9435 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9436 /// sizes of an array access. Returns the remainder of the delinearization that
9437 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9438 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9439 /// expressions in the stride and base of a SCEV corresponding to the
9440 /// computation of a GCD (greatest common divisor) of base and stride.  When
9441 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9442 ///
9443 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9444 ///
9445 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9446 ///
9447 ///    for (long i = 0; i < n; i++)
9448 ///      for (long j = 0; j < m; j++)
9449 ///        for (long k = 0; k < o; k++)
9450 ///          A[i][j][k] = 1.0;
9451 ///  }
9452 ///
9453 /// the delinearization input is the following AddRec SCEV:
9454 ///
9455 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9456 ///
9457 /// From this SCEV, we are able to say that the base offset of the access is %A
9458 /// because it appears as an offset that does not divide any of the strides in
9459 /// the loops:
9460 ///
9461 ///  CHECK: Base offset: %A
9462 ///
9463 /// and then SCEV->delinearize determines the size of some of the dimensions of
9464 /// the array as these are the multiples by which the strides are happening:
9465 ///
9466 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9467 ///
9468 /// Note that the outermost dimension remains of UnknownSize because there are
9469 /// no strides that would help identifying the size of the last dimension: when
9470 /// the array has been statically allocated, one could compute the size of that
9471 /// dimension by dividing the overall size of the array by the size of the known
9472 /// dimensions: %m * %o * 8.
9473 ///
9474 /// Finally delinearize provides the access functions for the array reference
9475 /// that does correspond to A[i][j][k] of the above C testcase:
9476 ///
9477 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9478 ///
9479 /// The testcases are checking the output of a function pass:
9480 /// DelinearizationPass that walks through all loads and stores of a function
9481 /// asking for the SCEV of the memory access with respect to all enclosing
9482 /// loops, calling SCEV->delinearize on that and printing the results.
9483 
9484 void ScalarEvolution::delinearize(const SCEV *Expr,
9485                                  SmallVectorImpl<const SCEV *> &Subscripts,
9486                                  SmallVectorImpl<const SCEV *> &Sizes,
9487                                  const SCEV *ElementSize) {
9488   // First step: collect parametric terms.
9489   SmallVector<const SCEV *, 4> Terms;
9490   collectParametricTerms(Expr, Terms);
9491 
9492   if (Terms.empty())
9493     return;
9494 
9495   // Second step: find subscript sizes.
9496   findArrayDimensions(Terms, Sizes, ElementSize);
9497 
9498   if (Sizes.empty())
9499     return;
9500 
9501   // Third step: compute the access functions for each subscript.
9502   computeAccessFunctions(Expr, Subscripts, Sizes);
9503 
9504   if (Subscripts.empty())
9505     return;
9506 
9507   DEBUG({
9508       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9509       dbgs() << "ArrayDecl[UnknownSize]";
9510       for (const SCEV *S : Sizes)
9511         dbgs() << "[" << *S << "]";
9512 
9513       dbgs() << "\nArrayRef";
9514       for (const SCEV *S : Subscripts)
9515         dbgs() << "[" << *S << "]";
9516       dbgs() << "\n";
9517     });
9518 }
9519 
9520 //===----------------------------------------------------------------------===//
9521 //                   SCEVCallbackVH Class Implementation
9522 //===----------------------------------------------------------------------===//
9523 
9524 void ScalarEvolution::SCEVCallbackVH::deleted() {
9525   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9526   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9527     SE->ConstantEvolutionLoopExitValue.erase(PN);
9528   SE->eraseValueFromMap(getValPtr());
9529   // this now dangles!
9530 }
9531 
9532 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9533   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9534 
9535   // Forget all the expressions associated with users of the old value,
9536   // so that future queries will recompute the expressions using the new
9537   // value.
9538   Value *Old = getValPtr();
9539   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9540   SmallPtrSet<User *, 8> Visited;
9541   while (!Worklist.empty()) {
9542     User *U = Worklist.pop_back_val();
9543     // Deleting the Old value will cause this to dangle. Postpone
9544     // that until everything else is done.
9545     if (U == Old)
9546       continue;
9547     if (!Visited.insert(U).second)
9548       continue;
9549     if (PHINode *PN = dyn_cast<PHINode>(U))
9550       SE->ConstantEvolutionLoopExitValue.erase(PN);
9551     SE->eraseValueFromMap(U);
9552     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9553   }
9554   // Delete the Old value.
9555   if (PHINode *PN = dyn_cast<PHINode>(Old))
9556     SE->ConstantEvolutionLoopExitValue.erase(PN);
9557   SE->eraseValueFromMap(Old);
9558   // this now dangles!
9559 }
9560 
9561 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9562   : CallbackVH(V), SE(se) {}
9563 
9564 //===----------------------------------------------------------------------===//
9565 //                   ScalarEvolution Class Implementation
9566 //===----------------------------------------------------------------------===//
9567 
9568 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9569                                  AssumptionCache &AC, DominatorTree &DT,
9570                                  LoopInfo &LI)
9571     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9572       CouldNotCompute(new SCEVCouldNotCompute()),
9573       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9574       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9575       FirstUnknown(nullptr) {
9576 
9577   // To use guards for proving predicates, we need to scan every instruction in
9578   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9579   // time if the IR does not actually contain any calls to
9580   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9581   //
9582   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9583   // to _add_ guards to the module when there weren't any before, and wants
9584   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9585   // efficient in lieu of being smart in that rather obscure case.
9586 
9587   auto *GuardDecl = F.getParent()->getFunction(
9588       Intrinsic::getName(Intrinsic::experimental_guard));
9589   HasGuards = GuardDecl && !GuardDecl->use_empty();
9590 }
9591 
9592 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9593     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9594       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9595       ValueExprMap(std::move(Arg.ValueExprMap)),
9596       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9597       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9598       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
9599       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9600       PredicatedBackedgeTakenCounts(
9601           std::move(Arg.PredicatedBackedgeTakenCounts)),
9602       ConstantEvolutionLoopExitValue(
9603           std::move(Arg.ConstantEvolutionLoopExitValue)),
9604       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9605       LoopDispositions(std::move(Arg.LoopDispositions)),
9606       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9607       BlockDispositions(std::move(Arg.BlockDispositions)),
9608       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9609       SignedRanges(std::move(Arg.SignedRanges)),
9610       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9611       UniquePreds(std::move(Arg.UniquePreds)),
9612       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9613       FirstUnknown(Arg.FirstUnknown) {
9614   Arg.FirstUnknown = nullptr;
9615 }
9616 
9617 ScalarEvolution::~ScalarEvolution() {
9618   // Iterate through all the SCEVUnknown instances and call their
9619   // destructors, so that they release their references to their values.
9620   for (SCEVUnknown *U = FirstUnknown; U;) {
9621     SCEVUnknown *Tmp = U;
9622     U = U->Next;
9623     Tmp->~SCEVUnknown();
9624   }
9625   FirstUnknown = nullptr;
9626 
9627   ExprValueMap.clear();
9628   ValueExprMap.clear();
9629   HasRecMap.clear();
9630 
9631   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9632   // that a loop had multiple computable exits.
9633   for (auto &BTCI : BackedgeTakenCounts)
9634     BTCI.second.clear();
9635   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9636     BTCI.second.clear();
9637 
9638   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9639   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9640   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9641 }
9642 
9643 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9644   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9645 }
9646 
9647 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9648                           const Loop *L) {
9649   // Print all inner loops first
9650   for (Loop *I : *L)
9651     PrintLoopInfo(OS, SE, I);
9652 
9653   OS << "Loop ";
9654   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9655   OS << ": ";
9656 
9657   SmallVector<BasicBlock *, 8> ExitBlocks;
9658   L->getExitBlocks(ExitBlocks);
9659   if (ExitBlocks.size() != 1)
9660     OS << "<multiple exits> ";
9661 
9662   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9663     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9664   } else {
9665     OS << "Unpredictable backedge-taken count. ";
9666   }
9667 
9668   OS << "\n"
9669         "Loop ";
9670   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9671   OS << ": ";
9672 
9673   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9674     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9675     if (SE->isBackedgeTakenCountMaxOrZero(L))
9676       OS << ", actual taken count either this or zero.";
9677   } else {
9678     OS << "Unpredictable max backedge-taken count. ";
9679   }
9680 
9681   OS << "\n"
9682         "Loop ";
9683   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9684   OS << ": ";
9685 
9686   SCEVUnionPredicate Pred;
9687   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9688   if (!isa<SCEVCouldNotCompute>(PBT)) {
9689     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9690     OS << " Predicates:\n";
9691     Pred.print(OS, 4);
9692   } else {
9693     OS << "Unpredictable predicated backedge-taken count. ";
9694   }
9695   OS << "\n";
9696 
9697   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9698     OS << "Loop ";
9699     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9700     OS << ": ";
9701     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
9702   }
9703 }
9704 
9705 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9706   switch (LD) {
9707   case ScalarEvolution::LoopVariant:
9708     return "Variant";
9709   case ScalarEvolution::LoopInvariant:
9710     return "Invariant";
9711   case ScalarEvolution::LoopComputable:
9712     return "Computable";
9713   }
9714   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9715 }
9716 
9717 void ScalarEvolution::print(raw_ostream &OS) const {
9718   // ScalarEvolution's implementation of the print method is to print
9719   // out SCEV values of all instructions that are interesting. Doing
9720   // this potentially causes it to create new SCEV objects though,
9721   // which technically conflicts with the const qualifier. This isn't
9722   // observable from outside the class though, so casting away the
9723   // const isn't dangerous.
9724   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9725 
9726   OS << "Classifying expressions for: ";
9727   F.printAsOperand(OS, /*PrintType=*/false);
9728   OS << "\n";
9729   for (Instruction &I : instructions(F))
9730     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9731       OS << I << '\n';
9732       OS << "  -->  ";
9733       const SCEV *SV = SE.getSCEV(&I);
9734       SV->print(OS);
9735       if (!isa<SCEVCouldNotCompute>(SV)) {
9736         OS << " U: ";
9737         SE.getUnsignedRange(SV).print(OS);
9738         OS << " S: ";
9739         SE.getSignedRange(SV).print(OS);
9740       }
9741 
9742       const Loop *L = LI.getLoopFor(I.getParent());
9743 
9744       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9745       if (AtUse != SV) {
9746         OS << "  -->  ";
9747         AtUse->print(OS);
9748         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9749           OS << " U: ";
9750           SE.getUnsignedRange(AtUse).print(OS);
9751           OS << " S: ";
9752           SE.getSignedRange(AtUse).print(OS);
9753         }
9754       }
9755 
9756       if (L) {
9757         OS << "\t\t" "Exits: ";
9758         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9759         if (!SE.isLoopInvariant(ExitValue, L)) {
9760           OS << "<<Unknown>>";
9761         } else {
9762           OS << *ExitValue;
9763         }
9764 
9765         bool First = true;
9766         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9767           if (First) {
9768             OS << "\t\t" "LoopDispositions: { ";
9769             First = false;
9770           } else {
9771             OS << ", ";
9772           }
9773 
9774           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9775           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9776         }
9777 
9778         for (auto *InnerL : depth_first(L)) {
9779           if (InnerL == L)
9780             continue;
9781           if (First) {
9782             OS << "\t\t" "LoopDispositions: { ";
9783             First = false;
9784           } else {
9785             OS << ", ";
9786           }
9787 
9788           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9789           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9790         }
9791 
9792         OS << " }";
9793       }
9794 
9795       OS << "\n";
9796     }
9797 
9798   OS << "Determining loop execution counts for: ";
9799   F.printAsOperand(OS, /*PrintType=*/false);
9800   OS << "\n";
9801   for (Loop *I : LI)
9802     PrintLoopInfo(OS, &SE, I);
9803 }
9804 
9805 ScalarEvolution::LoopDisposition
9806 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9807   auto &Values = LoopDispositions[S];
9808   for (auto &V : Values) {
9809     if (V.getPointer() == L)
9810       return V.getInt();
9811   }
9812   Values.emplace_back(L, LoopVariant);
9813   LoopDisposition D = computeLoopDisposition(S, L);
9814   auto &Values2 = LoopDispositions[S];
9815   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9816     if (V.getPointer() == L) {
9817       V.setInt(D);
9818       break;
9819     }
9820   }
9821   return D;
9822 }
9823 
9824 ScalarEvolution::LoopDisposition
9825 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9826   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9827   case scConstant:
9828     return LoopInvariant;
9829   case scTruncate:
9830   case scZeroExtend:
9831   case scSignExtend:
9832     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9833   case scAddRecExpr: {
9834     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9835 
9836     // If L is the addrec's loop, it's computable.
9837     if (AR->getLoop() == L)
9838       return LoopComputable;
9839 
9840     // Add recurrences are never invariant in the function-body (null loop).
9841     if (!L)
9842       return LoopVariant;
9843 
9844     // This recurrence is variant w.r.t. L if L contains AR's loop.
9845     if (L->contains(AR->getLoop()))
9846       return LoopVariant;
9847 
9848     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9849     if (AR->getLoop()->contains(L))
9850       return LoopInvariant;
9851 
9852     // This recurrence is variant w.r.t. L if any of its operands
9853     // are variant.
9854     for (auto *Op : AR->operands())
9855       if (!isLoopInvariant(Op, L))
9856         return LoopVariant;
9857 
9858     // Otherwise it's loop-invariant.
9859     return LoopInvariant;
9860   }
9861   case scAddExpr:
9862   case scMulExpr:
9863   case scUMaxExpr:
9864   case scSMaxExpr: {
9865     bool HasVarying = false;
9866     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9867       LoopDisposition D = getLoopDisposition(Op, L);
9868       if (D == LoopVariant)
9869         return LoopVariant;
9870       if (D == LoopComputable)
9871         HasVarying = true;
9872     }
9873     return HasVarying ? LoopComputable : LoopInvariant;
9874   }
9875   case scUDivExpr: {
9876     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9877     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9878     if (LD == LoopVariant)
9879       return LoopVariant;
9880     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9881     if (RD == LoopVariant)
9882       return LoopVariant;
9883     return (LD == LoopInvariant && RD == LoopInvariant) ?
9884            LoopInvariant : LoopComputable;
9885   }
9886   case scUnknown:
9887     // All non-instruction values are loop invariant.  All instructions are loop
9888     // invariant if they are not contained in the specified loop.
9889     // Instructions are never considered invariant in the function body
9890     // (null loop) because they are defined within the "loop".
9891     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9892       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9893     return LoopInvariant;
9894   case scCouldNotCompute:
9895     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9896   }
9897   llvm_unreachable("Unknown SCEV kind!");
9898 }
9899 
9900 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9901   return getLoopDisposition(S, L) == LoopInvariant;
9902 }
9903 
9904 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9905   return getLoopDisposition(S, L) == LoopComputable;
9906 }
9907 
9908 ScalarEvolution::BlockDisposition
9909 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9910   auto &Values = BlockDispositions[S];
9911   for (auto &V : Values) {
9912     if (V.getPointer() == BB)
9913       return V.getInt();
9914   }
9915   Values.emplace_back(BB, DoesNotDominateBlock);
9916   BlockDisposition D = computeBlockDisposition(S, BB);
9917   auto &Values2 = BlockDispositions[S];
9918   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9919     if (V.getPointer() == BB) {
9920       V.setInt(D);
9921       break;
9922     }
9923   }
9924   return D;
9925 }
9926 
9927 ScalarEvolution::BlockDisposition
9928 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9929   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9930   case scConstant:
9931     return ProperlyDominatesBlock;
9932   case scTruncate:
9933   case scZeroExtend:
9934   case scSignExtend:
9935     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9936   case scAddRecExpr: {
9937     // This uses a "dominates" query instead of "properly dominates" query
9938     // to test for proper dominance too, because the instruction which
9939     // produces the addrec's value is a PHI, and a PHI effectively properly
9940     // dominates its entire containing block.
9941     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9942     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9943       return DoesNotDominateBlock;
9944 
9945     // Fall through into SCEVNAryExpr handling.
9946     LLVM_FALLTHROUGH;
9947   }
9948   case scAddExpr:
9949   case scMulExpr:
9950   case scUMaxExpr:
9951   case scSMaxExpr: {
9952     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9953     bool Proper = true;
9954     for (const SCEV *NAryOp : NAry->operands()) {
9955       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9956       if (D == DoesNotDominateBlock)
9957         return DoesNotDominateBlock;
9958       if (D == DominatesBlock)
9959         Proper = false;
9960     }
9961     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9962   }
9963   case scUDivExpr: {
9964     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9965     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9966     BlockDisposition LD = getBlockDisposition(LHS, BB);
9967     if (LD == DoesNotDominateBlock)
9968       return DoesNotDominateBlock;
9969     BlockDisposition RD = getBlockDisposition(RHS, BB);
9970     if (RD == DoesNotDominateBlock)
9971       return DoesNotDominateBlock;
9972     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9973       ProperlyDominatesBlock : DominatesBlock;
9974   }
9975   case scUnknown:
9976     if (Instruction *I =
9977           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9978       if (I->getParent() == BB)
9979         return DominatesBlock;
9980       if (DT.properlyDominates(I->getParent(), BB))
9981         return ProperlyDominatesBlock;
9982       return DoesNotDominateBlock;
9983     }
9984     return ProperlyDominatesBlock;
9985   case scCouldNotCompute:
9986     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9987   }
9988   llvm_unreachable("Unknown SCEV kind!");
9989 }
9990 
9991 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9992   return getBlockDisposition(S, BB) >= DominatesBlock;
9993 }
9994 
9995 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9996   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9997 }
9998 
9999 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10000   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10001 }
10002 
10003 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10004   ValuesAtScopes.erase(S);
10005   LoopDispositions.erase(S);
10006   BlockDispositions.erase(S);
10007   UnsignedRanges.erase(S);
10008   SignedRanges.erase(S);
10009   ExprValueMap.erase(S);
10010   HasRecMap.erase(S);
10011   MinTrailingZerosCache.erase(S);
10012 
10013   auto RemoveSCEVFromBackedgeMap =
10014       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10015         for (auto I = Map.begin(), E = Map.end(); I != E;) {
10016           BackedgeTakenInfo &BEInfo = I->second;
10017           if (BEInfo.hasOperand(S, this)) {
10018             BEInfo.clear();
10019             Map.erase(I++);
10020           } else
10021             ++I;
10022         }
10023       };
10024 
10025   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10026   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10027 }
10028 
10029 typedef DenseMap<const Loop *, std::string> VerifyMap;
10030 
10031 /// replaceSubString - Replaces all occurrences of From in Str with To.
10032 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10033   size_t Pos = 0;
10034   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10035     Str.replace(Pos, From.size(), To.data(), To.size());
10036     Pos += To.size();
10037   }
10038 }
10039 
10040 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10041 static void
10042 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
10043   std::string &S = Map[L];
10044   if (S.empty()) {
10045     raw_string_ostream OS(S);
10046     SE.getBackedgeTakenCount(L)->print(OS);
10047 
10048     // false and 0 are semantically equivalent. This can happen in dead loops.
10049     replaceSubString(OS.str(), "false", "0");
10050     // Remove wrap flags, their use in SCEV is highly fragile.
10051     // FIXME: Remove this when SCEV gets smarter about them.
10052     replaceSubString(OS.str(), "<nw>", "");
10053     replaceSubString(OS.str(), "<nsw>", "");
10054     replaceSubString(OS.str(), "<nuw>", "");
10055   }
10056 
10057   for (auto *R : reverse(*L))
10058     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
10059 }
10060 
10061 void ScalarEvolution::verify() const {
10062   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10063 
10064   // Gather stringified backedge taken counts for all loops using SCEV's caches.
10065   // FIXME: It would be much better to store actual values instead of strings,
10066   //        but SCEV pointers will change if we drop the caches.
10067   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
10068   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10069     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10070 
10071   // Gather stringified backedge taken counts for all loops using a fresh
10072   // ScalarEvolution object.
10073   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10074   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10075     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10076 
10077   // Now compare whether they're the same with and without caches. This allows
10078   // verifying that no pass changed the cache.
10079   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10080          "New loops suddenly appeared!");
10081 
10082   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10083                            OldE = BackedgeDumpsOld.end(),
10084                            NewI = BackedgeDumpsNew.begin();
10085        OldI != OldE; ++OldI, ++NewI) {
10086     assert(OldI->first == NewI->first && "Loop order changed!");
10087 
10088     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10089     // changes.
10090     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10091     // means that a pass is buggy or SCEV has to learn a new pattern but is
10092     // usually not harmful.
10093     if (OldI->second != NewI->second &&
10094         OldI->second.find("undef") == std::string::npos &&
10095         NewI->second.find("undef") == std::string::npos &&
10096         OldI->second != "***COULDNOTCOMPUTE***" &&
10097         NewI->second != "***COULDNOTCOMPUTE***") {
10098       dbgs() << "SCEVValidator: SCEV for loop '"
10099              << OldI->first->getHeader()->getName()
10100              << "' changed from '" << OldI->second
10101              << "' to '" << NewI->second << "'!\n";
10102       std::abort();
10103     }
10104   }
10105 
10106   // TODO: Verify more things.
10107 }
10108 
10109 bool ScalarEvolution::invalidate(
10110     Function &F, const PreservedAnalyses &PA,
10111     FunctionAnalysisManager::Invalidator &Inv) {
10112   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10113   // of its dependencies is invalidated.
10114   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10115   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10116          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10117          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10118          Inv.invalidate<LoopAnalysis>(F, PA);
10119 }
10120 
10121 AnalysisKey ScalarEvolutionAnalysis::Key;
10122 
10123 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10124                                              FunctionAnalysisManager &AM) {
10125   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10126                          AM.getResult<AssumptionAnalysis>(F),
10127                          AM.getResult<DominatorTreeAnalysis>(F),
10128                          AM.getResult<LoopAnalysis>(F));
10129 }
10130 
10131 PreservedAnalyses
10132 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10133   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10134   return PreservedAnalyses::all();
10135 }
10136 
10137 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10138                       "Scalar Evolution Analysis", false, true)
10139 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10140 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10141 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10142 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10143 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10144                     "Scalar Evolution Analysis", false, true)
10145 char ScalarEvolutionWrapperPass::ID = 0;
10146 
10147 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10148   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10149 }
10150 
10151 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10152   SE.reset(new ScalarEvolution(
10153       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10154       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10155       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10156       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10157   return false;
10158 }
10159 
10160 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10161 
10162 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10163   SE->print(OS);
10164 }
10165 
10166 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10167   if (!VerifySCEV)
10168     return;
10169 
10170   SE->verify();
10171 }
10172 
10173 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10174   AU.setPreservesAll();
10175   AU.addRequiredTransitive<AssumptionCacheTracker>();
10176   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10177   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10178   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10179 }
10180 
10181 const SCEVPredicate *
10182 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10183                                    const SCEVConstant *RHS) {
10184   FoldingSetNodeID ID;
10185   // Unique this node based on the arguments
10186   ID.AddInteger(SCEVPredicate::P_Equal);
10187   ID.AddPointer(LHS);
10188   ID.AddPointer(RHS);
10189   void *IP = nullptr;
10190   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10191     return S;
10192   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10193       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10194   UniquePreds.InsertNode(Eq, IP);
10195   return Eq;
10196 }
10197 
10198 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10199     const SCEVAddRecExpr *AR,
10200     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10201   FoldingSetNodeID ID;
10202   // Unique this node based on the arguments
10203   ID.AddInteger(SCEVPredicate::P_Wrap);
10204   ID.AddPointer(AR);
10205   ID.AddInteger(AddedFlags);
10206   void *IP = nullptr;
10207   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10208     return S;
10209   auto *OF = new (SCEVAllocator)
10210       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10211   UniquePreds.InsertNode(OF, IP);
10212   return OF;
10213 }
10214 
10215 namespace {
10216 
10217 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10218 public:
10219   /// Rewrites \p S in the context of a loop L and the SCEV predication
10220   /// infrastructure.
10221   ///
10222   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10223   /// equivalences present in \p Pred.
10224   ///
10225   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10226   /// \p NewPreds such that the result will be an AddRecExpr.
10227   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10228                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10229                              SCEVUnionPredicate *Pred) {
10230     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10231     return Rewriter.visit(S);
10232   }
10233 
10234   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10235                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10236                         SCEVUnionPredicate *Pred)
10237       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10238 
10239   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10240     if (Pred) {
10241       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10242       for (auto *Pred : ExprPreds)
10243         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10244           if (IPred->getLHS() == Expr)
10245             return IPred->getRHS();
10246     }
10247 
10248     return Expr;
10249   }
10250 
10251   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10252     const SCEV *Operand = visit(Expr->getOperand());
10253     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10254     if (AR && AR->getLoop() == L && AR->isAffine()) {
10255       // This couldn't be folded because the operand didn't have the nuw
10256       // flag. Add the nusw flag as an assumption that we could make.
10257       const SCEV *Step = AR->getStepRecurrence(SE);
10258       Type *Ty = Expr->getType();
10259       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10260         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10261                                 SE.getSignExtendExpr(Step, Ty), L,
10262                                 AR->getNoWrapFlags());
10263     }
10264     return SE.getZeroExtendExpr(Operand, Expr->getType());
10265   }
10266 
10267   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10268     const SCEV *Operand = visit(Expr->getOperand());
10269     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10270     if (AR && AR->getLoop() == L && AR->isAffine()) {
10271       // This couldn't be folded because the operand didn't have the nsw
10272       // flag. Add the nssw flag as an assumption that we could make.
10273       const SCEV *Step = AR->getStepRecurrence(SE);
10274       Type *Ty = Expr->getType();
10275       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10276         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10277                                 SE.getSignExtendExpr(Step, Ty), L,
10278                                 AR->getNoWrapFlags());
10279     }
10280     return SE.getSignExtendExpr(Operand, Expr->getType());
10281   }
10282 
10283 private:
10284   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10285                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10286     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10287     if (!NewPreds) {
10288       // Check if we've already made this assumption.
10289       return Pred && Pred->implies(A);
10290     }
10291     NewPreds->insert(A);
10292     return true;
10293   }
10294 
10295   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10296   SCEVUnionPredicate *Pred;
10297   const Loop *L;
10298 };
10299 } // end anonymous namespace
10300 
10301 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10302                                                    SCEVUnionPredicate &Preds) {
10303   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10304 }
10305 
10306 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10307     const SCEV *S, const Loop *L,
10308     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10309 
10310   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10311   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10312   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10313 
10314   if (!AddRec)
10315     return nullptr;
10316 
10317   // Since the transformation was successful, we can now transfer the SCEV
10318   // predicates.
10319   for (auto *P : TransformPreds)
10320     Preds.insert(P);
10321 
10322   return AddRec;
10323 }
10324 
10325 /// SCEV predicates
10326 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10327                              SCEVPredicateKind Kind)
10328     : FastID(ID), Kind(Kind) {}
10329 
10330 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10331                                        const SCEVUnknown *LHS,
10332                                        const SCEVConstant *RHS)
10333     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10334 
10335 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10336   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10337 
10338   if (!Op)
10339     return false;
10340 
10341   return Op->LHS == LHS && Op->RHS == RHS;
10342 }
10343 
10344 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10345 
10346 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10347 
10348 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10349   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10350 }
10351 
10352 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10353                                      const SCEVAddRecExpr *AR,
10354                                      IncrementWrapFlags Flags)
10355     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10356 
10357 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10358 
10359 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10360   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10361 
10362   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10363 }
10364 
10365 bool SCEVWrapPredicate::isAlwaysTrue() const {
10366   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10367   IncrementWrapFlags IFlags = Flags;
10368 
10369   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10370     IFlags = clearFlags(IFlags, IncrementNSSW);
10371 
10372   return IFlags == IncrementAnyWrap;
10373 }
10374 
10375 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10376   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10377   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10378     OS << "<nusw>";
10379   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10380     OS << "<nssw>";
10381   OS << "\n";
10382 }
10383 
10384 SCEVWrapPredicate::IncrementWrapFlags
10385 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10386                                    ScalarEvolution &SE) {
10387   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10388   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10389 
10390   // We can safely transfer the NSW flag as NSSW.
10391   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10392     ImpliedFlags = IncrementNSSW;
10393 
10394   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10395     // If the increment is positive, the SCEV NUW flag will also imply the
10396     // WrapPredicate NUSW flag.
10397     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10398       if (Step->getValue()->getValue().isNonNegative())
10399         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10400   }
10401 
10402   return ImpliedFlags;
10403 }
10404 
10405 /// Union predicates don't get cached so create a dummy set ID for it.
10406 SCEVUnionPredicate::SCEVUnionPredicate()
10407     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10408 
10409 bool SCEVUnionPredicate::isAlwaysTrue() const {
10410   return all_of(Preds,
10411                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10412 }
10413 
10414 ArrayRef<const SCEVPredicate *>
10415 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10416   auto I = SCEVToPreds.find(Expr);
10417   if (I == SCEVToPreds.end())
10418     return ArrayRef<const SCEVPredicate *>();
10419   return I->second;
10420 }
10421 
10422 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10423   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10424     return all_of(Set->Preds,
10425                   [this](const SCEVPredicate *I) { return this->implies(I); });
10426 
10427   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10428   if (ScevPredsIt == SCEVToPreds.end())
10429     return false;
10430   auto &SCEVPreds = ScevPredsIt->second;
10431 
10432   return any_of(SCEVPreds,
10433                 [N](const SCEVPredicate *I) { return I->implies(N); });
10434 }
10435 
10436 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10437 
10438 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10439   for (auto Pred : Preds)
10440     Pred->print(OS, Depth);
10441 }
10442 
10443 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10444   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10445     for (auto Pred : Set->Preds)
10446       add(Pred);
10447     return;
10448   }
10449 
10450   if (implies(N))
10451     return;
10452 
10453   const SCEV *Key = N->getExpr();
10454   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10455                 " associated expression!");
10456 
10457   SCEVToPreds[Key].push_back(N);
10458   Preds.push_back(N);
10459 }
10460 
10461 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10462                                                      Loop &L)
10463     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10464 
10465 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10466   const SCEV *Expr = SE.getSCEV(V);
10467   RewriteEntry &Entry = RewriteMap[Expr];
10468 
10469   // If we already have an entry and the version matches, return it.
10470   if (Entry.second && Generation == Entry.first)
10471     return Entry.second;
10472 
10473   // We found an entry but it's stale. Rewrite the stale entry
10474   // according to the current predicate.
10475   if (Entry.second)
10476     Expr = Entry.second;
10477 
10478   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10479   Entry = {Generation, NewSCEV};
10480 
10481   return NewSCEV;
10482 }
10483 
10484 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10485   if (!BackedgeCount) {
10486     SCEVUnionPredicate BackedgePred;
10487     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10488     addPredicate(BackedgePred);
10489   }
10490   return BackedgeCount;
10491 }
10492 
10493 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10494   if (Preds.implies(&Pred))
10495     return;
10496   Preds.add(&Pred);
10497   updateGeneration();
10498 }
10499 
10500 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10501   return Preds;
10502 }
10503 
10504 void PredicatedScalarEvolution::updateGeneration() {
10505   // If the generation number wrapped recompute everything.
10506   if (++Generation == 0) {
10507     for (auto &II : RewriteMap) {
10508       const SCEV *Rewritten = II.second.second;
10509       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10510     }
10511   }
10512 }
10513 
10514 void PredicatedScalarEvolution::setNoOverflow(
10515     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10516   const SCEV *Expr = getSCEV(V);
10517   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10518 
10519   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10520 
10521   // Clear the statically implied flags.
10522   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10523   addPredicate(*SE.getWrapPredicate(AR, Flags));
10524 
10525   auto II = FlagsMap.insert({V, Flags});
10526   if (!II.second)
10527     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10528 }
10529 
10530 bool PredicatedScalarEvolution::hasNoOverflow(
10531     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10532   const SCEV *Expr = getSCEV(V);
10533   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10534 
10535   Flags = SCEVWrapPredicate::clearFlags(
10536       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10537 
10538   auto II = FlagsMap.find(V);
10539 
10540   if (II != FlagsMap.end())
10541     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10542 
10543   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10544 }
10545 
10546 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10547   const SCEV *Expr = this->getSCEV(V);
10548   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10549   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10550 
10551   if (!New)
10552     return nullptr;
10553 
10554   for (auto *P : NewPreds)
10555     Preds.add(P);
10556 
10557   updateGeneration();
10558   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10559   return New;
10560 }
10561 
10562 PredicatedScalarEvolution::PredicatedScalarEvolution(
10563     const PredicatedScalarEvolution &Init)
10564     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10565       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10566   for (const auto &I : Init.FlagsMap)
10567     FlagsMap.insert(I);
10568 }
10569 
10570 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10571   // For each block.
10572   for (auto *BB : L.getBlocks())
10573     for (auto &I : *BB) {
10574       if (!SE.isSCEVable(I.getType()))
10575         continue;
10576 
10577       auto *Expr = SE.getSCEV(&I);
10578       auto II = RewriteMap.find(Expr);
10579 
10580       if (II == RewriteMap.end())
10581         continue;
10582 
10583       // Don't print things that are not interesting.
10584       if (II->second.second == Expr)
10585         continue;
10586 
10587       OS.indent(Depth) << "[PSE]" << I << ":\n";
10588       OS.indent(Depth + 2) << *Expr << "\n";
10589       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10590     }
10591 }
10592