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> MaxSCEVOperationsImplicationDepth(
141     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
142     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
143     cl::init(2));
144 
145 static cl::opt<unsigned> MaxValueCompareDepth(
146     "scalar-evolution-max-value-compare-depth", cl::Hidden,
147     cl::desc("Maximum depth of recursive value complexity comparisons"),
148     cl::init(2));
149 
150 static cl::opt<unsigned>
151     MaxAddExprDepth("scalar-evolution-max-addexpr-depth", cl::Hidden,
152                     cl::desc("Maximum depth of recursive AddExpr"),
153                     cl::init(32));
154 
155 static cl::opt<unsigned> MaxConstantEvolvingDepth(
156     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
157     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
158 
159 //===----------------------------------------------------------------------===//
160 //                           SCEV class definitions
161 //===----------------------------------------------------------------------===//
162 
163 //===----------------------------------------------------------------------===//
164 // Implementation of the SCEV class.
165 //
166 
167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168 LLVM_DUMP_METHOD void SCEV::dump() const {
169   print(dbgs());
170   dbgs() << '\n';
171 }
172 #endif
173 
174 void SCEV::print(raw_ostream &OS) const {
175   switch (static_cast<SCEVTypes>(getSCEVType())) {
176   case scConstant:
177     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
178     return;
179   case scTruncate: {
180     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
181     const SCEV *Op = Trunc->getOperand();
182     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
183        << *Trunc->getType() << ")";
184     return;
185   }
186   case scZeroExtend: {
187     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
188     const SCEV *Op = ZExt->getOperand();
189     OS << "(zext " << *Op->getType() << " " << *Op << " to "
190        << *ZExt->getType() << ")";
191     return;
192   }
193   case scSignExtend: {
194     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
195     const SCEV *Op = SExt->getOperand();
196     OS << "(sext " << *Op->getType() << " " << *Op << " to "
197        << *SExt->getType() << ")";
198     return;
199   }
200   case scAddRecExpr: {
201     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
202     OS << "{" << *AR->getOperand(0);
203     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
204       OS << ",+," << *AR->getOperand(i);
205     OS << "}<";
206     if (AR->hasNoUnsignedWrap())
207       OS << "nuw><";
208     if (AR->hasNoSignedWrap())
209       OS << "nsw><";
210     if (AR->hasNoSelfWrap() &&
211         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
212       OS << "nw><";
213     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
214     OS << ">";
215     return;
216   }
217   case scAddExpr:
218   case scMulExpr:
219   case scUMaxExpr:
220   case scSMaxExpr: {
221     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
222     const char *OpStr = nullptr;
223     switch (NAry->getSCEVType()) {
224     case scAddExpr: OpStr = " + "; break;
225     case scMulExpr: OpStr = " * "; break;
226     case scUMaxExpr: OpStr = " umax "; break;
227     case scSMaxExpr: OpStr = " smax "; break;
228     }
229     OS << "(";
230     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
231          I != E; ++I) {
232       OS << **I;
233       if (std::next(I) != E)
234         OS << OpStr;
235     }
236     OS << ")";
237     switch (NAry->getSCEVType()) {
238     case scAddExpr:
239     case scMulExpr:
240       if (NAry->hasNoUnsignedWrap())
241         OS << "<nuw>";
242       if (NAry->hasNoSignedWrap())
243         OS << "<nsw>";
244     }
245     return;
246   }
247   case scUDivExpr: {
248     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
249     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
250     return;
251   }
252   case scUnknown: {
253     const SCEVUnknown *U = cast<SCEVUnknown>(this);
254     Type *AllocTy;
255     if (U->isSizeOf(AllocTy)) {
256       OS << "sizeof(" << *AllocTy << ")";
257       return;
258     }
259     if (U->isAlignOf(AllocTy)) {
260       OS << "alignof(" << *AllocTy << ")";
261       return;
262     }
263 
264     Type *CTy;
265     Constant *FieldNo;
266     if (U->isOffsetOf(CTy, FieldNo)) {
267       OS << "offsetof(" << *CTy << ", ";
268       FieldNo->printAsOperand(OS, false);
269       OS << ")";
270       return;
271     }
272 
273     // Otherwise just print it normally.
274     U->getValue()->printAsOperand(OS, false);
275     return;
276   }
277   case scCouldNotCompute:
278     OS << "***COULDNOTCOMPUTE***";
279     return;
280   }
281   llvm_unreachable("Unknown SCEV kind!");
282 }
283 
284 Type *SCEV::getType() const {
285   switch (static_cast<SCEVTypes>(getSCEVType())) {
286   case scConstant:
287     return cast<SCEVConstant>(this)->getType();
288   case scTruncate:
289   case scZeroExtend:
290   case scSignExtend:
291     return cast<SCEVCastExpr>(this)->getType();
292   case scAddRecExpr:
293   case scMulExpr:
294   case scUMaxExpr:
295   case scSMaxExpr:
296     return cast<SCEVNAryExpr>(this)->getType();
297   case scAddExpr:
298     return cast<SCEVAddExpr>(this)->getType();
299   case scUDivExpr:
300     return cast<SCEVUDivExpr>(this)->getType();
301   case scUnknown:
302     return cast<SCEVUnknown>(this)->getType();
303   case scCouldNotCompute:
304     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
305   }
306   llvm_unreachable("Unknown SCEV kind!");
307 }
308 
309 bool SCEV::isZero() const {
310   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
311     return SC->getValue()->isZero();
312   return false;
313 }
314 
315 bool SCEV::isOne() const {
316   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
317     return SC->getValue()->isOne();
318   return false;
319 }
320 
321 bool SCEV::isAllOnesValue() const {
322   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
323     return SC->getValue()->isAllOnesValue();
324   return false;
325 }
326 
327 bool SCEV::isNonConstantNegative() const {
328   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
329   if (!Mul) return false;
330 
331   // If there is a constant factor, it will be first.
332   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
333   if (!SC) return false;
334 
335   // Return true if the value is negative, this matches things like (-42 * V).
336   return SC->getAPInt().isNegative();
337 }
338 
339 SCEVCouldNotCompute::SCEVCouldNotCompute() :
340   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
341 
342 bool SCEVCouldNotCompute::classof(const SCEV *S) {
343   return S->getSCEVType() == scCouldNotCompute;
344 }
345 
346 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
347   FoldingSetNodeID ID;
348   ID.AddInteger(scConstant);
349   ID.AddPointer(V);
350   void *IP = nullptr;
351   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
352   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
353   UniqueSCEVs.InsertNode(S, IP);
354   return S;
355 }
356 
357 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
358   return getConstant(ConstantInt::get(getContext(), Val));
359 }
360 
361 const SCEV *
362 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
363   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
364   return getConstant(ConstantInt::get(ITy, V, isSigned));
365 }
366 
367 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
368                            unsigned SCEVTy, const SCEV *op, Type *ty)
369   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
370 
371 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
372                                    const SCEV *op, Type *ty)
373   : SCEVCastExpr(ID, scTruncate, op, ty) {
374   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
375          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
376          "Cannot truncate non-integer value!");
377 }
378 
379 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
380                                        const SCEV *op, Type *ty)
381   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
382   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
383          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
384          "Cannot zero extend non-integer value!");
385 }
386 
387 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
388                                        const SCEV *op, Type *ty)
389   : SCEVCastExpr(ID, scSignExtend, op, ty) {
390   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
391          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
392          "Cannot sign extend non-integer value!");
393 }
394 
395 void SCEVUnknown::deleted() {
396   // Clear this SCEVUnknown from various maps.
397   SE->forgetMemoizedResults(this);
398 
399   // Remove this SCEVUnknown from the uniquing map.
400   SE->UniqueSCEVs.RemoveNode(this);
401 
402   // Release the value.
403   setValPtr(nullptr);
404 }
405 
406 void SCEVUnknown::allUsesReplacedWith(Value *New) {
407   // Clear this SCEVUnknown from various maps.
408   SE->forgetMemoizedResults(this);
409 
410   // Remove this SCEVUnknown from the uniquing map.
411   SE->UniqueSCEVs.RemoveNode(this);
412 
413   // Update this SCEVUnknown to point to the new value. This is needed
414   // because there may still be outstanding SCEVs which still point to
415   // this SCEVUnknown.
416   setValPtr(New);
417 }
418 
419 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
420   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
421     if (VCE->getOpcode() == Instruction::PtrToInt)
422       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
423         if (CE->getOpcode() == Instruction::GetElementPtr &&
424             CE->getOperand(0)->isNullValue() &&
425             CE->getNumOperands() == 2)
426           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
427             if (CI->isOne()) {
428               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
429                                  ->getElementType();
430               return true;
431             }
432 
433   return false;
434 }
435 
436 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
437   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
438     if (VCE->getOpcode() == Instruction::PtrToInt)
439       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
440         if (CE->getOpcode() == Instruction::GetElementPtr &&
441             CE->getOperand(0)->isNullValue()) {
442           Type *Ty =
443             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
444           if (StructType *STy = dyn_cast<StructType>(Ty))
445             if (!STy->isPacked() &&
446                 CE->getNumOperands() == 3 &&
447                 CE->getOperand(1)->isNullValue()) {
448               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
449                 if (CI->isOne() &&
450                     STy->getNumElements() == 2 &&
451                     STy->getElementType(0)->isIntegerTy(1)) {
452                   AllocTy = STy->getElementType(1);
453                   return true;
454                 }
455             }
456         }
457 
458   return false;
459 }
460 
461 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
462   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
463     if (VCE->getOpcode() == Instruction::PtrToInt)
464       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
465         if (CE->getOpcode() == Instruction::GetElementPtr &&
466             CE->getNumOperands() == 3 &&
467             CE->getOperand(0)->isNullValue() &&
468             CE->getOperand(1)->isNullValue()) {
469           Type *Ty =
470             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
471           // Ignore vector types here so that ScalarEvolutionExpander doesn't
472           // emit getelementptrs that index into vectors.
473           if (Ty->isStructTy() || Ty->isArrayTy()) {
474             CTy = Ty;
475             FieldNo = CE->getOperand(2);
476             return true;
477           }
478         }
479 
480   return false;
481 }
482 
483 //===----------------------------------------------------------------------===//
484 //                               SCEV Utilities
485 //===----------------------------------------------------------------------===//
486 
487 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
488 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
489 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
490 /// have been previously deemed to be "equally complex" by this routine.  It is
491 /// intended to avoid exponential time complexity in cases like:
492 ///
493 ///   %a = f(%x, %y)
494 ///   %b = f(%a, %a)
495 ///   %c = f(%b, %b)
496 ///
497 ///   %d = f(%x, %y)
498 ///   %e = f(%d, %d)
499 ///   %f = f(%e, %e)
500 ///
501 ///   CompareValueComplexity(%f, %c)
502 ///
503 /// Since we do not continue running this routine on expression trees once we
504 /// have seen unequal values, there is no need to track them in the cache.
505 static int
506 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
507                        const LoopInfo *const LI, Value *LV, Value *RV,
508                        unsigned Depth) {
509   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
510     return 0;
511 
512   // Order pointer values after integer values. This helps SCEVExpander form
513   // GEPs.
514   bool LIsPointer = LV->getType()->isPointerTy(),
515        RIsPointer = RV->getType()->isPointerTy();
516   if (LIsPointer != RIsPointer)
517     return (int)LIsPointer - (int)RIsPointer;
518 
519   // Compare getValueID values.
520   unsigned LID = LV->getValueID(), RID = RV->getValueID();
521   if (LID != RID)
522     return (int)LID - (int)RID;
523 
524   // Sort arguments by their position.
525   if (const auto *LA = dyn_cast<Argument>(LV)) {
526     const auto *RA = cast<Argument>(RV);
527     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
528     return (int)LArgNo - (int)RArgNo;
529   }
530 
531   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
532     const auto *RGV = cast<GlobalValue>(RV);
533 
534     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
535       auto LT = GV->getLinkage();
536       return !(GlobalValue::isPrivateLinkage(LT) ||
537                GlobalValue::isInternalLinkage(LT));
538     };
539 
540     // Use the names to distinguish the two values, but only if the
541     // names are semantically important.
542     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
543       return LGV->getName().compare(RGV->getName());
544   }
545 
546   // For instructions, compare their loop depth, and their operand count.  This
547   // is pretty loose.
548   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
549     const auto *RInst = cast<Instruction>(RV);
550 
551     // Compare loop depths.
552     const BasicBlock *LParent = LInst->getParent(),
553                      *RParent = RInst->getParent();
554     if (LParent != RParent) {
555       unsigned LDepth = LI->getLoopDepth(LParent),
556                RDepth = LI->getLoopDepth(RParent);
557       if (LDepth != RDepth)
558         return (int)LDepth - (int)RDepth;
559     }
560 
561     // Compare the number of operands.
562     unsigned LNumOps = LInst->getNumOperands(),
563              RNumOps = RInst->getNumOperands();
564     if (LNumOps != RNumOps)
565       return (int)LNumOps - (int)RNumOps;
566 
567     for (unsigned Idx : seq(0u, LNumOps)) {
568       int Result =
569           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
570                                  RInst->getOperand(Idx), Depth + 1);
571       if (Result != 0)
572         return Result;
573     }
574   }
575 
576   EqCache.insert({LV, RV});
577   return 0;
578 }
579 
580 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
581 // than RHS, respectively. A three-way result allows recursive comparisons to be
582 // more efficient.
583 static int CompareSCEVComplexity(
584     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
585     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
586     unsigned Depth = 0) {
587   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
588   if (LHS == RHS)
589     return 0;
590 
591   // Primarily, sort the SCEVs by their getSCEVType().
592   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
593   if (LType != RType)
594     return (int)LType - (int)RType;
595 
596   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
597     return 0;
598   // Aside from the getSCEVType() ordering, the particular ordering
599   // isn't very important except that it's beneficial to be consistent,
600   // so that (a + b) and (b + a) don't end up as different expressions.
601   switch (static_cast<SCEVTypes>(LType)) {
602   case scUnknown: {
603     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
604     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
605 
606     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
607     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
608                                    Depth + 1);
609     if (X == 0)
610       EqCacheSCEV.insert({LHS, RHS});
611     return X;
612   }
613 
614   case scConstant: {
615     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
616     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
617 
618     // Compare constant values.
619     const APInt &LA = LC->getAPInt();
620     const APInt &RA = RC->getAPInt();
621     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
622     if (LBitWidth != RBitWidth)
623       return (int)LBitWidth - (int)RBitWidth;
624     return LA.ult(RA) ? -1 : 1;
625   }
626 
627   case scAddRecExpr: {
628     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
629     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
630 
631     // Compare addrec loop depths.
632     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
633     if (LLoop != RLoop) {
634       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
635       if (LDepth != RDepth)
636         return (int)LDepth - (int)RDepth;
637     }
638 
639     // Addrec complexity grows with operand count.
640     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
641     if (LNumOps != RNumOps)
642       return (int)LNumOps - (int)RNumOps;
643 
644     // Lexicographically compare.
645     for (unsigned i = 0; i != LNumOps; ++i) {
646       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
647                                     RA->getOperand(i), Depth + 1);
648       if (X != 0)
649         return X;
650     }
651     EqCacheSCEV.insert({LHS, RHS});
652     return 0;
653   }
654 
655   case scAddExpr:
656   case scMulExpr:
657   case scSMaxExpr:
658   case scUMaxExpr: {
659     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
660     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
661 
662     // Lexicographically compare n-ary expressions.
663     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
664     if (LNumOps != RNumOps)
665       return (int)LNumOps - (int)RNumOps;
666 
667     for (unsigned i = 0; i != LNumOps; ++i) {
668       if (i >= RNumOps)
669         return 1;
670       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
671                                     RC->getOperand(i), Depth + 1);
672       if (X != 0)
673         return X;
674     }
675     EqCacheSCEV.insert({LHS, RHS});
676     return 0;
677   }
678 
679   case scUDivExpr: {
680     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
681     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
682 
683     // Lexicographically compare udiv expressions.
684     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
685                                   Depth + 1);
686     if (X != 0)
687       return X;
688     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
689                               Depth + 1);
690     if (X == 0)
691       EqCacheSCEV.insert({LHS, RHS});
692     return X;
693   }
694 
695   case scTruncate:
696   case scZeroExtend:
697   case scSignExtend: {
698     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
699     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
700 
701     // Compare cast expressions by operand.
702     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
703                                   RC->getOperand(), Depth + 1);
704     if (X == 0)
705       EqCacheSCEV.insert({LHS, RHS});
706     return X;
707   }
708 
709   case scCouldNotCompute:
710     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
711   }
712   llvm_unreachable("Unknown SCEV kind!");
713 }
714 
715 /// Given a list of SCEV objects, order them by their complexity, and group
716 /// objects of the same complexity together by value.  When this routine is
717 /// finished, we know that any duplicates in the vector are consecutive and that
718 /// complexity is monotonically increasing.
719 ///
720 /// Note that we go take special precautions to ensure that we get deterministic
721 /// results from this routine.  In other words, we don't want the results of
722 /// this to depend on where the addresses of various SCEV objects happened to
723 /// land in memory.
724 ///
725 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
726                               LoopInfo *LI) {
727   if (Ops.size() < 2) return;  // Noop
728 
729   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
730   if (Ops.size() == 2) {
731     // This is the common case, which also happens to be trivially simple.
732     // Special case it.
733     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
734     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
735       std::swap(LHS, RHS);
736     return;
737   }
738 
739   // Do the rough sort by complexity.
740   std::stable_sort(Ops.begin(), Ops.end(),
741                    [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
742                      return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
743                    });
744 
745   // Now that we are sorted by complexity, group elements of the same
746   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
747   // be extremely short in practice.  Note that we take this approach because we
748   // do not want to depend on the addresses of the objects we are grouping.
749   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
750     const SCEV *S = Ops[i];
751     unsigned Complexity = S->getSCEVType();
752 
753     // If there are any objects of the same complexity and same value as this
754     // one, group them.
755     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
756       if (Ops[j] == S) { // Found a duplicate.
757         // Move it to immediately after i'th element.
758         std::swap(Ops[i+1], Ops[j]);
759         ++i;   // no need to rescan it.
760         if (i == e-2) return;  // Done!
761       }
762     }
763   }
764 }
765 
766 // Returns the size of the SCEV S.
767 static inline int sizeOfSCEV(const SCEV *S) {
768   struct FindSCEVSize {
769     int Size;
770     FindSCEVSize() : Size(0) {}
771 
772     bool follow(const SCEV *S) {
773       ++Size;
774       // Keep looking at all operands of S.
775       return true;
776     }
777     bool isDone() const {
778       return false;
779     }
780   };
781 
782   FindSCEVSize F;
783   SCEVTraversal<FindSCEVSize> ST(F);
784   ST.visitAll(S);
785   return F.Size;
786 }
787 
788 namespace {
789 
790 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
791 public:
792   // Computes the Quotient and Remainder of the division of Numerator by
793   // Denominator.
794   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
795                      const SCEV *Denominator, const SCEV **Quotient,
796                      const SCEV **Remainder) {
797     assert(Numerator && Denominator && "Uninitialized SCEV");
798 
799     SCEVDivision D(SE, Numerator, Denominator);
800 
801     // Check for the trivial case here to avoid having to check for it in the
802     // rest of the code.
803     if (Numerator == Denominator) {
804       *Quotient = D.One;
805       *Remainder = D.Zero;
806       return;
807     }
808 
809     if (Numerator->isZero()) {
810       *Quotient = D.Zero;
811       *Remainder = D.Zero;
812       return;
813     }
814 
815     // A simple case when N/1. The quotient is N.
816     if (Denominator->isOne()) {
817       *Quotient = Numerator;
818       *Remainder = D.Zero;
819       return;
820     }
821 
822     // Split the Denominator when it is a product.
823     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
824       const SCEV *Q, *R;
825       *Quotient = Numerator;
826       for (const SCEV *Op : T->operands()) {
827         divide(SE, *Quotient, Op, &Q, &R);
828         *Quotient = Q;
829 
830         // Bail out when the Numerator is not divisible by one of the terms of
831         // the Denominator.
832         if (!R->isZero()) {
833           *Quotient = D.Zero;
834           *Remainder = Numerator;
835           return;
836         }
837       }
838       *Remainder = D.Zero;
839       return;
840     }
841 
842     D.visit(Numerator);
843     *Quotient = D.Quotient;
844     *Remainder = D.Remainder;
845   }
846 
847   // Except in the trivial case described above, we do not know how to divide
848   // Expr by Denominator for the following functions with empty implementation.
849   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
850   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
851   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
852   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
853   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
854   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
855   void visitUnknown(const SCEVUnknown *Numerator) {}
856   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
857 
858   void visitConstant(const SCEVConstant *Numerator) {
859     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
860       APInt NumeratorVal = Numerator->getAPInt();
861       APInt DenominatorVal = D->getAPInt();
862       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
863       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
864 
865       if (NumeratorBW > DenominatorBW)
866         DenominatorVal = DenominatorVal.sext(NumeratorBW);
867       else if (NumeratorBW < DenominatorBW)
868         NumeratorVal = NumeratorVal.sext(DenominatorBW);
869 
870       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
871       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
872       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
873       Quotient = SE.getConstant(QuotientVal);
874       Remainder = SE.getConstant(RemainderVal);
875       return;
876     }
877   }
878 
879   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
880     const SCEV *StartQ, *StartR, *StepQ, *StepR;
881     if (!Numerator->isAffine())
882       return cannotDivide(Numerator);
883     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
884     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
885     // Bail out if the types do not match.
886     Type *Ty = Denominator->getType();
887     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
888         Ty != StepQ->getType() || Ty != StepR->getType())
889       return cannotDivide(Numerator);
890     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
891                                 Numerator->getNoWrapFlags());
892     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
893                                  Numerator->getNoWrapFlags());
894   }
895 
896   void visitAddExpr(const SCEVAddExpr *Numerator) {
897     SmallVector<const SCEV *, 2> Qs, Rs;
898     Type *Ty = Denominator->getType();
899 
900     for (const SCEV *Op : Numerator->operands()) {
901       const SCEV *Q, *R;
902       divide(SE, Op, Denominator, &Q, &R);
903 
904       // Bail out if types do not match.
905       if (Ty != Q->getType() || Ty != R->getType())
906         return cannotDivide(Numerator);
907 
908       Qs.push_back(Q);
909       Rs.push_back(R);
910     }
911 
912     if (Qs.size() == 1) {
913       Quotient = Qs[0];
914       Remainder = Rs[0];
915       return;
916     }
917 
918     Quotient = SE.getAddExpr(Qs);
919     Remainder = SE.getAddExpr(Rs);
920   }
921 
922   void visitMulExpr(const SCEVMulExpr *Numerator) {
923     SmallVector<const SCEV *, 2> Qs;
924     Type *Ty = Denominator->getType();
925 
926     bool FoundDenominatorTerm = false;
927     for (const SCEV *Op : Numerator->operands()) {
928       // Bail out if types do not match.
929       if (Ty != Op->getType())
930         return cannotDivide(Numerator);
931 
932       if (FoundDenominatorTerm) {
933         Qs.push_back(Op);
934         continue;
935       }
936 
937       // Check whether Denominator divides one of the product operands.
938       const SCEV *Q, *R;
939       divide(SE, Op, Denominator, &Q, &R);
940       if (!R->isZero()) {
941         Qs.push_back(Op);
942         continue;
943       }
944 
945       // Bail out if types do not match.
946       if (Ty != Q->getType())
947         return cannotDivide(Numerator);
948 
949       FoundDenominatorTerm = true;
950       Qs.push_back(Q);
951     }
952 
953     if (FoundDenominatorTerm) {
954       Remainder = Zero;
955       if (Qs.size() == 1)
956         Quotient = Qs[0];
957       else
958         Quotient = SE.getMulExpr(Qs);
959       return;
960     }
961 
962     if (!isa<SCEVUnknown>(Denominator))
963       return cannotDivide(Numerator);
964 
965     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
966     ValueToValueMap RewriteMap;
967     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
968         cast<SCEVConstant>(Zero)->getValue();
969     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
970 
971     if (Remainder->isZero()) {
972       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
973       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
974           cast<SCEVConstant>(One)->getValue();
975       Quotient =
976           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
977       return;
978     }
979 
980     // Quotient is (Numerator - Remainder) divided by Denominator.
981     const SCEV *Q, *R;
982     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
983     // This SCEV does not seem to simplify: fail the division here.
984     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
985       return cannotDivide(Numerator);
986     divide(SE, Diff, Denominator, &Q, &R);
987     if (R != Zero)
988       return cannotDivide(Numerator);
989     Quotient = Q;
990   }
991 
992 private:
993   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
994                const SCEV *Denominator)
995       : SE(S), Denominator(Denominator) {
996     Zero = SE.getZero(Denominator->getType());
997     One = SE.getOne(Denominator->getType());
998 
999     // We generally do not know how to divide Expr by Denominator. We
1000     // initialize the division to a "cannot divide" state to simplify the rest
1001     // of the code.
1002     cannotDivide(Numerator);
1003   }
1004 
1005   // Convenience function for giving up on the division. We set the quotient to
1006   // be equal to zero and the remainder to be equal to the numerator.
1007   void cannotDivide(const SCEV *Numerator) {
1008     Quotient = Zero;
1009     Remainder = Numerator;
1010   }
1011 
1012   ScalarEvolution &SE;
1013   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1014 };
1015 
1016 }
1017 
1018 //===----------------------------------------------------------------------===//
1019 //                      Simple SCEV method implementations
1020 //===----------------------------------------------------------------------===//
1021 
1022 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1023 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1024                                        ScalarEvolution &SE,
1025                                        Type *ResultTy) {
1026   // Handle the simplest case efficiently.
1027   if (K == 1)
1028     return SE.getTruncateOrZeroExtend(It, ResultTy);
1029 
1030   // We are using the following formula for BC(It, K):
1031   //
1032   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1033   //
1034   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1035   // overflow.  Hence, we must assure that the result of our computation is
1036   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1037   // safe in modular arithmetic.
1038   //
1039   // However, this code doesn't use exactly that formula; the formula it uses
1040   // is something like the following, where T is the number of factors of 2 in
1041   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1042   // exponentiation:
1043   //
1044   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1045   //
1046   // This formula is trivially equivalent to the previous formula.  However,
1047   // this formula can be implemented much more efficiently.  The trick is that
1048   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1049   // arithmetic.  To do exact division in modular arithmetic, all we have
1050   // to do is multiply by the inverse.  Therefore, this step can be done at
1051   // width W.
1052   //
1053   // The next issue is how to safely do the division by 2^T.  The way this
1054   // is done is by doing the multiplication step at a width of at least W + T
1055   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1056   // when we perform the division by 2^T (which is equivalent to a right shift
1057   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1058   // truncated out after the division by 2^T.
1059   //
1060   // In comparison to just directly using the first formula, this technique
1061   // is much more efficient; using the first formula requires W * K bits,
1062   // but this formula less than W + K bits. Also, the first formula requires
1063   // a division step, whereas this formula only requires multiplies and shifts.
1064   //
1065   // It doesn't matter whether the subtraction step is done in the calculation
1066   // width or the input iteration count's width; if the subtraction overflows,
1067   // the result must be zero anyway.  We prefer here to do it in the width of
1068   // the induction variable because it helps a lot for certain cases; CodeGen
1069   // isn't smart enough to ignore the overflow, which leads to much less
1070   // efficient code if the width of the subtraction is wider than the native
1071   // register width.
1072   //
1073   // (It's possible to not widen at all by pulling out factors of 2 before
1074   // the multiplication; for example, K=2 can be calculated as
1075   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1076   // extra arithmetic, so it's not an obvious win, and it gets
1077   // much more complicated for K > 3.)
1078 
1079   // Protection from insane SCEVs; this bound is conservative,
1080   // but it probably doesn't matter.
1081   if (K > 1000)
1082     return SE.getCouldNotCompute();
1083 
1084   unsigned W = SE.getTypeSizeInBits(ResultTy);
1085 
1086   // Calculate K! / 2^T and T; we divide out the factors of two before
1087   // multiplying for calculating K! / 2^T to avoid overflow.
1088   // Other overflow doesn't matter because we only care about the bottom
1089   // W bits of the result.
1090   APInt OddFactorial(W, 1);
1091   unsigned T = 1;
1092   for (unsigned i = 3; i <= K; ++i) {
1093     APInt Mult(W, i);
1094     unsigned TwoFactors = Mult.countTrailingZeros();
1095     T += TwoFactors;
1096     Mult.lshrInPlace(TwoFactors);
1097     OddFactorial *= Mult;
1098   }
1099 
1100   // We need at least W + T bits for the multiplication step
1101   unsigned CalculationBits = W + T;
1102 
1103   // Calculate 2^T, at width T+W.
1104   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1105 
1106   // Calculate the multiplicative inverse of K! / 2^T;
1107   // this multiplication factor will perform the exact division by
1108   // K! / 2^T.
1109   APInt Mod = APInt::getSignedMinValue(W+1);
1110   APInt MultiplyFactor = OddFactorial.zext(W+1);
1111   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1112   MultiplyFactor = MultiplyFactor.trunc(W);
1113 
1114   // Calculate the product, at width T+W
1115   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1116                                                       CalculationBits);
1117   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1118   for (unsigned i = 1; i != K; ++i) {
1119     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1120     Dividend = SE.getMulExpr(Dividend,
1121                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1122   }
1123 
1124   // Divide by 2^T
1125   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1126 
1127   // Truncate the result, and divide by K! / 2^T.
1128 
1129   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1130                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1131 }
1132 
1133 /// Return the value of this chain of recurrences at the specified iteration
1134 /// number.  We can evaluate this recurrence by multiplying each element in the
1135 /// chain by the binomial coefficient corresponding to it.  In other words, we
1136 /// can evaluate {A,+,B,+,C,+,D} as:
1137 ///
1138 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1139 ///
1140 /// where BC(It, k) stands for binomial coefficient.
1141 ///
1142 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1143                                                 ScalarEvolution &SE) const {
1144   const SCEV *Result = getStart();
1145   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1146     // The computation is correct in the face of overflow provided that the
1147     // multiplication is performed _after_ the evaluation of the binomial
1148     // coefficient.
1149     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1150     if (isa<SCEVCouldNotCompute>(Coeff))
1151       return Coeff;
1152 
1153     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1154   }
1155   return Result;
1156 }
1157 
1158 //===----------------------------------------------------------------------===//
1159 //                    SCEV Expression folder implementations
1160 //===----------------------------------------------------------------------===//
1161 
1162 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1163                                              Type *Ty) {
1164   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1165          "This is not a truncating conversion!");
1166   assert(isSCEVable(Ty) &&
1167          "This is not a conversion to a SCEVable type!");
1168   Ty = getEffectiveSCEVType(Ty);
1169 
1170   FoldingSetNodeID ID;
1171   ID.AddInteger(scTruncate);
1172   ID.AddPointer(Op);
1173   ID.AddPointer(Ty);
1174   void *IP = nullptr;
1175   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1176 
1177   // Fold if the operand is constant.
1178   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1179     return getConstant(
1180       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1181 
1182   // trunc(trunc(x)) --> trunc(x)
1183   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1184     return getTruncateExpr(ST->getOperand(), Ty);
1185 
1186   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1187   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1188     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1189 
1190   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1191   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1192     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1193 
1194   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1195   // eliminate all the truncates, or we replace other casts with truncates.
1196   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1197     SmallVector<const SCEV *, 4> Operands;
1198     bool hasTrunc = false;
1199     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1200       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1201       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1202         hasTrunc = isa<SCEVTruncateExpr>(S);
1203       Operands.push_back(S);
1204     }
1205     if (!hasTrunc)
1206       return getAddExpr(Operands);
1207     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1208   }
1209 
1210   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1211   // eliminate all the truncates, or we replace other casts with truncates.
1212   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1213     SmallVector<const SCEV *, 4> Operands;
1214     bool hasTrunc = false;
1215     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1216       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1217       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1218         hasTrunc = isa<SCEVTruncateExpr>(S);
1219       Operands.push_back(S);
1220     }
1221     if (!hasTrunc)
1222       return getMulExpr(Operands);
1223     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1224   }
1225 
1226   // If the input value is a chrec scev, truncate the chrec's operands.
1227   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1228     SmallVector<const SCEV *, 4> Operands;
1229     for (const SCEV *Op : AddRec->operands())
1230       Operands.push_back(getTruncateExpr(Op, Ty));
1231     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1232   }
1233 
1234   // The cast wasn't folded; create an explicit cast node. We can reuse
1235   // the existing insert position since if we get here, we won't have
1236   // made any changes which would invalidate it.
1237   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1238                                                  Op, Ty);
1239   UniqueSCEVs.InsertNode(S, IP);
1240   return S;
1241 }
1242 
1243 // Get the limit of a recurrence such that incrementing by Step cannot cause
1244 // signed overflow as long as the value of the recurrence within the
1245 // loop does not exceed this limit before incrementing.
1246 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1247                                                  ICmpInst::Predicate *Pred,
1248                                                  ScalarEvolution *SE) {
1249   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1250   if (SE->isKnownPositive(Step)) {
1251     *Pred = ICmpInst::ICMP_SLT;
1252     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1253                            SE->getSignedRange(Step).getSignedMax());
1254   }
1255   if (SE->isKnownNegative(Step)) {
1256     *Pred = ICmpInst::ICMP_SGT;
1257     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1258                            SE->getSignedRange(Step).getSignedMin());
1259   }
1260   return nullptr;
1261 }
1262 
1263 // Get the limit of a recurrence such that incrementing by Step cannot cause
1264 // unsigned overflow as long as the value of the recurrence within the loop does
1265 // not exceed this limit before incrementing.
1266 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1267                                                    ICmpInst::Predicate *Pred,
1268                                                    ScalarEvolution *SE) {
1269   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1270   *Pred = ICmpInst::ICMP_ULT;
1271 
1272   return SE->getConstant(APInt::getMinValue(BitWidth) -
1273                          SE->getUnsignedRange(Step).getUnsignedMax());
1274 }
1275 
1276 namespace {
1277 
1278 struct ExtendOpTraitsBase {
1279   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(
1280       const SCEV *, Type *, ScalarEvolution::ExtendCacheTy &Cache);
1281 };
1282 
1283 // Used to make code generic over signed and unsigned overflow.
1284 template <typename ExtendOp> struct ExtendOpTraits {
1285   // Members present:
1286   //
1287   // static const SCEV::NoWrapFlags WrapType;
1288   //
1289   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1290   //
1291   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1292   //                                           ICmpInst::Predicate *Pred,
1293   //                                           ScalarEvolution *SE);
1294 };
1295 
1296 template <>
1297 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1298   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1299 
1300   static const GetExtendExprTy GetExtendExpr;
1301 
1302   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303                                              ICmpInst::Predicate *Pred,
1304                                              ScalarEvolution *SE) {
1305     return getSignedOverflowLimitForStep(Step, Pred, SE);
1306   }
1307 };
1308 
1309 const ExtendOpTraitsBase::GetExtendExprTy
1310     ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
1311         &ScalarEvolution::getSignExtendExprCached;
1312 
1313 template <>
1314 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1315   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1316 
1317   static const GetExtendExprTy GetExtendExpr;
1318 
1319   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1320                                              ICmpInst::Predicate *Pred,
1321                                              ScalarEvolution *SE) {
1322     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1323   }
1324 };
1325 
1326 const ExtendOpTraitsBase::GetExtendExprTy
1327     ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
1328         &ScalarEvolution::getZeroExtendExprCached;
1329 }
1330 
1331 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1332 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1333 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1334 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1335 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1336 // expression "Step + sext/zext(PreIncAR)" is congruent with
1337 // "sext/zext(PostIncAR)"
1338 template <typename ExtendOpTy>
1339 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1340                                         ScalarEvolution *SE,
1341                                         ScalarEvolution::ExtendCacheTy &Cache) {
1342   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1343   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1344 
1345   const Loop *L = AR->getLoop();
1346   const SCEV *Start = AR->getStart();
1347   const SCEV *Step = AR->getStepRecurrence(*SE);
1348 
1349   // Check for a simple looking step prior to loop entry.
1350   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1351   if (!SA)
1352     return nullptr;
1353 
1354   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1355   // subtraction is expensive. For this purpose, perform a quick and dirty
1356   // difference, by checking for Step in the operand list.
1357   SmallVector<const SCEV *, 4> DiffOps;
1358   for (const SCEV *Op : SA->operands())
1359     if (Op != Step)
1360       DiffOps.push_back(Op);
1361 
1362   if (DiffOps.size() == SA->getNumOperands())
1363     return nullptr;
1364 
1365   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1366   // `Step`:
1367 
1368   // 1. NSW/NUW flags on the step increment.
1369   auto PreStartFlags =
1370     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1371   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1372   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1373       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1374 
1375   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1376   // "S+X does not sign/unsign-overflow".
1377   //
1378 
1379   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1380   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1381       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1382     return PreStart;
1383 
1384   // 2. Direct overflow check on the step operation's expression.
1385   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1386   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1387   const SCEV *OperandExtendedStart =
1388       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Cache),
1389                      (SE->*GetExtendExpr)(Step, WideTy, Cache));
1390   if ((SE->*GetExtendExpr)(Start, WideTy, Cache) == OperandExtendedStart) {
1391     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1392       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1393       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1394       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1395       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1396     }
1397     return PreStart;
1398   }
1399 
1400   // 3. Loop precondition.
1401   ICmpInst::Predicate Pred;
1402   const SCEV *OverflowLimit =
1403       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1404 
1405   if (OverflowLimit &&
1406       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1407     return PreStart;
1408 
1409   return nullptr;
1410 }
1411 
1412 // Get the normalized zero or sign extended expression for this AddRec's Start.
1413 template <typename ExtendOpTy>
1414 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1415                                         ScalarEvolution *SE,
1416                                         ScalarEvolution::ExtendCacheTy &Cache) {
1417   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1418 
1419   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Cache);
1420   if (!PreStart)
1421     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Cache);
1422 
1423   return SE->getAddExpr(
1424       (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Cache),
1425       (SE->*GetExtendExpr)(PreStart, Ty, Cache));
1426 }
1427 
1428 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1429 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1430 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1431 //
1432 // Formally:
1433 //
1434 //     {S,+,X} == {S-T,+,X} + T
1435 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1436 //
1437 // If ({S-T,+,X} + T) does not overflow  ... (1)
1438 //
1439 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1440 //
1441 // If {S-T,+,X} does not overflow  ... (2)
1442 //
1443 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1444 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1445 //
1446 // If (S-T)+T does not overflow  ... (3)
1447 //
1448 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1449 //      == {Ext(S),+,Ext(X)} == LHS
1450 //
1451 // Thus, if (1), (2) and (3) are true for some T, then
1452 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1453 //
1454 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1455 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1456 // to check for (1) and (2).
1457 //
1458 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1459 // is `Delta` (defined below).
1460 //
1461 template <typename ExtendOpTy>
1462 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1463                                                 const SCEV *Step,
1464                                                 const Loop *L) {
1465   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1466 
1467   // We restrict `Start` to a constant to prevent SCEV from spending too much
1468   // time here.  It is correct (but more expensive) to continue with a
1469   // non-constant `Start` and do a general SCEV subtraction to compute
1470   // `PreStart` below.
1471   //
1472   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1473   if (!StartC)
1474     return false;
1475 
1476   APInt StartAI = StartC->getAPInt();
1477 
1478   for (unsigned Delta : {-2, -1, 1, 2}) {
1479     const SCEV *PreStart = getConstant(StartAI - Delta);
1480 
1481     FoldingSetNodeID ID;
1482     ID.AddInteger(scAddRecExpr);
1483     ID.AddPointer(PreStart);
1484     ID.AddPointer(Step);
1485     ID.AddPointer(L);
1486     void *IP = nullptr;
1487     const auto *PreAR =
1488       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1489 
1490     // Give up if we don't already have the add recurrence we need because
1491     // actually constructing an add recurrence is relatively expensive.
1492     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1493       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1494       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1495       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1496           DeltaS, &Pred, this);
1497       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1498         return true;
1499     }
1500   }
1501 
1502   return false;
1503 }
1504 
1505 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty) {
1506   // Use the local cache to prevent exponential behavior of
1507   // getZeroExtendExprImpl.
1508   ExtendCacheTy Cache;
1509   return getZeroExtendExprCached(Op, Ty, Cache);
1510 }
1511 
1512 /// Query \p Cache before calling getZeroExtendExprImpl. If there is no
1513 /// related entry in the \p Cache, call getZeroExtendExprImpl and save
1514 /// the result in the \p Cache.
1515 const SCEV *ScalarEvolution::getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1516                                                      ExtendCacheTy &Cache) {
1517   auto It = Cache.find({Op, Ty});
1518   if (It != Cache.end())
1519     return It->second;
1520   const SCEV *ZExt = getZeroExtendExprImpl(Op, Ty, Cache);
1521   auto InsertResult = Cache.insert({{Op, Ty}, ZExt});
1522   assert(InsertResult.second && "Expect the key was not in the cache");
1523   (void)InsertResult;
1524   return ZExt;
1525 }
1526 
1527 /// The real implementation of getZeroExtendExpr.
1528 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1529                                                    ExtendCacheTy &Cache) {
1530   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1531          "This is not an extending conversion!");
1532   assert(isSCEVable(Ty) &&
1533          "This is not a conversion to a SCEVable type!");
1534   Ty = getEffectiveSCEVType(Ty);
1535 
1536   // Fold if the operand is constant.
1537   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1538     return getConstant(
1539         cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1540 
1541   // zext(zext(x)) --> zext(x)
1542   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1543     return getZeroExtendExprCached(SZ->getOperand(), Ty, Cache);
1544 
1545   // Before doing any expensive analysis, check to see if we've already
1546   // computed a SCEV for this Op and Ty.
1547   FoldingSetNodeID ID;
1548   ID.AddInteger(scZeroExtend);
1549   ID.AddPointer(Op);
1550   ID.AddPointer(Ty);
1551   void *IP = nullptr;
1552   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1553 
1554   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1555   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1556     // It's possible the bits taken off by the truncate were all zero bits. If
1557     // so, we should be able to simplify this further.
1558     const SCEV *X = ST->getOperand();
1559     ConstantRange CR = getUnsignedRange(X);
1560     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1561     unsigned NewBits = getTypeSizeInBits(Ty);
1562     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1563             CR.zextOrTrunc(NewBits)))
1564       return getTruncateOrZeroExtend(X, Ty);
1565   }
1566 
1567   // If the input value is a chrec scev, and we can prove that the value
1568   // did not overflow the old, smaller, value, we can zero extend all of the
1569   // operands (often constants).  This allows analysis of something like
1570   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1571   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1572     if (AR->isAffine()) {
1573       const SCEV *Start = AR->getStart();
1574       const SCEV *Step = AR->getStepRecurrence(*this);
1575       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1576       const Loop *L = AR->getLoop();
1577 
1578       if (!AR->hasNoUnsignedWrap()) {
1579         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1580         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1581       }
1582 
1583       // If we have special knowledge that this addrec won't overflow,
1584       // we don't need to do any further analysis.
1585       if (AR->hasNoUnsignedWrap())
1586         return getAddRecExpr(
1587             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1588             getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1589 
1590       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1591       // Note that this serves two purposes: It filters out loops that are
1592       // simply not analyzable, and it covers the case where this code is
1593       // being called from within backedge-taken count analysis, such that
1594       // attempting to ask for the backedge-taken count would likely result
1595       // in infinite recursion. In the later case, the analysis code will
1596       // cope with a conservative value, and it will take care to purge
1597       // that value once it has finished.
1598       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1599       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1600         // Manually compute the final value for AR, checking for
1601         // overflow.
1602 
1603         // Check whether the backedge-taken count can be losslessly casted to
1604         // the addrec's type. The count is always unsigned.
1605         const SCEV *CastedMaxBECount =
1606           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1607         const SCEV *RecastedMaxBECount =
1608           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1609         if (MaxBECount == RecastedMaxBECount) {
1610           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1611           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1612           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1613           const SCEV *ZAdd =
1614               getZeroExtendExprCached(getAddExpr(Start, ZMul), WideTy, Cache);
1615           const SCEV *WideStart = getZeroExtendExprCached(Start, WideTy, Cache);
1616           const SCEV *WideMaxBECount =
1617               getZeroExtendExprCached(CastedMaxBECount, WideTy, Cache);
1618           const SCEV *OperandExtendedAdd = getAddExpr(
1619               WideStart, getMulExpr(WideMaxBECount, getZeroExtendExprCached(
1620                                                         Step, WideTy, Cache)));
1621           if (ZAdd == OperandExtendedAdd) {
1622             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1623             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1624             // Return the expression with the addrec on the outside.
1625             return getAddRecExpr(
1626                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1627                 getZeroExtendExprCached(Step, Ty, Cache), L,
1628                 AR->getNoWrapFlags());
1629           }
1630           // Similar to above, only this time treat the step value as signed.
1631           // This covers loops that count down.
1632           OperandExtendedAdd =
1633             getAddExpr(WideStart,
1634                        getMulExpr(WideMaxBECount,
1635                                   getSignExtendExpr(Step, WideTy)));
1636           if (ZAdd == OperandExtendedAdd) {
1637             // Cache knowledge of AR NW, which is propagated to this AddRec.
1638             // Negative step causes unsigned wrap, but it still can't self-wrap.
1639             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1640             // Return the expression with the addrec on the outside.
1641             return getAddRecExpr(
1642                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1643                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1644           }
1645         }
1646       }
1647 
1648       // Normally, in the cases we can prove no-overflow via a
1649       // backedge guarding condition, we can also compute a backedge
1650       // taken count for the loop.  The exceptions are assumptions and
1651       // guards present in the loop -- SCEV is not great at exploiting
1652       // these to compute max backedge taken counts, but can still use
1653       // these to prove lack of overflow.  Use this fact to avoid
1654       // doing extra work that may not pay off.
1655       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1656           !AC.assumptions().empty()) {
1657         // If the backedge is guarded by a comparison with the pre-inc
1658         // value the addrec is safe. Also, if the entry is guarded by
1659         // a comparison with the start value and the backedge is
1660         // guarded by a comparison with the post-inc value, the addrec
1661         // is safe.
1662         if (isKnownPositive(Step)) {
1663           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1664                                       getUnsignedRange(Step).getUnsignedMax());
1665           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1666               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1667                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1668                                            AR->getPostIncExpr(*this), N))) {
1669             // Cache knowledge of AR NUW, which is propagated to this
1670             // AddRec.
1671             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1672             // Return the expression with the addrec on the outside.
1673             return getAddRecExpr(
1674                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1675                 getZeroExtendExprCached(Step, Ty, Cache), L,
1676                 AR->getNoWrapFlags());
1677           }
1678         } else if (isKnownNegative(Step)) {
1679           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1680                                       getSignedRange(Step).getSignedMin());
1681           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1682               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1683                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1684                                            AR->getPostIncExpr(*this), N))) {
1685             // Cache knowledge of AR NW, which is propagated to this
1686             // AddRec.  Negative step causes unsigned wrap, but it
1687             // still can't self-wrap.
1688             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1689             // Return the expression with the addrec on the outside.
1690             return getAddRecExpr(
1691                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1692                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1693           }
1694         }
1695       }
1696 
1697       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1698         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1699         return getAddRecExpr(
1700             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Cache),
1701             getZeroExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1702       }
1703     }
1704 
1705   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1706     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1707     if (SA->hasNoUnsignedWrap()) {
1708       // If the addition does not unsign overflow then we can, by definition,
1709       // commute the zero extension with the addition operation.
1710       SmallVector<const SCEV *, 4> Ops;
1711       for (const auto *Op : SA->operands())
1712         Ops.push_back(getZeroExtendExprCached(Op, Ty, Cache));
1713       return getAddExpr(Ops, SCEV::FlagNUW);
1714     }
1715   }
1716 
1717   // The cast wasn't folded; create an explicit cast node.
1718   // Recompute the insert position, as it may have been invalidated.
1719   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1720   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1721                                                    Op, Ty);
1722   UniqueSCEVs.InsertNode(S, IP);
1723   return S;
1724 }
1725 
1726 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty) {
1727   // Use the local cache to prevent exponential behavior of
1728   // getSignExtendExprImpl.
1729   ExtendCacheTy Cache;
1730   return getSignExtendExprCached(Op, Ty, Cache);
1731 }
1732 
1733 /// Query \p Cache before calling getSignExtendExprImpl. If there is no
1734 /// related entry in the \p Cache, call getSignExtendExprImpl and save
1735 /// the result in the \p Cache.
1736 const SCEV *ScalarEvolution::getSignExtendExprCached(const SCEV *Op, Type *Ty,
1737                                                      ExtendCacheTy &Cache) {
1738   auto It = Cache.find({Op, Ty});
1739   if (It != Cache.end())
1740     return It->second;
1741   const SCEV *SExt = getSignExtendExprImpl(Op, Ty, Cache);
1742   auto InsertResult = Cache.insert({{Op, Ty}, SExt});
1743   assert(InsertResult.second && "Expect the key was not in the cache");
1744   (void)InsertResult;
1745   return SExt;
1746 }
1747 
1748 /// The real implementation of getSignExtendExpr.
1749 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1750                                                    ExtendCacheTy &Cache) {
1751   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1752          "This is not an extending conversion!");
1753   assert(isSCEVable(Ty) &&
1754          "This is not a conversion to a SCEVable type!");
1755   Ty = getEffectiveSCEVType(Ty);
1756 
1757   // Fold if the operand is constant.
1758   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1759     return getConstant(
1760         cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1761 
1762   // sext(sext(x)) --> sext(x)
1763   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1764     return getSignExtendExprCached(SS->getOperand(), Ty, Cache);
1765 
1766   // sext(zext(x)) --> zext(x)
1767   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1768     return getZeroExtendExpr(SZ->getOperand(), Ty);
1769 
1770   // Before doing any expensive analysis, check to see if we've already
1771   // computed a SCEV for this Op and Ty.
1772   FoldingSetNodeID ID;
1773   ID.AddInteger(scSignExtend);
1774   ID.AddPointer(Op);
1775   ID.AddPointer(Ty);
1776   void *IP = nullptr;
1777   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1778 
1779   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1780   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1781     // It's possible the bits taken off by the truncate were all sign bits. If
1782     // so, we should be able to simplify this further.
1783     const SCEV *X = ST->getOperand();
1784     ConstantRange CR = getSignedRange(X);
1785     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1786     unsigned NewBits = getTypeSizeInBits(Ty);
1787     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1788             CR.sextOrTrunc(NewBits)))
1789       return getTruncateOrSignExtend(X, Ty);
1790   }
1791 
1792   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1793   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1794     if (SA->getNumOperands() == 2) {
1795       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1796       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1797       if (SMul && SC1) {
1798         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1799           const APInt &C1 = SC1->getAPInt();
1800           const APInt &C2 = SC2->getAPInt();
1801           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1802               C2.ugt(C1) && C2.isPowerOf2())
1803             return getAddExpr(getSignExtendExprCached(SC1, Ty, Cache),
1804                               getSignExtendExprCached(SMul, Ty, Cache));
1805         }
1806       }
1807     }
1808 
1809     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1810     if (SA->hasNoSignedWrap()) {
1811       // If the addition does not sign overflow then we can, by definition,
1812       // commute the sign extension with the addition operation.
1813       SmallVector<const SCEV *, 4> Ops;
1814       for (const auto *Op : SA->operands())
1815         Ops.push_back(getSignExtendExprCached(Op, Ty, Cache));
1816       return getAddExpr(Ops, SCEV::FlagNSW);
1817     }
1818   }
1819   // If the input value is a chrec scev, and we can prove that the value
1820   // did not overflow the old, smaller, value, we can sign extend all of the
1821   // operands (often constants).  This allows analysis of something like
1822   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1823   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1824     if (AR->isAffine()) {
1825       const SCEV *Start = AR->getStart();
1826       const SCEV *Step = AR->getStepRecurrence(*this);
1827       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1828       const Loop *L = AR->getLoop();
1829 
1830       if (!AR->hasNoSignedWrap()) {
1831         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1832         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1833       }
1834 
1835       // If we have special knowledge that this addrec won't overflow,
1836       // we don't need to do any further analysis.
1837       if (AR->hasNoSignedWrap())
1838         return getAddRecExpr(
1839             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1840             getSignExtendExprCached(Step, Ty, Cache), L, SCEV::FlagNSW);
1841 
1842       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1843       // Note that this serves two purposes: It filters out loops that are
1844       // simply not analyzable, and it covers the case where this code is
1845       // being called from within backedge-taken count analysis, such that
1846       // attempting to ask for the backedge-taken count would likely result
1847       // in infinite recursion. In the later case, the analysis code will
1848       // cope with a conservative value, and it will take care to purge
1849       // that value once it has finished.
1850       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1851       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1852         // Manually compute the final value for AR, checking for
1853         // overflow.
1854 
1855         // Check whether the backedge-taken count can be losslessly casted to
1856         // the addrec's type. The count is always unsigned.
1857         const SCEV *CastedMaxBECount =
1858           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1859         const SCEV *RecastedMaxBECount =
1860           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1861         if (MaxBECount == RecastedMaxBECount) {
1862           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1863           // Check whether Start+Step*MaxBECount has no signed overflow.
1864           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1865           const SCEV *SAdd =
1866               getSignExtendExprCached(getAddExpr(Start, SMul), WideTy, Cache);
1867           const SCEV *WideStart = getSignExtendExprCached(Start, WideTy, Cache);
1868           const SCEV *WideMaxBECount =
1869               getZeroExtendExpr(CastedMaxBECount, WideTy);
1870           const SCEV *OperandExtendedAdd = getAddExpr(
1871               WideStart, getMulExpr(WideMaxBECount, getSignExtendExprCached(
1872                                                         Step, WideTy, Cache)));
1873           if (SAdd == OperandExtendedAdd) {
1874             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1875             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1876             // Return the expression with the addrec on the outside.
1877             return getAddRecExpr(
1878                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1879                 getSignExtendExprCached(Step, Ty, Cache), L,
1880                 AR->getNoWrapFlags());
1881           }
1882           // Similar to above, only this time treat the step value as unsigned.
1883           // This covers loops that count up with an unsigned step.
1884           OperandExtendedAdd =
1885             getAddExpr(WideStart,
1886                        getMulExpr(WideMaxBECount,
1887                                   getZeroExtendExpr(Step, WideTy)));
1888           if (SAdd == OperandExtendedAdd) {
1889             // If AR wraps around then
1890             //
1891             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1892             // => SAdd != OperandExtendedAdd
1893             //
1894             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1895             // (SAdd == OperandExtendedAdd => AR is NW)
1896 
1897             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1898 
1899             // Return the expression with the addrec on the outside.
1900             return getAddRecExpr(
1901                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1902                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1903           }
1904         }
1905       }
1906 
1907       // Normally, in the cases we can prove no-overflow via a
1908       // backedge guarding condition, we can also compute a backedge
1909       // taken count for the loop.  The exceptions are assumptions and
1910       // guards present in the loop -- SCEV is not great at exploiting
1911       // these to compute max backedge taken counts, but can still use
1912       // these to prove lack of overflow.  Use this fact to avoid
1913       // doing extra work that may not pay off.
1914 
1915       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1916           !AC.assumptions().empty()) {
1917         // If the backedge is guarded by a comparison with the pre-inc
1918         // value the addrec is safe. Also, if the entry is guarded by
1919         // a comparison with the start value and the backedge is
1920         // guarded by a comparison with the post-inc value, the addrec
1921         // is safe.
1922         ICmpInst::Predicate Pred;
1923         const SCEV *OverflowLimit =
1924             getSignedOverflowLimitForStep(Step, &Pred, this);
1925         if (OverflowLimit &&
1926             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1927              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1928               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1929                                           OverflowLimit)))) {
1930           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1931           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1932           return getAddRecExpr(
1933               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1934               getSignExtendExprCached(Step, Ty, Cache), L,
1935               AR->getNoWrapFlags());
1936         }
1937       }
1938 
1939       // If Start and Step are constants, check if we can apply this
1940       // transformation:
1941       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1942       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1943       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1944       if (SC1 && SC2) {
1945         const APInt &C1 = SC1->getAPInt();
1946         const APInt &C2 = SC2->getAPInt();
1947         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1948             C2.isPowerOf2()) {
1949           Start = getSignExtendExprCached(Start, Ty, Cache);
1950           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1951                                             AR->getNoWrapFlags());
1952           return getAddExpr(Start, getSignExtendExprCached(NewAR, Ty, Cache));
1953         }
1954       }
1955 
1956       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1957         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1958         return getAddRecExpr(
1959             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Cache),
1960             getSignExtendExprCached(Step, Ty, Cache), L, AR->getNoWrapFlags());
1961       }
1962     }
1963 
1964   // If the input value is provably positive and we could not simplify
1965   // away the sext build a zext instead.
1966   if (isKnownNonNegative(Op))
1967     return getZeroExtendExpr(Op, Ty);
1968 
1969   // The cast wasn't folded; create an explicit cast node.
1970   // Recompute the insert position, as it may have been invalidated.
1971   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1972   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1973                                                    Op, Ty);
1974   UniqueSCEVs.InsertNode(S, IP);
1975   return S;
1976 }
1977 
1978 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1979 /// unspecified bits out to the given type.
1980 ///
1981 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1982                                               Type *Ty) {
1983   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1984          "This is not an extending conversion!");
1985   assert(isSCEVable(Ty) &&
1986          "This is not a conversion to a SCEVable type!");
1987   Ty = getEffectiveSCEVType(Ty);
1988 
1989   // Sign-extend negative constants.
1990   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1991     if (SC->getAPInt().isNegative())
1992       return getSignExtendExpr(Op, Ty);
1993 
1994   // Peel off a truncate cast.
1995   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1996     const SCEV *NewOp = T->getOperand();
1997     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1998       return getAnyExtendExpr(NewOp, Ty);
1999     return getTruncateOrNoop(NewOp, Ty);
2000   }
2001 
2002   // Next try a zext cast. If the cast is folded, use it.
2003   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2004   if (!isa<SCEVZeroExtendExpr>(ZExt))
2005     return ZExt;
2006 
2007   // Next try a sext cast. If the cast is folded, use it.
2008   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2009   if (!isa<SCEVSignExtendExpr>(SExt))
2010     return SExt;
2011 
2012   // Force the cast to be folded into the operands of an addrec.
2013   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2014     SmallVector<const SCEV *, 4> Ops;
2015     for (const SCEV *Op : AR->operands())
2016       Ops.push_back(getAnyExtendExpr(Op, Ty));
2017     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2018   }
2019 
2020   // If the expression is obviously signed, use the sext cast value.
2021   if (isa<SCEVSMaxExpr>(Op))
2022     return SExt;
2023 
2024   // Absent any other information, use the zext cast value.
2025   return ZExt;
2026 }
2027 
2028 /// Process the given Ops list, which is a list of operands to be added under
2029 /// the given scale, update the given map. This is a helper function for
2030 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2031 /// that would form an add expression like this:
2032 ///
2033 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2034 ///
2035 /// where A and B are constants, update the map with these values:
2036 ///
2037 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2038 ///
2039 /// and add 13 + A*B*29 to AccumulatedConstant.
2040 /// This will allow getAddRecExpr to produce this:
2041 ///
2042 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2043 ///
2044 /// This form often exposes folding opportunities that are hidden in
2045 /// the original operand list.
2046 ///
2047 /// Return true iff it appears that any interesting folding opportunities
2048 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2049 /// the common case where no interesting opportunities are present, and
2050 /// is also used as a check to avoid infinite recursion.
2051 ///
2052 static bool
2053 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2054                              SmallVectorImpl<const SCEV *> &NewOps,
2055                              APInt &AccumulatedConstant,
2056                              const SCEV *const *Ops, size_t NumOperands,
2057                              const APInt &Scale,
2058                              ScalarEvolution &SE) {
2059   bool Interesting = false;
2060 
2061   // Iterate over the add operands. They are sorted, with constants first.
2062   unsigned i = 0;
2063   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2064     ++i;
2065     // Pull a buried constant out to the outside.
2066     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2067       Interesting = true;
2068     AccumulatedConstant += Scale * C->getAPInt();
2069   }
2070 
2071   // Next comes everything else. We're especially interested in multiplies
2072   // here, but they're in the middle, so just visit the rest with one loop.
2073   for (; i != NumOperands; ++i) {
2074     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2075     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2076       APInt NewScale =
2077           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2078       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2079         // A multiplication of a constant with another add; recurse.
2080         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2081         Interesting |=
2082           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2083                                        Add->op_begin(), Add->getNumOperands(),
2084                                        NewScale, SE);
2085       } else {
2086         // A multiplication of a constant with some other value. Update
2087         // the map.
2088         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2089         const SCEV *Key = SE.getMulExpr(MulOps);
2090         auto Pair = M.insert({Key, NewScale});
2091         if (Pair.second) {
2092           NewOps.push_back(Pair.first->first);
2093         } else {
2094           Pair.first->second += NewScale;
2095           // The map already had an entry for this value, which may indicate
2096           // a folding opportunity.
2097           Interesting = true;
2098         }
2099       }
2100     } else {
2101       // An ordinary operand. Update the map.
2102       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2103           M.insert({Ops[i], Scale});
2104       if (Pair.second) {
2105         NewOps.push_back(Pair.first->first);
2106       } else {
2107         Pair.first->second += Scale;
2108         // The map already had an entry for this value, which may indicate
2109         // a folding opportunity.
2110         Interesting = true;
2111       }
2112     }
2113   }
2114 
2115   return Interesting;
2116 }
2117 
2118 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2119 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2120 // can't-overflow flags for the operation if possible.
2121 static SCEV::NoWrapFlags
2122 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2123                       const SmallVectorImpl<const SCEV *> &Ops,
2124                       SCEV::NoWrapFlags Flags) {
2125   using namespace std::placeholders;
2126   typedef OverflowingBinaryOperator OBO;
2127 
2128   bool CanAnalyze =
2129       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2130   (void)CanAnalyze;
2131   assert(CanAnalyze && "don't call from other places!");
2132 
2133   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2134   SCEV::NoWrapFlags SignOrUnsignWrap =
2135       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2136 
2137   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2138   auto IsKnownNonNegative = [&](const SCEV *S) {
2139     return SE->isKnownNonNegative(S);
2140   };
2141 
2142   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2143     Flags =
2144         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2145 
2146   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2147 
2148   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2149       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2150 
2151     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2152     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2153 
2154     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2155     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2156       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2157           Instruction::Add, C, OBO::NoSignedWrap);
2158       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2159         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2160     }
2161     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2162       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2163           Instruction::Add, C, OBO::NoUnsignedWrap);
2164       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2165         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2166     }
2167   }
2168 
2169   return Flags;
2170 }
2171 
2172 /// Get a canonical add expression, or something simpler if possible.
2173 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2174                                         SCEV::NoWrapFlags Flags,
2175                                         unsigned Depth) {
2176   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2177          "only nuw or nsw allowed");
2178   assert(!Ops.empty() && "Cannot get empty add!");
2179   if (Ops.size() == 1) return Ops[0];
2180 #ifndef NDEBUG
2181   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2182   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2183     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2184            "SCEVAddExpr operand types don't match!");
2185 #endif
2186 
2187   // Sort by complexity, this groups all similar expression types together.
2188   GroupByComplexity(Ops, &LI);
2189 
2190   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2191 
2192   // If there are any constants, fold them together.
2193   unsigned Idx = 0;
2194   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2195     ++Idx;
2196     assert(Idx < Ops.size());
2197     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2198       // We found two constants, fold them together!
2199       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2200       if (Ops.size() == 2) return Ops[0];
2201       Ops.erase(Ops.begin()+1);  // Erase the folded element
2202       LHSC = cast<SCEVConstant>(Ops[0]);
2203     }
2204 
2205     // If we are left with a constant zero being added, strip it off.
2206     if (LHSC->getValue()->isZero()) {
2207       Ops.erase(Ops.begin());
2208       --Idx;
2209     }
2210 
2211     if (Ops.size() == 1) return Ops[0];
2212   }
2213 
2214   // Limit recursion calls depth
2215   if (Depth > MaxAddExprDepth)
2216     return getOrCreateAddExpr(Ops, Flags);
2217 
2218   // Okay, check to see if the same value occurs in the operand list more than
2219   // once.  If so, merge them together into an multiply expression.  Since we
2220   // sorted the list, these values are required to be adjacent.
2221   Type *Ty = Ops[0]->getType();
2222   bool FoundMatch = false;
2223   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2224     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2225       // Scan ahead to count how many equal operands there are.
2226       unsigned Count = 2;
2227       while (i+Count != e && Ops[i+Count] == Ops[i])
2228         ++Count;
2229       // Merge the values into a multiply.
2230       const SCEV *Scale = getConstant(Ty, Count);
2231       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2232       if (Ops.size() == Count)
2233         return Mul;
2234       Ops[i] = Mul;
2235       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2236       --i; e -= Count - 1;
2237       FoundMatch = true;
2238     }
2239   if (FoundMatch)
2240     return getAddExpr(Ops, Flags);
2241 
2242   // Check for truncates. If all the operands are truncated from the same
2243   // type, see if factoring out the truncate would permit the result to be
2244   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2245   // if the contents of the resulting outer trunc fold to something simple.
2246   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2247     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2248     Type *DstType = Trunc->getType();
2249     Type *SrcType = Trunc->getOperand()->getType();
2250     SmallVector<const SCEV *, 8> LargeOps;
2251     bool Ok = true;
2252     // Check all the operands to see if they can be represented in the
2253     // source type of the truncate.
2254     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2255       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2256         if (T->getOperand()->getType() != SrcType) {
2257           Ok = false;
2258           break;
2259         }
2260         LargeOps.push_back(T->getOperand());
2261       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2262         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2263       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2264         SmallVector<const SCEV *, 8> LargeMulOps;
2265         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2266           if (const SCEVTruncateExpr *T =
2267                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2268             if (T->getOperand()->getType() != SrcType) {
2269               Ok = false;
2270               break;
2271             }
2272             LargeMulOps.push_back(T->getOperand());
2273           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2274             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2275           } else {
2276             Ok = false;
2277             break;
2278           }
2279         }
2280         if (Ok)
2281           LargeOps.push_back(getMulExpr(LargeMulOps));
2282       } else {
2283         Ok = false;
2284         break;
2285       }
2286     }
2287     if (Ok) {
2288       // Evaluate the expression in the larger type.
2289       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2290       // If it folds to something simple, use it. Otherwise, don't.
2291       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2292         return getTruncateExpr(Fold, DstType);
2293     }
2294   }
2295 
2296   // Skip past any other cast SCEVs.
2297   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2298     ++Idx;
2299 
2300   // If there are add operands they would be next.
2301   if (Idx < Ops.size()) {
2302     bool DeletedAdd = false;
2303     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2304       if (Ops.size() > AddOpsInlineThreshold ||
2305           Add->getNumOperands() > AddOpsInlineThreshold)
2306         break;
2307       // If we have an add, expand the add operands onto the end of the operands
2308       // list.
2309       Ops.erase(Ops.begin()+Idx);
2310       Ops.append(Add->op_begin(), Add->op_end());
2311       DeletedAdd = true;
2312     }
2313 
2314     // If we deleted at least one add, we added operands to the end of the list,
2315     // and they are not necessarily sorted.  Recurse to resort and resimplify
2316     // any operands we just acquired.
2317     if (DeletedAdd)
2318       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2319   }
2320 
2321   // Skip over the add expression until we get to a multiply.
2322   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2323     ++Idx;
2324 
2325   // Check to see if there are any folding opportunities present with
2326   // operands multiplied by constant values.
2327   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2328     uint64_t BitWidth = getTypeSizeInBits(Ty);
2329     DenseMap<const SCEV *, APInt> M;
2330     SmallVector<const SCEV *, 8> NewOps;
2331     APInt AccumulatedConstant(BitWidth, 0);
2332     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2333                                      Ops.data(), Ops.size(),
2334                                      APInt(BitWidth, 1), *this)) {
2335       struct APIntCompare {
2336         bool operator()(const APInt &LHS, const APInt &RHS) const {
2337           return LHS.ult(RHS);
2338         }
2339       };
2340 
2341       // Some interesting folding opportunity is present, so its worthwhile to
2342       // re-generate the operands list. Group the operands by constant scale,
2343       // to avoid multiplying by the same constant scale multiple times.
2344       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2345       for (const SCEV *NewOp : NewOps)
2346         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2347       // Re-generate the operands list.
2348       Ops.clear();
2349       if (AccumulatedConstant != 0)
2350         Ops.push_back(getConstant(AccumulatedConstant));
2351       for (auto &MulOp : MulOpLists)
2352         if (MulOp.first != 0)
2353           Ops.push_back(getMulExpr(
2354               getConstant(MulOp.first),
2355               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)));
2356       if (Ops.empty())
2357         return getZero(Ty);
2358       if (Ops.size() == 1)
2359         return Ops[0];
2360       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2361     }
2362   }
2363 
2364   // If we are adding something to a multiply expression, make sure the
2365   // something is not already an operand of the multiply.  If so, merge it into
2366   // the multiply.
2367   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2368     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2369     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2370       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2371       if (isa<SCEVConstant>(MulOpSCEV))
2372         continue;
2373       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2374         if (MulOpSCEV == Ops[AddOp]) {
2375           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2376           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2377           if (Mul->getNumOperands() != 2) {
2378             // If the multiply has more than two operands, we must get the
2379             // Y*Z term.
2380             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2381                                                 Mul->op_begin()+MulOp);
2382             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2383             InnerMul = getMulExpr(MulOps);
2384           }
2385           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2386           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2387           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2388           if (Ops.size() == 2) return OuterMul;
2389           if (AddOp < Idx) {
2390             Ops.erase(Ops.begin()+AddOp);
2391             Ops.erase(Ops.begin()+Idx-1);
2392           } else {
2393             Ops.erase(Ops.begin()+Idx);
2394             Ops.erase(Ops.begin()+AddOp-1);
2395           }
2396           Ops.push_back(OuterMul);
2397           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2398         }
2399 
2400       // Check this multiply against other multiplies being added together.
2401       for (unsigned OtherMulIdx = Idx+1;
2402            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2403            ++OtherMulIdx) {
2404         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2405         // If MulOp occurs in OtherMul, we can fold the two multiplies
2406         // together.
2407         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2408              OMulOp != e; ++OMulOp)
2409           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2410             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2411             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2412             if (Mul->getNumOperands() != 2) {
2413               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2414                                                   Mul->op_begin()+MulOp);
2415               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2416               InnerMul1 = getMulExpr(MulOps);
2417             }
2418             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2419             if (OtherMul->getNumOperands() != 2) {
2420               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2421                                                   OtherMul->op_begin()+OMulOp);
2422               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2423               InnerMul2 = getMulExpr(MulOps);
2424             }
2425             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2426             const SCEV *InnerMulSum =
2427                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2428             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2429             if (Ops.size() == 2) return OuterMul;
2430             Ops.erase(Ops.begin()+Idx);
2431             Ops.erase(Ops.begin()+OtherMulIdx-1);
2432             Ops.push_back(OuterMul);
2433             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2434           }
2435       }
2436     }
2437   }
2438 
2439   // If there are any add recurrences in the operands list, see if any other
2440   // added values are loop invariant.  If so, we can fold them into the
2441   // recurrence.
2442   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2443     ++Idx;
2444 
2445   // Scan over all recurrences, trying to fold loop invariants into them.
2446   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2447     // Scan all of the other operands to this add and add them to the vector if
2448     // they are loop invariant w.r.t. the recurrence.
2449     SmallVector<const SCEV *, 8> LIOps;
2450     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2451     const Loop *AddRecLoop = AddRec->getLoop();
2452     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2453       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2454         LIOps.push_back(Ops[i]);
2455         Ops.erase(Ops.begin()+i);
2456         --i; --e;
2457       }
2458 
2459     // If we found some loop invariants, fold them into the recurrence.
2460     if (!LIOps.empty()) {
2461       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2462       LIOps.push_back(AddRec->getStart());
2463 
2464       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2465                                              AddRec->op_end());
2466       // This follows from the fact that the no-wrap flags on the outer add
2467       // expression are applicable on the 0th iteration, when the add recurrence
2468       // will be equal to its start value.
2469       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2470 
2471       // Build the new addrec. Propagate the NUW and NSW flags if both the
2472       // outer add and the inner addrec are guaranteed to have no overflow.
2473       // Always propagate NW.
2474       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2475       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2476 
2477       // If all of the other operands were loop invariant, we are done.
2478       if (Ops.size() == 1) return NewRec;
2479 
2480       // Otherwise, add the folded AddRec by the non-invariant parts.
2481       for (unsigned i = 0;; ++i)
2482         if (Ops[i] == AddRec) {
2483           Ops[i] = NewRec;
2484           break;
2485         }
2486       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2487     }
2488 
2489     // Okay, if there weren't any loop invariants to be folded, check to see if
2490     // there are multiple AddRec's with the same loop induction variable being
2491     // added together.  If so, we can fold them.
2492     for (unsigned OtherIdx = Idx+1;
2493          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2494          ++OtherIdx)
2495       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2496         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2497         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2498                                                AddRec->op_end());
2499         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2500              ++OtherIdx)
2501           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2502             if (OtherAddRec->getLoop() == AddRecLoop) {
2503               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2504                    i != e; ++i) {
2505                 if (i >= AddRecOps.size()) {
2506                   AddRecOps.append(OtherAddRec->op_begin()+i,
2507                                    OtherAddRec->op_end());
2508                   break;
2509                 }
2510                 SmallVector<const SCEV *, 2> TwoOps = {
2511                     AddRecOps[i], OtherAddRec->getOperand(i)};
2512                 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2513               }
2514               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2515             }
2516         // Step size has changed, so we cannot guarantee no self-wraparound.
2517         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2518         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2519       }
2520 
2521     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2522     // next one.
2523   }
2524 
2525   // Okay, it looks like we really DO need an add expr.  Check to see if we
2526   // already have one, otherwise create a new one.
2527   return getOrCreateAddExpr(Ops, Flags);
2528 }
2529 
2530 const SCEV *
2531 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2532                                     SCEV::NoWrapFlags Flags) {
2533   FoldingSetNodeID ID;
2534   ID.AddInteger(scAddExpr);
2535   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2536     ID.AddPointer(Ops[i]);
2537   void *IP = nullptr;
2538   SCEVAddExpr *S =
2539       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2540   if (!S) {
2541     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2542     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2543     S = new (SCEVAllocator)
2544         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2545     UniqueSCEVs.InsertNode(S, IP);
2546   }
2547   S->setNoWrapFlags(Flags);
2548   return S;
2549 }
2550 
2551 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2552   uint64_t k = i*j;
2553   if (j > 1 && k / j != i) Overflow = true;
2554   return k;
2555 }
2556 
2557 /// Compute the result of "n choose k", the binomial coefficient.  If an
2558 /// intermediate computation overflows, Overflow will be set and the return will
2559 /// be garbage. Overflow is not cleared on absence of overflow.
2560 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2561   // We use the multiplicative formula:
2562   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2563   // At each iteration, we take the n-th term of the numeral and divide by the
2564   // (k-n)th term of the denominator.  This division will always produce an
2565   // integral result, and helps reduce the chance of overflow in the
2566   // intermediate computations. However, we can still overflow even when the
2567   // final result would fit.
2568 
2569   if (n == 0 || n == k) return 1;
2570   if (k > n) return 0;
2571 
2572   if (k > n/2)
2573     k = n-k;
2574 
2575   uint64_t r = 1;
2576   for (uint64_t i = 1; i <= k; ++i) {
2577     r = umul_ov(r, n-(i-1), Overflow);
2578     r /= i;
2579   }
2580   return r;
2581 }
2582 
2583 /// Determine if any of the operands in this SCEV are a constant or if
2584 /// any of the add or multiply expressions in this SCEV contain a constant.
2585 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2586   SmallVector<const SCEV *, 4> Ops;
2587   Ops.push_back(StartExpr);
2588   while (!Ops.empty()) {
2589     const SCEV *CurrentExpr = Ops.pop_back_val();
2590     if (isa<SCEVConstant>(*CurrentExpr))
2591       return true;
2592 
2593     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2594       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2595       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2596     }
2597   }
2598   return false;
2599 }
2600 
2601 /// Get a canonical multiply expression, or something simpler if possible.
2602 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2603                                         SCEV::NoWrapFlags Flags) {
2604   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2605          "only nuw or nsw allowed");
2606   assert(!Ops.empty() && "Cannot get empty mul!");
2607   if (Ops.size() == 1) return Ops[0];
2608 #ifndef NDEBUG
2609   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2610   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2611     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2612            "SCEVMulExpr operand types don't match!");
2613 #endif
2614 
2615   // Sort by complexity, this groups all similar expression types together.
2616   GroupByComplexity(Ops, &LI);
2617 
2618   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2619 
2620   // If there are any constants, fold them together.
2621   unsigned Idx = 0;
2622   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2623 
2624     // C1*(C2+V) -> C1*C2 + C1*V
2625     if (Ops.size() == 2)
2626         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2627           // If any of Add's ops are Adds or Muls with a constant,
2628           // apply this transformation as well.
2629           if (Add->getNumOperands() == 2)
2630             if (containsConstantSomewhere(Add))
2631               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2632                                 getMulExpr(LHSC, Add->getOperand(1)));
2633 
2634     ++Idx;
2635     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2636       // We found two constants, fold them together!
2637       ConstantInt *Fold =
2638           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2639       Ops[0] = getConstant(Fold);
2640       Ops.erase(Ops.begin()+1);  // Erase the folded element
2641       if (Ops.size() == 1) return Ops[0];
2642       LHSC = cast<SCEVConstant>(Ops[0]);
2643     }
2644 
2645     // If we are left with a constant one being multiplied, strip it off.
2646     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2647       Ops.erase(Ops.begin());
2648       --Idx;
2649     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2650       // If we have a multiply of zero, it will always be zero.
2651       return Ops[0];
2652     } else if (Ops[0]->isAllOnesValue()) {
2653       // If we have a mul by -1 of an add, try distributing the -1 among the
2654       // add operands.
2655       if (Ops.size() == 2) {
2656         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2657           SmallVector<const SCEV *, 4> NewOps;
2658           bool AnyFolded = false;
2659           for (const SCEV *AddOp : Add->operands()) {
2660             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2661             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2662             NewOps.push_back(Mul);
2663           }
2664           if (AnyFolded)
2665             return getAddExpr(NewOps);
2666         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2667           // Negation preserves a recurrence's no self-wrap property.
2668           SmallVector<const SCEV *, 4> Operands;
2669           for (const SCEV *AddRecOp : AddRec->operands())
2670             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2671 
2672           return getAddRecExpr(Operands, AddRec->getLoop(),
2673                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2674         }
2675       }
2676     }
2677 
2678     if (Ops.size() == 1)
2679       return Ops[0];
2680   }
2681 
2682   // Skip over the add expression until we get to a multiply.
2683   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2684     ++Idx;
2685 
2686   // If there are mul operands inline them all into this expression.
2687   if (Idx < Ops.size()) {
2688     bool DeletedMul = false;
2689     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2690       if (Ops.size() > MulOpsInlineThreshold)
2691         break;
2692       // If we have an mul, expand the mul operands onto the end of the operands
2693       // list.
2694       Ops.erase(Ops.begin()+Idx);
2695       Ops.append(Mul->op_begin(), Mul->op_end());
2696       DeletedMul = true;
2697     }
2698 
2699     // If we deleted at least one mul, we added operands to the end of the list,
2700     // and they are not necessarily sorted.  Recurse to resort and resimplify
2701     // any operands we just acquired.
2702     if (DeletedMul)
2703       return getMulExpr(Ops);
2704   }
2705 
2706   // If there are any add recurrences in the operands list, see if any other
2707   // added values are loop invariant.  If so, we can fold them into the
2708   // recurrence.
2709   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2710     ++Idx;
2711 
2712   // Scan over all recurrences, trying to fold loop invariants into them.
2713   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2714     // Scan all of the other operands to this mul and add them to the vector if
2715     // they are loop invariant w.r.t. the recurrence.
2716     SmallVector<const SCEV *, 8> LIOps;
2717     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2718     const Loop *AddRecLoop = AddRec->getLoop();
2719     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2720       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2721         LIOps.push_back(Ops[i]);
2722         Ops.erase(Ops.begin()+i);
2723         --i; --e;
2724       }
2725 
2726     // If we found some loop invariants, fold them into the recurrence.
2727     if (!LIOps.empty()) {
2728       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2729       SmallVector<const SCEV *, 4> NewOps;
2730       NewOps.reserve(AddRec->getNumOperands());
2731       const SCEV *Scale = getMulExpr(LIOps);
2732       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2733         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2734 
2735       // Build the new addrec. Propagate the NUW and NSW flags if both the
2736       // outer mul and the inner addrec are guaranteed to have no overflow.
2737       //
2738       // No self-wrap cannot be guaranteed after changing the step size, but
2739       // will be inferred if either NUW or NSW is true.
2740       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2741       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2742 
2743       // If all of the other operands were loop invariant, we are done.
2744       if (Ops.size() == 1) return NewRec;
2745 
2746       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2747       for (unsigned i = 0;; ++i)
2748         if (Ops[i] == AddRec) {
2749           Ops[i] = NewRec;
2750           break;
2751         }
2752       return getMulExpr(Ops);
2753     }
2754 
2755     // Okay, if there weren't any loop invariants to be folded, check to see if
2756     // there are multiple AddRec's with the same loop induction variable being
2757     // multiplied together.  If so, we can fold them.
2758 
2759     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2760     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2761     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2762     //   ]]],+,...up to x=2n}.
2763     // Note that the arguments to choose() are always integers with values
2764     // known at compile time, never SCEV objects.
2765     //
2766     // The implementation avoids pointless extra computations when the two
2767     // addrec's are of different length (mathematically, it's equivalent to
2768     // an infinite stream of zeros on the right).
2769     bool OpsModified = false;
2770     for (unsigned OtherIdx = Idx+1;
2771          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2772          ++OtherIdx) {
2773       const SCEVAddRecExpr *OtherAddRec =
2774         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2775       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2776         continue;
2777 
2778       bool Overflow = false;
2779       Type *Ty = AddRec->getType();
2780       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2781       SmallVector<const SCEV*, 7> AddRecOps;
2782       for (int x = 0, xe = AddRec->getNumOperands() +
2783              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2784         const SCEV *Term = getZero(Ty);
2785         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2786           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2787           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2788                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2789                z < ze && !Overflow; ++z) {
2790             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2791             uint64_t Coeff;
2792             if (LargerThan64Bits)
2793               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2794             else
2795               Coeff = Coeff1*Coeff2;
2796             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2797             const SCEV *Term1 = AddRec->getOperand(y-z);
2798             const SCEV *Term2 = OtherAddRec->getOperand(z);
2799             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2800           }
2801         }
2802         AddRecOps.push_back(Term);
2803       }
2804       if (!Overflow) {
2805         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2806                                               SCEV::FlagAnyWrap);
2807         if (Ops.size() == 2) return NewAddRec;
2808         Ops[Idx] = NewAddRec;
2809         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2810         OpsModified = true;
2811         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2812         if (!AddRec)
2813           break;
2814       }
2815     }
2816     if (OpsModified)
2817       return getMulExpr(Ops);
2818 
2819     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2820     // next one.
2821   }
2822 
2823   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2824   // already have one, otherwise create a new one.
2825   FoldingSetNodeID ID;
2826   ID.AddInteger(scMulExpr);
2827   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2828     ID.AddPointer(Ops[i]);
2829   void *IP = nullptr;
2830   SCEVMulExpr *S =
2831     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2832   if (!S) {
2833     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2834     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2835     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2836                                         O, Ops.size());
2837     UniqueSCEVs.InsertNode(S, IP);
2838   }
2839   S->setNoWrapFlags(Flags);
2840   return S;
2841 }
2842 
2843 /// Get a canonical unsigned division expression, or something simpler if
2844 /// possible.
2845 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2846                                          const SCEV *RHS) {
2847   assert(getEffectiveSCEVType(LHS->getType()) ==
2848          getEffectiveSCEVType(RHS->getType()) &&
2849          "SCEVUDivExpr operand types don't match!");
2850 
2851   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2852     if (RHSC->getValue()->equalsInt(1))
2853       return LHS;                               // X udiv 1 --> x
2854     // If the denominator is zero, the result of the udiv is undefined. Don't
2855     // try to analyze it, because the resolution chosen here may differ from
2856     // the resolution chosen in other parts of the compiler.
2857     if (!RHSC->getValue()->isZero()) {
2858       // Determine if the division can be folded into the operands of
2859       // its operands.
2860       // TODO: Generalize this to non-constants by using known-bits information.
2861       Type *Ty = LHS->getType();
2862       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2863       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2864       // For non-power-of-two values, effectively round the value up to the
2865       // nearest power of two.
2866       if (!RHSC->getAPInt().isPowerOf2())
2867         ++MaxShiftAmt;
2868       IntegerType *ExtTy =
2869         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2870       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2871         if (const SCEVConstant *Step =
2872             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2873           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2874           const APInt &StepInt = Step->getAPInt();
2875           const APInt &DivInt = RHSC->getAPInt();
2876           if (!StepInt.urem(DivInt) &&
2877               getZeroExtendExpr(AR, ExtTy) ==
2878               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2879                             getZeroExtendExpr(Step, ExtTy),
2880                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2881             SmallVector<const SCEV *, 4> Operands;
2882             for (const SCEV *Op : AR->operands())
2883               Operands.push_back(getUDivExpr(Op, RHS));
2884             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2885           }
2886           /// Get a canonical UDivExpr for a recurrence.
2887           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2888           // We can currently only fold X%N if X is constant.
2889           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2890           if (StartC && !DivInt.urem(StepInt) &&
2891               getZeroExtendExpr(AR, ExtTy) ==
2892               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2893                             getZeroExtendExpr(Step, ExtTy),
2894                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2895             const APInt &StartInt = StartC->getAPInt();
2896             const APInt &StartRem = StartInt.urem(StepInt);
2897             if (StartRem != 0)
2898               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2899                                   AR->getLoop(), SCEV::FlagNW);
2900           }
2901         }
2902       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2903       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2904         SmallVector<const SCEV *, 4> Operands;
2905         for (const SCEV *Op : M->operands())
2906           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2907         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2908           // Find an operand that's safely divisible.
2909           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2910             const SCEV *Op = M->getOperand(i);
2911             const SCEV *Div = getUDivExpr(Op, RHSC);
2912             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2913               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2914                                                       M->op_end());
2915               Operands[i] = Div;
2916               return getMulExpr(Operands);
2917             }
2918           }
2919       }
2920       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2921       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2922         SmallVector<const SCEV *, 4> Operands;
2923         for (const SCEV *Op : A->operands())
2924           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2925         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2926           Operands.clear();
2927           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2928             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2929             if (isa<SCEVUDivExpr>(Op) ||
2930                 getMulExpr(Op, RHS) != A->getOperand(i))
2931               break;
2932             Operands.push_back(Op);
2933           }
2934           if (Operands.size() == A->getNumOperands())
2935             return getAddExpr(Operands);
2936         }
2937       }
2938 
2939       // Fold if both operands are constant.
2940       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2941         Constant *LHSCV = LHSC->getValue();
2942         Constant *RHSCV = RHSC->getValue();
2943         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2944                                                                    RHSCV)));
2945       }
2946     }
2947   }
2948 
2949   FoldingSetNodeID ID;
2950   ID.AddInteger(scUDivExpr);
2951   ID.AddPointer(LHS);
2952   ID.AddPointer(RHS);
2953   void *IP = nullptr;
2954   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2955   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2956                                              LHS, RHS);
2957   UniqueSCEVs.InsertNode(S, IP);
2958   return S;
2959 }
2960 
2961 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2962   APInt A = C1->getAPInt().abs();
2963   APInt B = C2->getAPInt().abs();
2964   uint32_t ABW = A.getBitWidth();
2965   uint32_t BBW = B.getBitWidth();
2966 
2967   if (ABW > BBW)
2968     B = B.zext(ABW);
2969   else if (ABW < BBW)
2970     A = A.zext(BBW);
2971 
2972   return APIntOps::GreatestCommonDivisor(A, B);
2973 }
2974 
2975 /// Get a canonical unsigned division expression, or something simpler if
2976 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2977 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2978 /// it's not exact because the udiv may be clearing bits.
2979 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2980                                               const SCEV *RHS) {
2981   // TODO: we could try to find factors in all sorts of things, but for now we
2982   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2983   // end of this file for inspiration.
2984 
2985   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2986   if (!Mul || !Mul->hasNoUnsignedWrap())
2987     return getUDivExpr(LHS, RHS);
2988 
2989   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2990     // If the mulexpr multiplies by a constant, then that constant must be the
2991     // first element of the mulexpr.
2992     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2993       if (LHSCst == RHSCst) {
2994         SmallVector<const SCEV *, 2> Operands;
2995         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2996         return getMulExpr(Operands);
2997       }
2998 
2999       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3000       // that there's a factor provided by one of the other terms. We need to
3001       // check.
3002       APInt Factor = gcd(LHSCst, RHSCst);
3003       if (!Factor.isIntN(1)) {
3004         LHSCst =
3005             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3006         RHSCst =
3007             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3008         SmallVector<const SCEV *, 2> Operands;
3009         Operands.push_back(LHSCst);
3010         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3011         LHS = getMulExpr(Operands);
3012         RHS = RHSCst;
3013         Mul = dyn_cast<SCEVMulExpr>(LHS);
3014         if (!Mul)
3015           return getUDivExactExpr(LHS, RHS);
3016       }
3017     }
3018   }
3019 
3020   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3021     if (Mul->getOperand(i) == RHS) {
3022       SmallVector<const SCEV *, 2> Operands;
3023       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3024       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3025       return getMulExpr(Operands);
3026     }
3027   }
3028 
3029   return getUDivExpr(LHS, RHS);
3030 }
3031 
3032 /// Get an add recurrence expression for the specified loop.  Simplify the
3033 /// expression as much as possible.
3034 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3035                                            const Loop *L,
3036                                            SCEV::NoWrapFlags Flags) {
3037   SmallVector<const SCEV *, 4> Operands;
3038   Operands.push_back(Start);
3039   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3040     if (StepChrec->getLoop() == L) {
3041       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3042       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3043     }
3044 
3045   Operands.push_back(Step);
3046   return getAddRecExpr(Operands, L, Flags);
3047 }
3048 
3049 /// Get an add recurrence expression for the specified loop.  Simplify the
3050 /// expression as much as possible.
3051 const SCEV *
3052 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3053                                const Loop *L, SCEV::NoWrapFlags Flags) {
3054   if (Operands.size() == 1) return Operands[0];
3055 #ifndef NDEBUG
3056   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3057   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3058     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3059            "SCEVAddRecExpr operand types don't match!");
3060   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3061     assert(isLoopInvariant(Operands[i], L) &&
3062            "SCEVAddRecExpr operand is not loop-invariant!");
3063 #endif
3064 
3065   if (Operands.back()->isZero()) {
3066     Operands.pop_back();
3067     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3068   }
3069 
3070   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3071   // use that information to infer NUW and NSW flags. However, computing a
3072   // BE count requires calling getAddRecExpr, so we may not yet have a
3073   // meaningful BE count at this point (and if we don't, we'd be stuck
3074   // with a SCEVCouldNotCompute as the cached BE count).
3075 
3076   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3077 
3078   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3079   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3080     const Loop *NestedLoop = NestedAR->getLoop();
3081     if (L->contains(NestedLoop)
3082             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3083             : (!NestedLoop->contains(L) &&
3084                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3085       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3086                                                   NestedAR->op_end());
3087       Operands[0] = NestedAR->getStart();
3088       // AddRecs require their operands be loop-invariant with respect to their
3089       // loops. Don't perform this transformation if it would break this
3090       // requirement.
3091       bool AllInvariant = all_of(
3092           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3093 
3094       if (AllInvariant) {
3095         // Create a recurrence for the outer loop with the same step size.
3096         //
3097         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3098         // inner recurrence has the same property.
3099         SCEV::NoWrapFlags OuterFlags =
3100           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3101 
3102         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3103         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3104           return isLoopInvariant(Op, NestedLoop);
3105         });
3106 
3107         if (AllInvariant) {
3108           // Ok, both add recurrences are valid after the transformation.
3109           //
3110           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3111           // the outer recurrence has the same property.
3112           SCEV::NoWrapFlags InnerFlags =
3113             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3114           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3115         }
3116       }
3117       // Reset Operands to its original state.
3118       Operands[0] = NestedAR;
3119     }
3120   }
3121 
3122   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3123   // already have one, otherwise create a new one.
3124   FoldingSetNodeID ID;
3125   ID.AddInteger(scAddRecExpr);
3126   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3127     ID.AddPointer(Operands[i]);
3128   ID.AddPointer(L);
3129   void *IP = nullptr;
3130   SCEVAddRecExpr *S =
3131     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3132   if (!S) {
3133     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3134     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3135     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3136                                            O, Operands.size(), L);
3137     UniqueSCEVs.InsertNode(S, IP);
3138   }
3139   S->setNoWrapFlags(Flags);
3140   return S;
3141 }
3142 
3143 const SCEV *
3144 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3145                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3146   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3147   // getSCEV(Base)->getType() has the same address space as Base->getType()
3148   // because SCEV::getType() preserves the address space.
3149   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3150   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3151   // instruction to its SCEV, because the Instruction may be guarded by control
3152   // flow and the no-overflow bits may not be valid for the expression in any
3153   // context. This can be fixed similarly to how these flags are handled for
3154   // adds.
3155   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3156                                              : SCEV::FlagAnyWrap;
3157 
3158   const SCEV *TotalOffset = getZero(IntPtrTy);
3159   // The array size is unimportant. The first thing we do on CurTy is getting
3160   // its element type.
3161   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3162   for (const SCEV *IndexExpr : IndexExprs) {
3163     // Compute the (potentially symbolic) offset in bytes for this index.
3164     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3165       // For a struct, add the member offset.
3166       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3167       unsigned FieldNo = Index->getZExtValue();
3168       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3169 
3170       // Add the field offset to the running total offset.
3171       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3172 
3173       // Update CurTy to the type of the field at Index.
3174       CurTy = STy->getTypeAtIndex(Index);
3175     } else {
3176       // Update CurTy to its element type.
3177       CurTy = cast<SequentialType>(CurTy)->getElementType();
3178       // For an array, add the element offset, explicitly scaled.
3179       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3180       // Getelementptr indices are signed.
3181       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3182 
3183       // Multiply the index by the element size to compute the element offset.
3184       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3185 
3186       // Add the element offset to the running total offset.
3187       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3188     }
3189   }
3190 
3191   // Add the total offset from all the GEP indices to the base.
3192   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3193 }
3194 
3195 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3196                                          const SCEV *RHS) {
3197   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3198   return getSMaxExpr(Ops);
3199 }
3200 
3201 const SCEV *
3202 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3203   assert(!Ops.empty() && "Cannot get empty smax!");
3204   if (Ops.size() == 1) return Ops[0];
3205 #ifndef NDEBUG
3206   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3207   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3208     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3209            "SCEVSMaxExpr operand types don't match!");
3210 #endif
3211 
3212   // Sort by complexity, this groups all similar expression types together.
3213   GroupByComplexity(Ops, &LI);
3214 
3215   // If there are any constants, fold them together.
3216   unsigned Idx = 0;
3217   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3218     ++Idx;
3219     assert(Idx < Ops.size());
3220     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3221       // We found two constants, fold them together!
3222       ConstantInt *Fold = ConstantInt::get(
3223           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3224       Ops[0] = getConstant(Fold);
3225       Ops.erase(Ops.begin()+1);  // Erase the folded element
3226       if (Ops.size() == 1) return Ops[0];
3227       LHSC = cast<SCEVConstant>(Ops[0]);
3228     }
3229 
3230     // If we are left with a constant minimum-int, strip it off.
3231     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3232       Ops.erase(Ops.begin());
3233       --Idx;
3234     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3235       // If we have an smax with a constant maximum-int, it will always be
3236       // maximum-int.
3237       return Ops[0];
3238     }
3239 
3240     if (Ops.size() == 1) return Ops[0];
3241   }
3242 
3243   // Find the first SMax
3244   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3245     ++Idx;
3246 
3247   // Check to see if one of the operands is an SMax. If so, expand its operands
3248   // onto our operand list, and recurse to simplify.
3249   if (Idx < Ops.size()) {
3250     bool DeletedSMax = false;
3251     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3252       Ops.erase(Ops.begin()+Idx);
3253       Ops.append(SMax->op_begin(), SMax->op_end());
3254       DeletedSMax = true;
3255     }
3256 
3257     if (DeletedSMax)
3258       return getSMaxExpr(Ops);
3259   }
3260 
3261   // Okay, check to see if the same value occurs in the operand list twice.  If
3262   // so, delete one.  Since we sorted the list, these values are required to
3263   // be adjacent.
3264   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3265     //  X smax Y smax Y  -->  X smax Y
3266     //  X smax Y         -->  X, if X is always greater than Y
3267     if (Ops[i] == Ops[i+1] ||
3268         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3269       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3270       --i; --e;
3271     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3272       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3273       --i; --e;
3274     }
3275 
3276   if (Ops.size() == 1) return Ops[0];
3277 
3278   assert(!Ops.empty() && "Reduced smax down to nothing!");
3279 
3280   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3281   // already have one, otherwise create a new one.
3282   FoldingSetNodeID ID;
3283   ID.AddInteger(scSMaxExpr);
3284   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3285     ID.AddPointer(Ops[i]);
3286   void *IP = nullptr;
3287   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3288   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3289   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3290   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3291                                              O, Ops.size());
3292   UniqueSCEVs.InsertNode(S, IP);
3293   return S;
3294 }
3295 
3296 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3297                                          const SCEV *RHS) {
3298   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3299   return getUMaxExpr(Ops);
3300 }
3301 
3302 const SCEV *
3303 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3304   assert(!Ops.empty() && "Cannot get empty umax!");
3305   if (Ops.size() == 1) return Ops[0];
3306 #ifndef NDEBUG
3307   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3308   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3309     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3310            "SCEVUMaxExpr operand types don't match!");
3311 #endif
3312 
3313   // Sort by complexity, this groups all similar expression types together.
3314   GroupByComplexity(Ops, &LI);
3315 
3316   // If there are any constants, fold them together.
3317   unsigned Idx = 0;
3318   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3319     ++Idx;
3320     assert(Idx < Ops.size());
3321     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3322       // We found two constants, fold them together!
3323       ConstantInt *Fold = ConstantInt::get(
3324           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3325       Ops[0] = getConstant(Fold);
3326       Ops.erase(Ops.begin()+1);  // Erase the folded element
3327       if (Ops.size() == 1) return Ops[0];
3328       LHSC = cast<SCEVConstant>(Ops[0]);
3329     }
3330 
3331     // If we are left with a constant minimum-int, strip it off.
3332     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3333       Ops.erase(Ops.begin());
3334       --Idx;
3335     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3336       // If we have an umax with a constant maximum-int, it will always be
3337       // maximum-int.
3338       return Ops[0];
3339     }
3340 
3341     if (Ops.size() == 1) return Ops[0];
3342   }
3343 
3344   // Find the first UMax
3345   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3346     ++Idx;
3347 
3348   // Check to see if one of the operands is a UMax. If so, expand its operands
3349   // onto our operand list, and recurse to simplify.
3350   if (Idx < Ops.size()) {
3351     bool DeletedUMax = false;
3352     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3353       Ops.erase(Ops.begin()+Idx);
3354       Ops.append(UMax->op_begin(), UMax->op_end());
3355       DeletedUMax = true;
3356     }
3357 
3358     if (DeletedUMax)
3359       return getUMaxExpr(Ops);
3360   }
3361 
3362   // Okay, check to see if the same value occurs in the operand list twice.  If
3363   // so, delete one.  Since we sorted the list, these values are required to
3364   // be adjacent.
3365   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3366     //  X umax Y umax Y  -->  X umax Y
3367     //  X umax Y         -->  X, if X is always greater than Y
3368     if (Ops[i] == Ops[i+1] ||
3369         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3370       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3371       --i; --e;
3372     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3373       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3374       --i; --e;
3375     }
3376 
3377   if (Ops.size() == 1) return Ops[0];
3378 
3379   assert(!Ops.empty() && "Reduced umax down to nothing!");
3380 
3381   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3382   // already have one, otherwise create a new one.
3383   FoldingSetNodeID ID;
3384   ID.AddInteger(scUMaxExpr);
3385   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3386     ID.AddPointer(Ops[i]);
3387   void *IP = nullptr;
3388   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3389   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3390   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3391   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3392                                              O, Ops.size());
3393   UniqueSCEVs.InsertNode(S, IP);
3394   return S;
3395 }
3396 
3397 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3398                                          const SCEV *RHS) {
3399   // ~smax(~x, ~y) == smin(x, y).
3400   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3401 }
3402 
3403 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3404                                          const SCEV *RHS) {
3405   // ~umax(~x, ~y) == umin(x, y)
3406   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3407 }
3408 
3409 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3410   // We can bypass creating a target-independent
3411   // constant expression and then folding it back into a ConstantInt.
3412   // This is just a compile-time optimization.
3413   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3414 }
3415 
3416 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3417                                              StructType *STy,
3418                                              unsigned FieldNo) {
3419   // We can bypass creating a target-independent
3420   // constant expression and then folding it back into a ConstantInt.
3421   // This is just a compile-time optimization.
3422   return getConstant(
3423       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3424 }
3425 
3426 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3427   // Don't attempt to do anything other than create a SCEVUnknown object
3428   // here.  createSCEV only calls getUnknown after checking for all other
3429   // interesting possibilities, and any other code that calls getUnknown
3430   // is doing so in order to hide a value from SCEV canonicalization.
3431 
3432   FoldingSetNodeID ID;
3433   ID.AddInteger(scUnknown);
3434   ID.AddPointer(V);
3435   void *IP = nullptr;
3436   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3437     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3438            "Stale SCEVUnknown in uniquing map!");
3439     return S;
3440   }
3441   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3442                                             FirstUnknown);
3443   FirstUnknown = cast<SCEVUnknown>(S);
3444   UniqueSCEVs.InsertNode(S, IP);
3445   return S;
3446 }
3447 
3448 //===----------------------------------------------------------------------===//
3449 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3450 //
3451 
3452 /// Test if values of the given type are analyzable within the SCEV
3453 /// framework. This primarily includes integer types, and it can optionally
3454 /// include pointer types if the ScalarEvolution class has access to
3455 /// target-specific information.
3456 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3457   // Integers and pointers are always SCEVable.
3458   return Ty->isIntegerTy() || Ty->isPointerTy();
3459 }
3460 
3461 /// Return the size in bits of the specified type, for which isSCEVable must
3462 /// return true.
3463 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3464   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3465   return getDataLayout().getTypeSizeInBits(Ty);
3466 }
3467 
3468 /// Return a type with the same bitwidth as the given type and which represents
3469 /// how SCEV will treat the given type, for which isSCEVable must return
3470 /// true. For pointer types, this is the pointer-sized integer type.
3471 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3472   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3473 
3474   if (Ty->isIntegerTy())
3475     return Ty;
3476 
3477   // The only other support type is pointer.
3478   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3479   return getDataLayout().getIntPtrType(Ty);
3480 }
3481 
3482 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3483   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3484 }
3485 
3486 const SCEV *ScalarEvolution::getCouldNotCompute() {
3487   return CouldNotCompute.get();
3488 }
3489 
3490 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3491   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3492     auto *SU = dyn_cast<SCEVUnknown>(S);
3493     return SU && SU->getValue() == nullptr;
3494   });
3495 
3496   return !ContainsNulls;
3497 }
3498 
3499 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3500   HasRecMapType::iterator I = HasRecMap.find(S);
3501   if (I != HasRecMap.end())
3502     return I->second;
3503 
3504   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3505   HasRecMap.insert({S, FoundAddRec});
3506   return FoundAddRec;
3507 }
3508 
3509 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3510 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3511 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3512 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3513   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3514   if (!Add)
3515     return {S, nullptr};
3516 
3517   if (Add->getNumOperands() != 2)
3518     return {S, nullptr};
3519 
3520   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3521   if (!ConstOp)
3522     return {S, nullptr};
3523 
3524   return {Add->getOperand(1), ConstOp->getValue()};
3525 }
3526 
3527 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3528 /// by the value and offset from any ValueOffsetPair in the set.
3529 SetVector<ScalarEvolution::ValueOffsetPair> *
3530 ScalarEvolution::getSCEVValues(const SCEV *S) {
3531   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3532   if (SI == ExprValueMap.end())
3533     return nullptr;
3534 #ifndef NDEBUG
3535   if (VerifySCEVMap) {
3536     // Check there is no dangling Value in the set returned.
3537     for (const auto &VE : SI->second)
3538       assert(ValueExprMap.count(VE.first));
3539   }
3540 #endif
3541   return &SI->second;
3542 }
3543 
3544 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3545 /// cannot be used separately. eraseValueFromMap should be used to remove
3546 /// V from ValueExprMap and ExprValueMap at the same time.
3547 void ScalarEvolution::eraseValueFromMap(Value *V) {
3548   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3549   if (I != ValueExprMap.end()) {
3550     const SCEV *S = I->second;
3551     // Remove {V, 0} from the set of ExprValueMap[S]
3552     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3553       SV->remove({V, nullptr});
3554 
3555     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3556     const SCEV *Stripped;
3557     ConstantInt *Offset;
3558     std::tie(Stripped, Offset) = splitAddExpr(S);
3559     if (Offset != nullptr) {
3560       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3561         SV->remove({V, Offset});
3562     }
3563     ValueExprMap.erase(V);
3564   }
3565 }
3566 
3567 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3568 /// create a new one.
3569 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3570   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3571 
3572   const SCEV *S = getExistingSCEV(V);
3573   if (S == nullptr) {
3574     S = createSCEV(V);
3575     // During PHI resolution, it is possible to create two SCEVs for the same
3576     // V, so it is needed to double check whether V->S is inserted into
3577     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3578     std::pair<ValueExprMapType::iterator, bool> Pair =
3579         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3580     if (Pair.second) {
3581       ExprValueMap[S].insert({V, nullptr});
3582 
3583       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3584       // ExprValueMap.
3585       const SCEV *Stripped = S;
3586       ConstantInt *Offset = nullptr;
3587       std::tie(Stripped, Offset) = splitAddExpr(S);
3588       // If stripped is SCEVUnknown, don't bother to save
3589       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3590       // increase the complexity of the expansion code.
3591       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3592       // because it may generate add/sub instead of GEP in SCEV expansion.
3593       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3594           !isa<GetElementPtrInst>(V))
3595         ExprValueMap[Stripped].insert({V, Offset});
3596     }
3597   }
3598   return S;
3599 }
3600 
3601 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3602   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3603 
3604   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3605   if (I != ValueExprMap.end()) {
3606     const SCEV *S = I->second;
3607     if (checkValidity(S))
3608       return S;
3609     eraseValueFromMap(V);
3610     forgetMemoizedResults(S);
3611   }
3612   return nullptr;
3613 }
3614 
3615 /// Return a SCEV corresponding to -V = -1*V
3616 ///
3617 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3618                                              SCEV::NoWrapFlags Flags) {
3619   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3620     return getConstant(
3621                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3622 
3623   Type *Ty = V->getType();
3624   Ty = getEffectiveSCEVType(Ty);
3625   return getMulExpr(
3626       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3627 }
3628 
3629 /// Return a SCEV corresponding to ~V = -1-V
3630 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3631   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3632     return getConstant(
3633                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3634 
3635   Type *Ty = V->getType();
3636   Ty = getEffectiveSCEVType(Ty);
3637   const SCEV *AllOnes =
3638                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3639   return getMinusSCEV(AllOnes, V);
3640 }
3641 
3642 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3643                                           SCEV::NoWrapFlags Flags) {
3644   // Fast path: X - X --> 0.
3645   if (LHS == RHS)
3646     return getZero(LHS->getType());
3647 
3648   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3649   // makes it so that we cannot make much use of NUW.
3650   auto AddFlags = SCEV::FlagAnyWrap;
3651   const bool RHSIsNotMinSigned =
3652       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3653   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3654     // Let M be the minimum representable signed value. Then (-1)*RHS
3655     // signed-wraps if and only if RHS is M. That can happen even for
3656     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3657     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3658     // (-1)*RHS, we need to prove that RHS != M.
3659     //
3660     // If LHS is non-negative and we know that LHS - RHS does not
3661     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3662     // either by proving that RHS > M or that LHS >= 0.
3663     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3664       AddFlags = SCEV::FlagNSW;
3665     }
3666   }
3667 
3668   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3669   // RHS is NSW and LHS >= 0.
3670   //
3671   // The difficulty here is that the NSW flag may have been proven
3672   // relative to a loop that is to be found in a recurrence in LHS and
3673   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3674   // larger scope than intended.
3675   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3676 
3677   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3678 }
3679 
3680 const SCEV *
3681 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3682   Type *SrcTy = V->getType();
3683   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3684          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3685          "Cannot truncate or zero extend with non-integer arguments!");
3686   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3687     return V;  // No conversion
3688   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3689     return getTruncateExpr(V, Ty);
3690   return getZeroExtendExpr(V, Ty);
3691 }
3692 
3693 const SCEV *
3694 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3695                                          Type *Ty) {
3696   Type *SrcTy = V->getType();
3697   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3698          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3699          "Cannot truncate or zero extend with non-integer arguments!");
3700   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3701     return V;  // No conversion
3702   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3703     return getTruncateExpr(V, Ty);
3704   return getSignExtendExpr(V, Ty);
3705 }
3706 
3707 const SCEV *
3708 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3709   Type *SrcTy = V->getType();
3710   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3711          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3712          "Cannot noop or zero extend with non-integer arguments!");
3713   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3714          "getNoopOrZeroExtend cannot truncate!");
3715   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3716     return V;  // No conversion
3717   return getZeroExtendExpr(V, Ty);
3718 }
3719 
3720 const SCEV *
3721 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3722   Type *SrcTy = V->getType();
3723   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3724          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3725          "Cannot noop or sign extend with non-integer arguments!");
3726   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3727          "getNoopOrSignExtend cannot truncate!");
3728   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3729     return V;  // No conversion
3730   return getSignExtendExpr(V, Ty);
3731 }
3732 
3733 const SCEV *
3734 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3735   Type *SrcTy = V->getType();
3736   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3737          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3738          "Cannot noop or any extend with non-integer arguments!");
3739   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3740          "getNoopOrAnyExtend cannot truncate!");
3741   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3742     return V;  // No conversion
3743   return getAnyExtendExpr(V, Ty);
3744 }
3745 
3746 const SCEV *
3747 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3748   Type *SrcTy = V->getType();
3749   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3750          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3751          "Cannot truncate or noop with non-integer arguments!");
3752   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3753          "getTruncateOrNoop cannot extend!");
3754   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3755     return V;  // No conversion
3756   return getTruncateExpr(V, Ty);
3757 }
3758 
3759 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3760                                                         const SCEV *RHS) {
3761   const SCEV *PromotedLHS = LHS;
3762   const SCEV *PromotedRHS = RHS;
3763 
3764   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3765     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3766   else
3767     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3768 
3769   return getUMaxExpr(PromotedLHS, PromotedRHS);
3770 }
3771 
3772 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3773                                                         const SCEV *RHS) {
3774   const SCEV *PromotedLHS = LHS;
3775   const SCEV *PromotedRHS = RHS;
3776 
3777   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3778     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3779   else
3780     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3781 
3782   return getUMinExpr(PromotedLHS, PromotedRHS);
3783 }
3784 
3785 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3786   // A pointer operand may evaluate to a nonpointer expression, such as null.
3787   if (!V->getType()->isPointerTy())
3788     return V;
3789 
3790   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3791     return getPointerBase(Cast->getOperand());
3792   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3793     const SCEV *PtrOp = nullptr;
3794     for (const SCEV *NAryOp : NAry->operands()) {
3795       if (NAryOp->getType()->isPointerTy()) {
3796         // Cannot find the base of an expression with multiple pointer operands.
3797         if (PtrOp)
3798           return V;
3799         PtrOp = NAryOp;
3800       }
3801     }
3802     if (!PtrOp)
3803       return V;
3804     return getPointerBase(PtrOp);
3805   }
3806   return V;
3807 }
3808 
3809 /// Push users of the given Instruction onto the given Worklist.
3810 static void
3811 PushDefUseChildren(Instruction *I,
3812                    SmallVectorImpl<Instruction *> &Worklist) {
3813   // Push the def-use children onto the Worklist stack.
3814   for (User *U : I->users())
3815     Worklist.push_back(cast<Instruction>(U));
3816 }
3817 
3818 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3819   SmallVector<Instruction *, 16> Worklist;
3820   PushDefUseChildren(PN, Worklist);
3821 
3822   SmallPtrSet<Instruction *, 8> Visited;
3823   Visited.insert(PN);
3824   while (!Worklist.empty()) {
3825     Instruction *I = Worklist.pop_back_val();
3826     if (!Visited.insert(I).second)
3827       continue;
3828 
3829     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3830     if (It != ValueExprMap.end()) {
3831       const SCEV *Old = It->second;
3832 
3833       // Short-circuit the def-use traversal if the symbolic name
3834       // ceases to appear in expressions.
3835       if (Old != SymName && !hasOperand(Old, SymName))
3836         continue;
3837 
3838       // SCEVUnknown for a PHI either means that it has an unrecognized
3839       // structure, it's a PHI that's in the progress of being computed
3840       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3841       // additional loop trip count information isn't going to change anything.
3842       // In the second case, createNodeForPHI will perform the necessary
3843       // updates on its own when it gets to that point. In the third, we do
3844       // want to forget the SCEVUnknown.
3845       if (!isa<PHINode>(I) ||
3846           !isa<SCEVUnknown>(Old) ||
3847           (I != PN && Old == SymName)) {
3848         eraseValueFromMap(It->first);
3849         forgetMemoizedResults(Old);
3850       }
3851     }
3852 
3853     PushDefUseChildren(I, Worklist);
3854   }
3855 }
3856 
3857 namespace {
3858 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3859 public:
3860   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3861                              ScalarEvolution &SE) {
3862     SCEVInitRewriter Rewriter(L, SE);
3863     const SCEV *Result = Rewriter.visit(S);
3864     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3865   }
3866 
3867   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3868       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3869 
3870   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3871     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3872       Valid = false;
3873     return Expr;
3874   }
3875 
3876   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3877     // Only allow AddRecExprs for this loop.
3878     if (Expr->getLoop() == L)
3879       return Expr->getStart();
3880     Valid = false;
3881     return Expr;
3882   }
3883 
3884   bool isValid() { return Valid; }
3885 
3886 private:
3887   const Loop *L;
3888   bool Valid;
3889 };
3890 
3891 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3892 public:
3893   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3894                              ScalarEvolution &SE) {
3895     SCEVShiftRewriter Rewriter(L, SE);
3896     const SCEV *Result = Rewriter.visit(S);
3897     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3898   }
3899 
3900   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3901       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3902 
3903   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3904     // Only allow AddRecExprs for this loop.
3905     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3906       Valid = false;
3907     return Expr;
3908   }
3909 
3910   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3911     if (Expr->getLoop() == L && Expr->isAffine())
3912       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3913     Valid = false;
3914     return Expr;
3915   }
3916   bool isValid() { return Valid; }
3917 
3918 private:
3919   const Loop *L;
3920   bool Valid;
3921 };
3922 } // end anonymous namespace
3923 
3924 SCEV::NoWrapFlags
3925 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3926   if (!AR->isAffine())
3927     return SCEV::FlagAnyWrap;
3928 
3929   typedef OverflowingBinaryOperator OBO;
3930   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3931 
3932   if (!AR->hasNoSignedWrap()) {
3933     ConstantRange AddRecRange = getSignedRange(AR);
3934     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3935 
3936     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3937         Instruction::Add, IncRange, OBO::NoSignedWrap);
3938     if (NSWRegion.contains(AddRecRange))
3939       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3940   }
3941 
3942   if (!AR->hasNoUnsignedWrap()) {
3943     ConstantRange AddRecRange = getUnsignedRange(AR);
3944     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3945 
3946     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3947         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3948     if (NUWRegion.contains(AddRecRange))
3949       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3950   }
3951 
3952   return Result;
3953 }
3954 
3955 namespace {
3956 /// Represents an abstract binary operation.  This may exist as a
3957 /// normal instruction or constant expression, or may have been
3958 /// derived from an expression tree.
3959 struct BinaryOp {
3960   unsigned Opcode;
3961   Value *LHS;
3962   Value *RHS;
3963   bool IsNSW;
3964   bool IsNUW;
3965 
3966   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3967   /// constant expression.
3968   Operator *Op;
3969 
3970   explicit BinaryOp(Operator *Op)
3971       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3972         IsNSW(false), IsNUW(false), Op(Op) {
3973     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3974       IsNSW = OBO->hasNoSignedWrap();
3975       IsNUW = OBO->hasNoUnsignedWrap();
3976     }
3977   }
3978 
3979   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3980                     bool IsNUW = false)
3981       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3982         Op(nullptr) {}
3983 };
3984 }
3985 
3986 
3987 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3988 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3989   auto *Op = dyn_cast<Operator>(V);
3990   if (!Op)
3991     return None;
3992 
3993   // Implementation detail: all the cleverness here should happen without
3994   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3995   // SCEV expressions when possible, and we should not break that.
3996 
3997   switch (Op->getOpcode()) {
3998   case Instruction::Add:
3999   case Instruction::Sub:
4000   case Instruction::Mul:
4001   case Instruction::UDiv:
4002   case Instruction::And:
4003   case Instruction::Or:
4004   case Instruction::AShr:
4005   case Instruction::Shl:
4006     return BinaryOp(Op);
4007 
4008   case Instruction::Xor:
4009     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4010       // If the RHS of the xor is a signbit, then this is just an add.
4011       // Instcombine turns add of signbit into xor as a strength reduction step.
4012       if (RHSC->getValue().isSignBit())
4013         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4014     return BinaryOp(Op);
4015 
4016   case Instruction::LShr:
4017     // Turn logical shift right of a constant into a unsigned divide.
4018     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4019       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4020 
4021       // If the shift count is not less than the bitwidth, the result of
4022       // the shift is undefined. Don't try to analyze it, because the
4023       // resolution chosen here may differ from the resolution chosen in
4024       // other parts of the compiler.
4025       if (SA->getValue().ult(BitWidth)) {
4026         Constant *X =
4027             ConstantInt::get(SA->getContext(),
4028                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4029         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4030       }
4031     }
4032     return BinaryOp(Op);
4033 
4034   case Instruction::ExtractValue: {
4035     auto *EVI = cast<ExtractValueInst>(Op);
4036     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4037       break;
4038 
4039     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4040     if (!CI)
4041       break;
4042 
4043     if (auto *F = CI->getCalledFunction())
4044       switch (F->getIntrinsicID()) {
4045       case Intrinsic::sadd_with_overflow:
4046       case Intrinsic::uadd_with_overflow: {
4047         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4048           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4049                           CI->getArgOperand(1));
4050 
4051         // Now that we know that all uses of the arithmetic-result component of
4052         // CI are guarded by the overflow check, we can go ahead and pretend
4053         // that the arithmetic is non-overflowing.
4054         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4055           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4056                           CI->getArgOperand(1), /* IsNSW = */ true,
4057                           /* IsNUW = */ false);
4058         else
4059           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4060                           CI->getArgOperand(1), /* IsNSW = */ false,
4061                           /* IsNUW*/ true);
4062       }
4063 
4064       case Intrinsic::ssub_with_overflow:
4065       case Intrinsic::usub_with_overflow:
4066         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4067                         CI->getArgOperand(1));
4068 
4069       case Intrinsic::smul_with_overflow:
4070       case Intrinsic::umul_with_overflow:
4071         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4072                         CI->getArgOperand(1));
4073       default:
4074         break;
4075       }
4076   }
4077 
4078   default:
4079     break;
4080   }
4081 
4082   return None;
4083 }
4084 
4085 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4086   const Loop *L = LI.getLoopFor(PN->getParent());
4087   if (!L || L->getHeader() != PN->getParent())
4088     return nullptr;
4089 
4090   // The loop may have multiple entrances or multiple exits; we can analyze
4091   // this phi as an addrec if it has a unique entry value and a unique
4092   // backedge value.
4093   Value *BEValueV = nullptr, *StartValueV = nullptr;
4094   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4095     Value *V = PN->getIncomingValue(i);
4096     if (L->contains(PN->getIncomingBlock(i))) {
4097       if (!BEValueV) {
4098         BEValueV = V;
4099       } else if (BEValueV != V) {
4100         BEValueV = nullptr;
4101         break;
4102       }
4103     } else if (!StartValueV) {
4104       StartValueV = V;
4105     } else if (StartValueV != V) {
4106       StartValueV = nullptr;
4107       break;
4108     }
4109   }
4110   if (BEValueV && StartValueV) {
4111     // While we are analyzing this PHI node, handle its value symbolically.
4112     const SCEV *SymbolicName = getUnknown(PN);
4113     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4114            "PHI node already processed?");
4115     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4116 
4117     // Using this symbolic name for the PHI, analyze the value coming around
4118     // the back-edge.
4119     const SCEV *BEValue = getSCEV(BEValueV);
4120 
4121     // NOTE: If BEValue is loop invariant, we know that the PHI node just
4122     // has a special value for the first iteration of the loop.
4123 
4124     // If the value coming around the backedge is an add with the symbolic
4125     // value we just inserted, then we found a simple induction variable!
4126     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4127       // If there is a single occurrence of the symbolic value, replace it
4128       // with a recurrence.
4129       unsigned FoundIndex = Add->getNumOperands();
4130       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4131         if (Add->getOperand(i) == SymbolicName)
4132           if (FoundIndex == e) {
4133             FoundIndex = i;
4134             break;
4135           }
4136 
4137       if (FoundIndex != Add->getNumOperands()) {
4138         // Create an add with everything but the specified operand.
4139         SmallVector<const SCEV *, 8> Ops;
4140         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4141           if (i != FoundIndex)
4142             Ops.push_back(Add->getOperand(i));
4143         const SCEV *Accum = getAddExpr(Ops);
4144 
4145         // This is not a valid addrec if the step amount is varying each
4146         // loop iteration, but is not itself an addrec in this loop.
4147         if (isLoopInvariant(Accum, L) ||
4148             (isa<SCEVAddRecExpr>(Accum) &&
4149              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4150           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4151 
4152           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4153             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4154               if (BO->IsNUW)
4155                 Flags = setFlags(Flags, SCEV::FlagNUW);
4156               if (BO->IsNSW)
4157                 Flags = setFlags(Flags, SCEV::FlagNSW);
4158             }
4159           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4160             // If the increment is an inbounds GEP, then we know the address
4161             // space cannot be wrapped around. We cannot make any guarantee
4162             // about signed or unsigned overflow because pointers are
4163             // unsigned but we may have a negative index from the base
4164             // pointer. We can guarantee that no unsigned wrap occurs if the
4165             // indices form a positive value.
4166             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4167               Flags = setFlags(Flags, SCEV::FlagNW);
4168 
4169               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4170               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4171                 Flags = setFlags(Flags, SCEV::FlagNUW);
4172             }
4173 
4174             // We cannot transfer nuw and nsw flags from subtraction
4175             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4176             // for instance.
4177           }
4178 
4179           const SCEV *StartVal = getSCEV(StartValueV);
4180           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4181 
4182           // Okay, for the entire analysis of this edge we assumed the PHI
4183           // to be symbolic.  We now need to go back and purge all of the
4184           // entries for the scalars that use the symbolic expression.
4185           forgetSymbolicName(PN, SymbolicName);
4186           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4187 
4188           // We can add Flags to the post-inc expression only if we
4189           // know that it us *undefined behavior* for BEValueV to
4190           // overflow.
4191           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4192             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4193               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4194 
4195           return PHISCEV;
4196         }
4197       }
4198     } else {
4199       // Otherwise, this could be a loop like this:
4200       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4201       // In this case, j = {1,+,1}  and BEValue is j.
4202       // Because the other in-value of i (0) fits the evolution of BEValue
4203       // i really is an addrec evolution.
4204       //
4205       // We can generalize this saying that i is the shifted value of BEValue
4206       // by one iteration:
4207       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4208       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4209       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4210       if (Shifted != getCouldNotCompute() &&
4211           Start != getCouldNotCompute()) {
4212         const SCEV *StartVal = getSCEV(StartValueV);
4213         if (Start == StartVal) {
4214           // Okay, for the entire analysis of this edge we assumed the PHI
4215           // to be symbolic.  We now need to go back and purge all of the
4216           // entries for the scalars that use the symbolic expression.
4217           forgetSymbolicName(PN, SymbolicName);
4218           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4219           return Shifted;
4220         }
4221       }
4222     }
4223 
4224     // Remove the temporary PHI node SCEV that has been inserted while intending
4225     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4226     // as it will prevent later (possibly simpler) SCEV expressions to be added
4227     // to the ValueExprMap.
4228     eraseValueFromMap(PN);
4229   }
4230 
4231   return nullptr;
4232 }
4233 
4234 // Checks if the SCEV S is available at BB.  S is considered available at BB
4235 // if S can be materialized at BB without introducing a fault.
4236 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4237                                BasicBlock *BB) {
4238   struct CheckAvailable {
4239     bool TraversalDone = false;
4240     bool Available = true;
4241 
4242     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4243     BasicBlock *BB = nullptr;
4244     DominatorTree &DT;
4245 
4246     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4247       : L(L), BB(BB), DT(DT) {}
4248 
4249     bool setUnavailable() {
4250       TraversalDone = true;
4251       Available = false;
4252       return false;
4253     }
4254 
4255     bool follow(const SCEV *S) {
4256       switch (S->getSCEVType()) {
4257       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4258       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4259         // These expressions are available if their operand(s) is/are.
4260         return true;
4261 
4262       case scAddRecExpr: {
4263         // We allow add recurrences that are on the loop BB is in, or some
4264         // outer loop.  This guarantees availability because the value of the
4265         // add recurrence at BB is simply the "current" value of the induction
4266         // variable.  We can relax this in the future; for instance an add
4267         // recurrence on a sibling dominating loop is also available at BB.
4268         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4269         if (L && (ARLoop == L || ARLoop->contains(L)))
4270           return true;
4271 
4272         return setUnavailable();
4273       }
4274 
4275       case scUnknown: {
4276         // For SCEVUnknown, we check for simple dominance.
4277         const auto *SU = cast<SCEVUnknown>(S);
4278         Value *V = SU->getValue();
4279 
4280         if (isa<Argument>(V))
4281           return false;
4282 
4283         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4284           return false;
4285 
4286         return setUnavailable();
4287       }
4288 
4289       case scUDivExpr:
4290       case scCouldNotCompute:
4291         // We do not try to smart about these at all.
4292         return setUnavailable();
4293       }
4294       llvm_unreachable("switch should be fully covered!");
4295     }
4296 
4297     bool isDone() { return TraversalDone; }
4298   };
4299 
4300   CheckAvailable CA(L, BB, DT);
4301   SCEVTraversal<CheckAvailable> ST(CA);
4302 
4303   ST.visitAll(S);
4304   return CA.Available;
4305 }
4306 
4307 // Try to match a control flow sequence that branches out at BI and merges back
4308 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4309 // match.
4310 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4311                           Value *&C, Value *&LHS, Value *&RHS) {
4312   C = BI->getCondition();
4313 
4314   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4315   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4316 
4317   if (!LeftEdge.isSingleEdge())
4318     return false;
4319 
4320   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4321 
4322   Use &LeftUse = Merge->getOperandUse(0);
4323   Use &RightUse = Merge->getOperandUse(1);
4324 
4325   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4326     LHS = LeftUse;
4327     RHS = RightUse;
4328     return true;
4329   }
4330 
4331   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4332     LHS = RightUse;
4333     RHS = LeftUse;
4334     return true;
4335   }
4336 
4337   return false;
4338 }
4339 
4340 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4341   auto IsReachable =
4342       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4343   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4344     const Loop *L = LI.getLoopFor(PN->getParent());
4345 
4346     // We don't want to break LCSSA, even in a SCEV expression tree.
4347     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4348       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4349         return nullptr;
4350 
4351     // Try to match
4352     //
4353     //  br %cond, label %left, label %right
4354     // left:
4355     //  br label %merge
4356     // right:
4357     //  br label %merge
4358     // merge:
4359     //  V = phi [ %x, %left ], [ %y, %right ]
4360     //
4361     // as "select %cond, %x, %y"
4362 
4363     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4364     assert(IDom && "At least the entry block should dominate PN");
4365 
4366     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4367     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4368 
4369     if (BI && BI->isConditional() &&
4370         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4371         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4372         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4373       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4374   }
4375 
4376   return nullptr;
4377 }
4378 
4379 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4380   if (const SCEV *S = createAddRecFromPHI(PN))
4381     return S;
4382 
4383   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4384     return S;
4385 
4386   // If the PHI has a single incoming value, follow that value, unless the
4387   // PHI's incoming blocks are in a different loop, in which case doing so
4388   // risks breaking LCSSA form. Instcombine would normally zap these, but
4389   // it doesn't have DominatorTree information, so it may miss cases.
4390   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4391     if (LI.replacementPreservesLCSSAForm(PN, V))
4392       return getSCEV(V);
4393 
4394   // If it's not a loop phi, we can't handle it yet.
4395   return getUnknown(PN);
4396 }
4397 
4398 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4399                                                       Value *Cond,
4400                                                       Value *TrueVal,
4401                                                       Value *FalseVal) {
4402   // Handle "constant" branch or select. This can occur for instance when a
4403   // loop pass transforms an inner loop and moves on to process the outer loop.
4404   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4405     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4406 
4407   // Try to match some simple smax or umax patterns.
4408   auto *ICI = dyn_cast<ICmpInst>(Cond);
4409   if (!ICI)
4410     return getUnknown(I);
4411 
4412   Value *LHS = ICI->getOperand(0);
4413   Value *RHS = ICI->getOperand(1);
4414 
4415   switch (ICI->getPredicate()) {
4416   case ICmpInst::ICMP_SLT:
4417   case ICmpInst::ICMP_SLE:
4418     std::swap(LHS, RHS);
4419     LLVM_FALLTHROUGH;
4420   case ICmpInst::ICMP_SGT:
4421   case ICmpInst::ICMP_SGE:
4422     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4423     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4424     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4425       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4426       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4427       const SCEV *LA = getSCEV(TrueVal);
4428       const SCEV *RA = getSCEV(FalseVal);
4429       const SCEV *LDiff = getMinusSCEV(LA, LS);
4430       const SCEV *RDiff = getMinusSCEV(RA, RS);
4431       if (LDiff == RDiff)
4432         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4433       LDiff = getMinusSCEV(LA, RS);
4434       RDiff = getMinusSCEV(RA, LS);
4435       if (LDiff == RDiff)
4436         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4437     }
4438     break;
4439   case ICmpInst::ICMP_ULT:
4440   case ICmpInst::ICMP_ULE:
4441     std::swap(LHS, RHS);
4442     LLVM_FALLTHROUGH;
4443   case ICmpInst::ICMP_UGT:
4444   case ICmpInst::ICMP_UGE:
4445     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4446     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4447     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4448       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4449       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4450       const SCEV *LA = getSCEV(TrueVal);
4451       const SCEV *RA = getSCEV(FalseVal);
4452       const SCEV *LDiff = getMinusSCEV(LA, LS);
4453       const SCEV *RDiff = getMinusSCEV(RA, RS);
4454       if (LDiff == RDiff)
4455         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4456       LDiff = getMinusSCEV(LA, RS);
4457       RDiff = getMinusSCEV(RA, LS);
4458       if (LDiff == RDiff)
4459         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4460     }
4461     break;
4462   case ICmpInst::ICMP_NE:
4463     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4464     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4465         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4466       const SCEV *One = getOne(I->getType());
4467       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4468       const SCEV *LA = getSCEV(TrueVal);
4469       const SCEV *RA = getSCEV(FalseVal);
4470       const SCEV *LDiff = getMinusSCEV(LA, LS);
4471       const SCEV *RDiff = getMinusSCEV(RA, One);
4472       if (LDiff == RDiff)
4473         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4474     }
4475     break;
4476   case ICmpInst::ICMP_EQ:
4477     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4478     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4479         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4480       const SCEV *One = getOne(I->getType());
4481       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4482       const SCEV *LA = getSCEV(TrueVal);
4483       const SCEV *RA = getSCEV(FalseVal);
4484       const SCEV *LDiff = getMinusSCEV(LA, One);
4485       const SCEV *RDiff = getMinusSCEV(RA, LS);
4486       if (LDiff == RDiff)
4487         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4488     }
4489     break;
4490   default:
4491     break;
4492   }
4493 
4494   return getUnknown(I);
4495 }
4496 
4497 /// Expand GEP instructions into add and multiply operations. This allows them
4498 /// to be analyzed by regular SCEV code.
4499 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4500   // Don't attempt to analyze GEPs over unsized objects.
4501   if (!GEP->getSourceElementType()->isSized())
4502     return getUnknown(GEP);
4503 
4504   SmallVector<const SCEV *, 4> IndexExprs;
4505   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4506     IndexExprs.push_back(getSCEV(*Index));
4507   return getGEPExpr(GEP, IndexExprs);
4508 }
4509 
4510 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4511   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4512     return C->getAPInt().countTrailingZeros();
4513 
4514   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4515     return std::min(GetMinTrailingZeros(T->getOperand()),
4516                     (uint32_t)getTypeSizeInBits(T->getType()));
4517 
4518   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4519     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4520     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4521                ? getTypeSizeInBits(E->getType())
4522                : OpRes;
4523   }
4524 
4525   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4526     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4527     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4528                ? getTypeSizeInBits(E->getType())
4529                : OpRes;
4530   }
4531 
4532   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4533     // The result is the min of all operands results.
4534     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4535     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4536       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4537     return MinOpRes;
4538   }
4539 
4540   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4541     // The result is the sum of all operands results.
4542     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4543     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4544     for (unsigned i = 1, e = M->getNumOperands();
4545          SumOpRes != BitWidth && i != e; ++i)
4546       SumOpRes =
4547           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
4548     return SumOpRes;
4549   }
4550 
4551   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4552     // The result is the min of all operands results.
4553     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4554     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4555       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4556     return MinOpRes;
4557   }
4558 
4559   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4560     // The result is the min of all operands results.
4561     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4562     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4563       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4564     return MinOpRes;
4565   }
4566 
4567   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4568     // The result is the min of all operands results.
4569     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4570     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4571       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4572     return MinOpRes;
4573   }
4574 
4575   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4576     // For a SCEVUnknown, ask ValueTracking.
4577     unsigned BitWidth = getTypeSizeInBits(U->getType());
4578     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4579     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4580                      nullptr, &DT);
4581     return Zeros.countTrailingOnes();
4582   }
4583 
4584   // SCEVUDivExpr
4585   return 0;
4586 }
4587 
4588 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4589   auto I = MinTrailingZerosCache.find(S);
4590   if (I != MinTrailingZerosCache.end())
4591     return I->second;
4592 
4593   uint32_t Result = GetMinTrailingZerosImpl(S);
4594   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
4595   assert(InsertPair.second && "Should insert a new key");
4596   return InsertPair.first->second;
4597 }
4598 
4599 /// Helper method to assign a range to V from metadata present in the IR.
4600 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4601   if (Instruction *I = dyn_cast<Instruction>(V))
4602     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4603       return getConstantRangeFromMetadata(*MD);
4604 
4605   return None;
4606 }
4607 
4608 /// Determine the range for a particular SCEV.  If SignHint is
4609 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4610 /// with a "cleaner" unsigned (resp. signed) representation.
4611 ConstantRange
4612 ScalarEvolution::getRange(const SCEV *S,
4613                           ScalarEvolution::RangeSignHint SignHint) {
4614   DenseMap<const SCEV *, ConstantRange> &Cache =
4615       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4616                                                        : SignedRanges;
4617 
4618   // See if we've computed this range already.
4619   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4620   if (I != Cache.end())
4621     return I->second;
4622 
4623   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4624     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4625 
4626   unsigned BitWidth = getTypeSizeInBits(S->getType());
4627   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4628 
4629   // If the value has known zeros, the maximum value will have those known zeros
4630   // as well.
4631   uint32_t TZ = GetMinTrailingZeros(S);
4632   if (TZ != 0) {
4633     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4634       ConservativeResult =
4635           ConstantRange(APInt::getMinValue(BitWidth),
4636                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4637     else
4638       ConservativeResult = ConstantRange(
4639           APInt::getSignedMinValue(BitWidth),
4640           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4641   }
4642 
4643   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4644     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4645     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4646       X = X.add(getRange(Add->getOperand(i), SignHint));
4647     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4648   }
4649 
4650   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4651     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4652     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4653       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4654     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4655   }
4656 
4657   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4658     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4659     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4660       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4661     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4662   }
4663 
4664   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4665     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4666     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4667       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4668     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4669   }
4670 
4671   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4672     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4673     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4674     return setRange(UDiv, SignHint,
4675                     ConservativeResult.intersectWith(X.udiv(Y)));
4676   }
4677 
4678   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4679     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4680     return setRange(ZExt, SignHint,
4681                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4682   }
4683 
4684   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4685     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4686     return setRange(SExt, SignHint,
4687                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4688   }
4689 
4690   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4691     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4692     return setRange(Trunc, SignHint,
4693                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4694   }
4695 
4696   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4697     // If there's no unsigned wrap, the value will never be less than its
4698     // initial value.
4699     if (AddRec->hasNoUnsignedWrap())
4700       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4701         if (!C->getValue()->isZero())
4702           ConservativeResult = ConservativeResult.intersectWith(
4703               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4704 
4705     // If there's no signed wrap, and all the operands have the same sign or
4706     // zero, the value won't ever change sign.
4707     if (AddRec->hasNoSignedWrap()) {
4708       bool AllNonNeg = true;
4709       bool AllNonPos = true;
4710       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4711         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4712         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4713       }
4714       if (AllNonNeg)
4715         ConservativeResult = ConservativeResult.intersectWith(
4716           ConstantRange(APInt(BitWidth, 0),
4717                         APInt::getSignedMinValue(BitWidth)));
4718       else if (AllNonPos)
4719         ConservativeResult = ConservativeResult.intersectWith(
4720           ConstantRange(APInt::getSignedMinValue(BitWidth),
4721                         APInt(BitWidth, 1)));
4722     }
4723 
4724     // TODO: non-affine addrec
4725     if (AddRec->isAffine()) {
4726       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4727       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4728           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4729         auto RangeFromAffine = getRangeForAffineAR(
4730             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4731             BitWidth);
4732         if (!RangeFromAffine.isFullSet())
4733           ConservativeResult =
4734               ConservativeResult.intersectWith(RangeFromAffine);
4735 
4736         auto RangeFromFactoring = getRangeViaFactoring(
4737             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4738             BitWidth);
4739         if (!RangeFromFactoring.isFullSet())
4740           ConservativeResult =
4741               ConservativeResult.intersectWith(RangeFromFactoring);
4742       }
4743     }
4744 
4745     return setRange(AddRec, SignHint, ConservativeResult);
4746   }
4747 
4748   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4749     // Check if the IR explicitly contains !range metadata.
4750     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4751     if (MDRange.hasValue())
4752       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4753 
4754     // Split here to avoid paying the compile-time cost of calling both
4755     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4756     // if needed.
4757     const DataLayout &DL = getDataLayout();
4758     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4759       // For a SCEVUnknown, ask ValueTracking.
4760       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4761       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4762       if (Ones != ~Zeros + 1)
4763         ConservativeResult =
4764             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4765     } else {
4766       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4767              "generalize as needed!");
4768       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4769       if (NS > 1)
4770         ConservativeResult = ConservativeResult.intersectWith(
4771             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4772                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4773     }
4774 
4775     return setRange(U, SignHint, ConservativeResult);
4776   }
4777 
4778   return setRange(S, SignHint, ConservativeResult);
4779 }
4780 
4781 // Given a StartRange, Step and MaxBECount for an expression compute a range of
4782 // values that the expression can take. Initially, the expression has a value
4783 // from StartRange and then is changed by Step up to MaxBECount times. Signed
4784 // argument defines if we treat Step as signed or unsigned.
4785 static ConstantRange getRangeForAffineARHelper(APInt Step,
4786                                                ConstantRange StartRange,
4787                                                APInt MaxBECount,
4788                                                unsigned BitWidth, bool Signed) {
4789   // If either Step or MaxBECount is 0, then the expression won't change, and we
4790   // just need to return the initial range.
4791   if (Step == 0 || MaxBECount == 0)
4792     return StartRange;
4793 
4794   // If we don't know anything about the initial value (i.e. StartRange is
4795   // FullRange), then we don't know anything about the final range either.
4796   // Return FullRange.
4797   if (StartRange.isFullSet())
4798     return ConstantRange(BitWidth, /* isFullSet = */ true);
4799 
4800   // If Step is signed and negative, then we use its absolute value, but we also
4801   // note that we're moving in the opposite direction.
4802   bool Descending = Signed && Step.isNegative();
4803 
4804   if (Signed)
4805     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
4806     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
4807     // This equations hold true due to the well-defined wrap-around behavior of
4808     // APInt.
4809     Step = Step.abs();
4810 
4811   // Check if Offset is more than full span of BitWidth. If it is, the
4812   // expression is guaranteed to overflow.
4813   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
4814     return ConstantRange(BitWidth, /* isFullSet = */ true);
4815 
4816   // Offset is by how much the expression can change. Checks above guarantee no
4817   // overflow here.
4818   APInt Offset = Step * MaxBECount;
4819 
4820   // Minimum value of the final range will match the minimal value of StartRange
4821   // if the expression is increasing and will be decreased by Offset otherwise.
4822   // Maximum value of the final range will match the maximal value of StartRange
4823   // if the expression is decreasing and will be increased by Offset otherwise.
4824   APInt StartLower = StartRange.getLower();
4825   APInt StartUpper = StartRange.getUpper() - 1;
4826   APInt MovedBoundary =
4827       Descending ? (StartLower - Offset) : (StartUpper + Offset);
4828 
4829   // It's possible that the new minimum/maximum value will fall into the initial
4830   // range (due to wrap around). This means that the expression can take any
4831   // value in this bitwidth, and we have to return full range.
4832   if (StartRange.contains(MovedBoundary))
4833     return ConstantRange(BitWidth, /* isFullSet = */ true);
4834 
4835   APInt NewLower, NewUpper;
4836   if (Descending) {
4837     NewLower = MovedBoundary;
4838     NewUpper = StartUpper;
4839   } else {
4840     NewLower = StartLower;
4841     NewUpper = MovedBoundary;
4842   }
4843 
4844   // If we end up with full range, return a proper full range.
4845   if (NewLower == NewUpper + 1)
4846     return ConstantRange(BitWidth, /* isFullSet = */ true);
4847 
4848   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
4849   return ConstantRange(NewLower, NewUpper + 1);
4850 }
4851 
4852 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4853                                                    const SCEV *Step,
4854                                                    const SCEV *MaxBECount,
4855                                                    unsigned BitWidth) {
4856   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4857          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4858          "Precondition!");
4859 
4860   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4861   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4862   APInt MaxBECountValue = MaxBECountRange.getUnsignedMax();
4863 
4864   // First, consider step signed.
4865   ConstantRange StartSRange = getSignedRange(Start);
4866   ConstantRange StepSRange = getSignedRange(Step);
4867 
4868   // If Step can be both positive and negative, we need to find ranges for the
4869   // maximum absolute step values in both directions and union them.
4870   ConstantRange SR =
4871       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
4872                                 MaxBECountValue, BitWidth, /* Signed = */ true);
4873   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
4874                                               StartSRange, MaxBECountValue,
4875                                               BitWidth, /* Signed = */ true));
4876 
4877   // Next, consider step unsigned.
4878   ConstantRange UR = getRangeForAffineARHelper(
4879       getUnsignedRange(Step).getUnsignedMax(), getUnsignedRange(Start),
4880       MaxBECountValue, BitWidth, /* Signed = */ false);
4881 
4882   // Finally, intersect signed and unsigned ranges.
4883   return SR.intersectWith(UR);
4884 }
4885 
4886 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4887                                                     const SCEV *Step,
4888                                                     const SCEV *MaxBECount,
4889                                                     unsigned BitWidth) {
4890   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4891   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4892 
4893   struct SelectPattern {
4894     Value *Condition = nullptr;
4895     APInt TrueValue;
4896     APInt FalseValue;
4897 
4898     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4899                            const SCEV *S) {
4900       Optional<unsigned> CastOp;
4901       APInt Offset(BitWidth, 0);
4902 
4903       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4904              "Should be!");
4905 
4906       // Peel off a constant offset:
4907       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4908         // In the future we could consider being smarter here and handle
4909         // {Start+Step,+,Step} too.
4910         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4911           return;
4912 
4913         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4914         S = SA->getOperand(1);
4915       }
4916 
4917       // Peel off a cast operation
4918       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4919         CastOp = SCast->getSCEVType();
4920         S = SCast->getOperand();
4921       }
4922 
4923       using namespace llvm::PatternMatch;
4924 
4925       auto *SU = dyn_cast<SCEVUnknown>(S);
4926       const APInt *TrueVal, *FalseVal;
4927       if (!SU ||
4928           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4929                                           m_APInt(FalseVal)))) {
4930         Condition = nullptr;
4931         return;
4932       }
4933 
4934       TrueValue = *TrueVal;
4935       FalseValue = *FalseVal;
4936 
4937       // Re-apply the cast we peeled off earlier
4938       if (CastOp.hasValue())
4939         switch (*CastOp) {
4940         default:
4941           llvm_unreachable("Unknown SCEV cast type!");
4942 
4943         case scTruncate:
4944           TrueValue = TrueValue.trunc(BitWidth);
4945           FalseValue = FalseValue.trunc(BitWidth);
4946           break;
4947         case scZeroExtend:
4948           TrueValue = TrueValue.zext(BitWidth);
4949           FalseValue = FalseValue.zext(BitWidth);
4950           break;
4951         case scSignExtend:
4952           TrueValue = TrueValue.sext(BitWidth);
4953           FalseValue = FalseValue.sext(BitWidth);
4954           break;
4955         }
4956 
4957       // Re-apply the constant offset we peeled off earlier
4958       TrueValue += Offset;
4959       FalseValue += Offset;
4960     }
4961 
4962     bool isRecognized() { return Condition != nullptr; }
4963   };
4964 
4965   SelectPattern StartPattern(*this, BitWidth, Start);
4966   if (!StartPattern.isRecognized())
4967     return ConstantRange(BitWidth, /* isFullSet = */ true);
4968 
4969   SelectPattern StepPattern(*this, BitWidth, Step);
4970   if (!StepPattern.isRecognized())
4971     return ConstantRange(BitWidth, /* isFullSet = */ true);
4972 
4973   if (StartPattern.Condition != StepPattern.Condition) {
4974     // We don't handle this case today; but we could, by considering four
4975     // possibilities below instead of two. I'm not sure if there are cases where
4976     // that will help over what getRange already does, though.
4977     return ConstantRange(BitWidth, /* isFullSet = */ true);
4978   }
4979 
4980   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4981   // construct arbitrary general SCEV expressions here.  This function is called
4982   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4983   // say) can end up caching a suboptimal value.
4984 
4985   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4986   // C2352 and C2512 (otherwise it isn't needed).
4987 
4988   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4989   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4990   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4991   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4992 
4993   ConstantRange TrueRange =
4994       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4995   ConstantRange FalseRange =
4996       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4997 
4998   return TrueRange.unionWith(FalseRange);
4999 }
5000 
5001 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5002   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5003   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5004 
5005   // Return early if there are no flags to propagate to the SCEV.
5006   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5007   if (BinOp->hasNoUnsignedWrap())
5008     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5009   if (BinOp->hasNoSignedWrap())
5010     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5011   if (Flags == SCEV::FlagAnyWrap)
5012     return SCEV::FlagAnyWrap;
5013 
5014   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5015 }
5016 
5017 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5018   // Here we check that I is in the header of the innermost loop containing I,
5019   // since we only deal with instructions in the loop header. The actual loop we
5020   // need to check later will come from an add recurrence, but getting that
5021   // requires computing the SCEV of the operands, which can be expensive. This
5022   // check we can do cheaply to rule out some cases early.
5023   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5024   if (InnermostContainingLoop == nullptr ||
5025       InnermostContainingLoop->getHeader() != I->getParent())
5026     return false;
5027 
5028   // Only proceed if we can prove that I does not yield poison.
5029   if (!isKnownNotFullPoison(I)) return false;
5030 
5031   // At this point we know that if I is executed, then it does not wrap
5032   // according to at least one of NSW or NUW. If I is not executed, then we do
5033   // not know if the calculation that I represents would wrap. Multiple
5034   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5035   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5036   // derived from other instructions that map to the same SCEV. We cannot make
5037   // that guarantee for cases where I is not executed. So we need to find the
5038   // loop that I is considered in relation to and prove that I is executed for
5039   // every iteration of that loop. That implies that the value that I
5040   // calculates does not wrap anywhere in the loop, so then we can apply the
5041   // flags to the SCEV.
5042   //
5043   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5044   // from different loops, so that we know which loop to prove that I is
5045   // executed in.
5046   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5047     // I could be an extractvalue from a call to an overflow intrinsic.
5048     // TODO: We can do better here in some cases.
5049     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5050       return false;
5051     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5052     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5053       bool AllOtherOpsLoopInvariant = true;
5054       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5055            ++OtherOpIndex) {
5056         if (OtherOpIndex != OpIndex) {
5057           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5058           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5059             AllOtherOpsLoopInvariant = false;
5060             break;
5061           }
5062         }
5063       }
5064       if (AllOtherOpsLoopInvariant &&
5065           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5066         return true;
5067     }
5068   }
5069   return false;
5070 }
5071 
5072 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5073   // If we know that \c I can never be poison period, then that's enough.
5074   if (isSCEVExprNeverPoison(I))
5075     return true;
5076 
5077   // For an add recurrence specifically, we assume that infinite loops without
5078   // side effects are undefined behavior, and then reason as follows:
5079   //
5080   // If the add recurrence is poison in any iteration, it is poison on all
5081   // future iterations (since incrementing poison yields poison). If the result
5082   // of the add recurrence is fed into the loop latch condition and the loop
5083   // does not contain any throws or exiting blocks other than the latch, we now
5084   // have the ability to "choose" whether the backedge is taken or not (by
5085   // choosing a sufficiently evil value for the poison feeding into the branch)
5086   // for every iteration including and after the one in which \p I first became
5087   // poison.  There are two possibilities (let's call the iteration in which \p
5088   // I first became poison as K):
5089   //
5090   //  1. In the set of iterations including and after K, the loop body executes
5091   //     no side effects.  In this case executing the backege an infinte number
5092   //     of times will yield undefined behavior.
5093   //
5094   //  2. In the set of iterations including and after K, the loop body executes
5095   //     at least one side effect.  In this case, that specific instance of side
5096   //     effect is control dependent on poison, which also yields undefined
5097   //     behavior.
5098 
5099   auto *ExitingBB = L->getExitingBlock();
5100   auto *LatchBB = L->getLoopLatch();
5101   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5102     return false;
5103 
5104   SmallPtrSet<const Instruction *, 16> Pushed;
5105   SmallVector<const Instruction *, 8> PoisonStack;
5106 
5107   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5108   // things that are known to be fully poison under that assumption go on the
5109   // PoisonStack.
5110   Pushed.insert(I);
5111   PoisonStack.push_back(I);
5112 
5113   bool LatchControlDependentOnPoison = false;
5114   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5115     const Instruction *Poison = PoisonStack.pop_back_val();
5116 
5117     for (auto *PoisonUser : Poison->users()) {
5118       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5119         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5120           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5121       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5122         assert(BI->isConditional() && "Only possibility!");
5123         if (BI->getParent() == LatchBB) {
5124           LatchControlDependentOnPoison = true;
5125           break;
5126         }
5127       }
5128     }
5129   }
5130 
5131   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5132 }
5133 
5134 ScalarEvolution::LoopProperties
5135 ScalarEvolution::getLoopProperties(const Loop *L) {
5136   typedef ScalarEvolution::LoopProperties LoopProperties;
5137 
5138   auto Itr = LoopPropertiesCache.find(L);
5139   if (Itr == LoopPropertiesCache.end()) {
5140     auto HasSideEffects = [](Instruction *I) {
5141       if (auto *SI = dyn_cast<StoreInst>(I))
5142         return !SI->isSimple();
5143 
5144       return I->mayHaveSideEffects();
5145     };
5146 
5147     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5148                          /*HasNoSideEffects*/ true};
5149 
5150     for (auto *BB : L->getBlocks())
5151       for (auto &I : *BB) {
5152         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5153           LP.HasNoAbnormalExits = false;
5154         if (HasSideEffects(&I))
5155           LP.HasNoSideEffects = false;
5156         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5157           break; // We're already as pessimistic as we can get.
5158       }
5159 
5160     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5161     assert(InsertPair.second && "We just checked!");
5162     Itr = InsertPair.first;
5163   }
5164 
5165   return Itr->second;
5166 }
5167 
5168 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5169   if (!isSCEVable(V->getType()))
5170     return getUnknown(V);
5171 
5172   if (Instruction *I = dyn_cast<Instruction>(V)) {
5173     // Don't attempt to analyze instructions in blocks that aren't
5174     // reachable. Such instructions don't matter, and they aren't required
5175     // to obey basic rules for definitions dominating uses which this
5176     // analysis depends on.
5177     if (!DT.isReachableFromEntry(I->getParent()))
5178       return getUnknown(V);
5179   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5180     return getConstant(CI);
5181   else if (isa<ConstantPointerNull>(V))
5182     return getZero(V->getType());
5183   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5184     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5185   else if (!isa<ConstantExpr>(V))
5186     return getUnknown(V);
5187 
5188   Operator *U = cast<Operator>(V);
5189   if (auto BO = MatchBinaryOp(U, DT)) {
5190     switch (BO->Opcode) {
5191     case Instruction::Add: {
5192       // The simple thing to do would be to just call getSCEV on both operands
5193       // and call getAddExpr with the result. However if we're looking at a
5194       // bunch of things all added together, this can be quite inefficient,
5195       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5196       // Instead, gather up all the operands and make a single getAddExpr call.
5197       // LLVM IR canonical form means we need only traverse the left operands.
5198       SmallVector<const SCEV *, 4> AddOps;
5199       do {
5200         if (BO->Op) {
5201           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5202             AddOps.push_back(OpSCEV);
5203             break;
5204           }
5205 
5206           // If a NUW or NSW flag can be applied to the SCEV for this
5207           // addition, then compute the SCEV for this addition by itself
5208           // with a separate call to getAddExpr. We need to do that
5209           // instead of pushing the operands of the addition onto AddOps,
5210           // since the flags are only known to apply to this particular
5211           // addition - they may not apply to other additions that can be
5212           // formed with operands from AddOps.
5213           const SCEV *RHS = getSCEV(BO->RHS);
5214           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5215           if (Flags != SCEV::FlagAnyWrap) {
5216             const SCEV *LHS = getSCEV(BO->LHS);
5217             if (BO->Opcode == Instruction::Sub)
5218               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5219             else
5220               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5221             break;
5222           }
5223         }
5224 
5225         if (BO->Opcode == Instruction::Sub)
5226           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5227         else
5228           AddOps.push_back(getSCEV(BO->RHS));
5229 
5230         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5231         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5232                        NewBO->Opcode != Instruction::Sub)) {
5233           AddOps.push_back(getSCEV(BO->LHS));
5234           break;
5235         }
5236         BO = NewBO;
5237       } while (true);
5238 
5239       return getAddExpr(AddOps);
5240     }
5241 
5242     case Instruction::Mul: {
5243       SmallVector<const SCEV *, 4> MulOps;
5244       do {
5245         if (BO->Op) {
5246           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5247             MulOps.push_back(OpSCEV);
5248             break;
5249           }
5250 
5251           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5252           if (Flags != SCEV::FlagAnyWrap) {
5253             MulOps.push_back(
5254                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5255             break;
5256           }
5257         }
5258 
5259         MulOps.push_back(getSCEV(BO->RHS));
5260         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5261         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5262           MulOps.push_back(getSCEV(BO->LHS));
5263           break;
5264         }
5265         BO = NewBO;
5266       } while (true);
5267 
5268       return getMulExpr(MulOps);
5269     }
5270     case Instruction::UDiv:
5271       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5272     case Instruction::Sub: {
5273       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5274       if (BO->Op)
5275         Flags = getNoWrapFlagsFromUB(BO->Op);
5276       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5277     }
5278     case Instruction::And:
5279       // For an expression like x&255 that merely masks off the high bits,
5280       // use zext(trunc(x)) as the SCEV expression.
5281       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5282         if (CI->isNullValue())
5283           return getSCEV(BO->RHS);
5284         if (CI->isAllOnesValue())
5285           return getSCEV(BO->LHS);
5286         const APInt &A = CI->getValue();
5287 
5288         // Instcombine's ShrinkDemandedConstant may strip bits out of
5289         // constants, obscuring what would otherwise be a low-bits mask.
5290         // Use computeKnownBits to compute what ShrinkDemandedConstant
5291         // knew about to reconstruct a low-bits mask value.
5292         unsigned LZ = A.countLeadingZeros();
5293         unsigned TZ = A.countTrailingZeros();
5294         unsigned BitWidth = A.getBitWidth();
5295         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5296         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5297                          0, &AC, nullptr, &DT);
5298 
5299         APInt EffectiveMask =
5300             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5301         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5302           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5303           const SCEV *LHS = getSCEV(BO->LHS);
5304           const SCEV *ShiftedLHS = nullptr;
5305           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5306             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5307               // For an expression like (x * 8) & 8, simplify the multiply.
5308               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5309               unsigned GCD = std::min(MulZeros, TZ);
5310               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5311               SmallVector<const SCEV*, 4> MulOps;
5312               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5313               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5314               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5315               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5316             }
5317           }
5318           if (!ShiftedLHS)
5319             ShiftedLHS = getUDivExpr(LHS, MulCount);
5320           return getMulExpr(
5321               getZeroExtendExpr(
5322                   getTruncateExpr(ShiftedLHS,
5323                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5324                   BO->LHS->getType()),
5325               MulCount);
5326         }
5327       }
5328       break;
5329 
5330     case Instruction::Or:
5331       // If the RHS of the Or is a constant, we may have something like:
5332       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5333       // optimizations will transparently handle this case.
5334       //
5335       // In order for this transformation to be safe, the LHS must be of the
5336       // form X*(2^n) and the Or constant must be less than 2^n.
5337       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5338         const SCEV *LHS = getSCEV(BO->LHS);
5339         const APInt &CIVal = CI->getValue();
5340         if (GetMinTrailingZeros(LHS) >=
5341             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5342           // Build a plain add SCEV.
5343           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5344           // If the LHS of the add was an addrec and it has no-wrap flags,
5345           // transfer the no-wrap flags, since an or won't introduce a wrap.
5346           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5347             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5348             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5349                 OldAR->getNoWrapFlags());
5350           }
5351           return S;
5352         }
5353       }
5354       break;
5355 
5356     case Instruction::Xor:
5357       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5358         // If the RHS of xor is -1, then this is a not operation.
5359         if (CI->isAllOnesValue())
5360           return getNotSCEV(getSCEV(BO->LHS));
5361 
5362         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5363         // This is a variant of the check for xor with -1, and it handles
5364         // the case where instcombine has trimmed non-demanded bits out
5365         // of an xor with -1.
5366         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5367           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5368             if (LBO->getOpcode() == Instruction::And &&
5369                 LCI->getValue() == CI->getValue())
5370               if (const SCEVZeroExtendExpr *Z =
5371                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5372                 Type *UTy = BO->LHS->getType();
5373                 const SCEV *Z0 = Z->getOperand();
5374                 Type *Z0Ty = Z0->getType();
5375                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5376 
5377                 // If C is a low-bits mask, the zero extend is serving to
5378                 // mask off the high bits. Complement the operand and
5379                 // re-apply the zext.
5380                 if (CI->getValue().isMask(Z0TySize))
5381                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5382 
5383                 // If C is a single bit, it may be in the sign-bit position
5384                 // before the zero-extend. In this case, represent the xor
5385                 // using an add, which is equivalent, and re-apply the zext.
5386                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5387                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5388                     Trunc.isSignBit())
5389                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5390                                            UTy);
5391               }
5392       }
5393       break;
5394 
5395   case Instruction::Shl:
5396     // Turn shift left of a constant amount into a multiply.
5397     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5398       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5399 
5400       // If the shift count is not less than the bitwidth, the result of
5401       // the shift is undefined. Don't try to analyze it, because the
5402       // resolution chosen here may differ from the resolution chosen in
5403       // other parts of the compiler.
5404       if (SA->getValue().uge(BitWidth))
5405         break;
5406 
5407       // It is currently not resolved how to interpret NSW for left
5408       // shift by BitWidth - 1, so we avoid applying flags in that
5409       // case. Remove this check (or this comment) once the situation
5410       // is resolved. See
5411       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5412       // and http://reviews.llvm.org/D8890 .
5413       auto Flags = SCEV::FlagAnyWrap;
5414       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5415         Flags = getNoWrapFlagsFromUB(BO->Op);
5416 
5417       Constant *X = ConstantInt::get(getContext(),
5418         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5419       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5420     }
5421     break;
5422 
5423     case Instruction::AShr:
5424       // AShr X, C, where C is a constant.
5425       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5426       if (!CI)
5427         break;
5428 
5429       Type *OuterTy = BO->LHS->getType();
5430       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5431       // If the shift count is not less than the bitwidth, the result of
5432       // the shift is undefined. Don't try to analyze it, because the
5433       // resolution chosen here may differ from the resolution chosen in
5434       // other parts of the compiler.
5435       if (CI->getValue().uge(BitWidth))
5436         break;
5437 
5438       if (CI->isNullValue())
5439         return getSCEV(BO->LHS); // shift by zero --> noop
5440 
5441       uint64_t AShrAmt = CI->getZExtValue();
5442       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5443 
5444       Operator *L = dyn_cast<Operator>(BO->LHS);
5445       if (L && L->getOpcode() == Instruction::Shl) {
5446         // X = Shl A, n
5447         // Y = AShr X, m
5448         // Both n and m are constant.
5449 
5450         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5451         if (L->getOperand(1) == BO->RHS)
5452           // For a two-shift sext-inreg, i.e. n = m,
5453           // use sext(trunc(x)) as the SCEV expression.
5454           return getSignExtendExpr(
5455               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5456 
5457         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5458         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5459           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5460           if (ShlAmt > AShrAmt) {
5461             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5462             // expression. We already checked that ShlAmt < BitWidth, so
5463             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5464             // ShlAmt - AShrAmt < Amt.
5465             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5466                                             ShlAmt - AShrAmt);
5467             return getSignExtendExpr(
5468                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5469                 getConstant(Mul)), OuterTy);
5470           }
5471         }
5472       }
5473       break;
5474     }
5475   }
5476 
5477   switch (U->getOpcode()) {
5478   case Instruction::Trunc:
5479     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5480 
5481   case Instruction::ZExt:
5482     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5483 
5484   case Instruction::SExt:
5485     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5486 
5487   case Instruction::BitCast:
5488     // BitCasts are no-op casts so we just eliminate the cast.
5489     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5490       return getSCEV(U->getOperand(0));
5491     break;
5492 
5493   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5494   // lead to pointer expressions which cannot safely be expanded to GEPs,
5495   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5496   // simplifying integer expressions.
5497 
5498   case Instruction::GetElementPtr:
5499     return createNodeForGEP(cast<GEPOperator>(U));
5500 
5501   case Instruction::PHI:
5502     return createNodeForPHI(cast<PHINode>(U));
5503 
5504   case Instruction::Select:
5505     // U can also be a select constant expr, which let fall through.  Since
5506     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5507     // constant expressions cannot have instructions as operands, we'd have
5508     // returned getUnknown for a select constant expressions anyway.
5509     if (isa<Instruction>(U))
5510       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5511                                       U->getOperand(1), U->getOperand(2));
5512     break;
5513 
5514   case Instruction::Call:
5515   case Instruction::Invoke:
5516     if (Value *RV = CallSite(U).getReturnedArgOperand())
5517       return getSCEV(RV);
5518     break;
5519   }
5520 
5521   return getUnknown(V);
5522 }
5523 
5524 
5525 
5526 //===----------------------------------------------------------------------===//
5527 //                   Iteration Count Computation Code
5528 //
5529 
5530 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5531   if (!ExitCount)
5532     return 0;
5533 
5534   ConstantInt *ExitConst = ExitCount->getValue();
5535 
5536   // Guard against huge trip counts.
5537   if (ExitConst->getValue().getActiveBits() > 32)
5538     return 0;
5539 
5540   // In case of integer overflow, this returns 0, which is correct.
5541   return ((unsigned)ExitConst->getZExtValue()) + 1;
5542 }
5543 
5544 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
5545   if (BasicBlock *ExitingBB = L->getExitingBlock())
5546     return getSmallConstantTripCount(L, ExitingBB);
5547 
5548   // No trip count information for multiple exits.
5549   return 0;
5550 }
5551 
5552 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
5553                                                     BasicBlock *ExitingBlock) {
5554   assert(ExitingBlock && "Must pass a non-null exiting block!");
5555   assert(L->isLoopExiting(ExitingBlock) &&
5556          "Exiting block must actually branch out of the loop!");
5557   const SCEVConstant *ExitCount =
5558       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5559   return getConstantTripCount(ExitCount);
5560 }
5561 
5562 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
5563   const auto *MaxExitCount =
5564       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5565   return getConstantTripCount(MaxExitCount);
5566 }
5567 
5568 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
5569   if (BasicBlock *ExitingBB = L->getExitingBlock())
5570     return getSmallConstantTripMultiple(L, ExitingBB);
5571 
5572   // No trip multiple information for multiple exits.
5573   return 0;
5574 }
5575 
5576 /// Returns the largest constant divisor of the trip count of this loop as a
5577 /// normal unsigned value, if possible. This means that the actual trip count is
5578 /// always a multiple of the returned value (don't forget the trip count could
5579 /// very well be zero as well!).
5580 ///
5581 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5582 /// multiple of a constant (which is also the case if the trip count is simply
5583 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5584 /// if the trip count is very large (>= 2^32).
5585 ///
5586 /// As explained in the comments for getSmallConstantTripCount, this assumes
5587 /// that control exits the loop via ExitingBlock.
5588 unsigned
5589 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
5590                                               BasicBlock *ExitingBlock) {
5591   assert(ExitingBlock && "Must pass a non-null exiting block!");
5592   assert(L->isLoopExiting(ExitingBlock) &&
5593          "Exiting block must actually branch out of the loop!");
5594   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5595   if (ExitCount == getCouldNotCompute())
5596     return 1;
5597 
5598   // Get the trip count from the BE count by adding 1.
5599   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5600 
5601   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
5602   if (!TC)
5603     // Attempt to factor more general cases. Returns the greatest power of
5604     // two divisor. If overflow happens, the trip count expression is still
5605     // divisible by the greatest power of 2 divisor returned.
5606     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
5607 
5608   ConstantInt *Result = TC->getValue();
5609 
5610   // Guard against huge trip counts (this requires checking
5611   // for zero to handle the case where the trip count == -1 and the
5612   // addition wraps).
5613   if (!Result || Result->getValue().getActiveBits() > 32 ||
5614       Result->getValue().getActiveBits() == 0)
5615     return 1;
5616 
5617   return (unsigned)Result->getZExtValue();
5618 }
5619 
5620 /// Get the expression for the number of loop iterations for which this loop is
5621 /// guaranteed not to exit via ExitingBlock. Otherwise return
5622 /// SCEVCouldNotCompute.
5623 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
5624                                           BasicBlock *ExitingBlock) {
5625   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5626 }
5627 
5628 const SCEV *
5629 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5630                                                  SCEVUnionPredicate &Preds) {
5631   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5632 }
5633 
5634 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5635   return getBackedgeTakenInfo(L).getExact(this);
5636 }
5637 
5638 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5639 /// known never to be less than the actual backedge taken count.
5640 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5641   return getBackedgeTakenInfo(L).getMax(this);
5642 }
5643 
5644 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5645   return getBackedgeTakenInfo(L).isMaxOrZero(this);
5646 }
5647 
5648 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5649 static void
5650 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5651   BasicBlock *Header = L->getHeader();
5652 
5653   // Push all Loop-header PHIs onto the Worklist stack.
5654   for (BasicBlock::iterator I = Header->begin();
5655        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5656     Worklist.push_back(PN);
5657 }
5658 
5659 const ScalarEvolution::BackedgeTakenInfo &
5660 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5661   auto &BTI = getBackedgeTakenInfo(L);
5662   if (BTI.hasFullInfo())
5663     return BTI;
5664 
5665   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5666 
5667   if (!Pair.second)
5668     return Pair.first->second;
5669 
5670   BackedgeTakenInfo Result =
5671       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5672 
5673   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5674 }
5675 
5676 const ScalarEvolution::BackedgeTakenInfo &
5677 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5678   // Initially insert an invalid entry for this loop. If the insertion
5679   // succeeds, proceed to actually compute a backedge-taken count and
5680   // update the value. The temporary CouldNotCompute value tells SCEV
5681   // code elsewhere that it shouldn't attempt to request a new
5682   // backedge-taken count, which could result in infinite recursion.
5683   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5684       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5685   if (!Pair.second)
5686     return Pair.first->second;
5687 
5688   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5689   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5690   // must be cleared in this scope.
5691   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5692 
5693   if (Result.getExact(this) != getCouldNotCompute()) {
5694     assert(isLoopInvariant(Result.getExact(this), L) &&
5695            isLoopInvariant(Result.getMax(this), L) &&
5696            "Computed backedge-taken count isn't loop invariant for loop!");
5697     ++NumTripCountsComputed;
5698   }
5699   else if (Result.getMax(this) == getCouldNotCompute() &&
5700            isa<PHINode>(L->getHeader()->begin())) {
5701     // Only count loops that have phi nodes as not being computable.
5702     ++NumTripCountsNotComputed;
5703   }
5704 
5705   // Now that we know more about the trip count for this loop, forget any
5706   // existing SCEV values for PHI nodes in this loop since they are only
5707   // conservative estimates made without the benefit of trip count
5708   // information. This is similar to the code in forgetLoop, except that
5709   // it handles SCEVUnknown PHI nodes specially.
5710   if (Result.hasAnyInfo()) {
5711     SmallVector<Instruction *, 16> Worklist;
5712     PushLoopPHIs(L, Worklist);
5713 
5714     SmallPtrSet<Instruction *, 8> Visited;
5715     while (!Worklist.empty()) {
5716       Instruction *I = Worklist.pop_back_val();
5717       if (!Visited.insert(I).second)
5718         continue;
5719 
5720       ValueExprMapType::iterator It =
5721         ValueExprMap.find_as(static_cast<Value *>(I));
5722       if (It != ValueExprMap.end()) {
5723         const SCEV *Old = It->second;
5724 
5725         // SCEVUnknown for a PHI either means that it has an unrecognized
5726         // structure, or it's a PHI that's in the progress of being computed
5727         // by createNodeForPHI.  In the former case, additional loop trip
5728         // count information isn't going to change anything. In the later
5729         // case, createNodeForPHI will perform the necessary updates on its
5730         // own when it gets to that point.
5731         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5732           eraseValueFromMap(It->first);
5733           forgetMemoizedResults(Old);
5734         }
5735         if (PHINode *PN = dyn_cast<PHINode>(I))
5736           ConstantEvolutionLoopExitValue.erase(PN);
5737       }
5738 
5739       PushDefUseChildren(I, Worklist);
5740     }
5741   }
5742 
5743   // Re-lookup the insert position, since the call to
5744   // computeBackedgeTakenCount above could result in a
5745   // recusive call to getBackedgeTakenInfo (on a different
5746   // loop), which would invalidate the iterator computed
5747   // earlier.
5748   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5749 }
5750 
5751 void ScalarEvolution::forgetLoop(const Loop *L) {
5752   // Drop any stored trip count value.
5753   auto RemoveLoopFromBackedgeMap =
5754       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5755         auto BTCPos = Map.find(L);
5756         if (BTCPos != Map.end()) {
5757           BTCPos->second.clear();
5758           Map.erase(BTCPos);
5759         }
5760       };
5761 
5762   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5763   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5764 
5765   // Drop information about expressions based on loop-header PHIs.
5766   SmallVector<Instruction *, 16> Worklist;
5767   PushLoopPHIs(L, Worklist);
5768 
5769   SmallPtrSet<Instruction *, 8> Visited;
5770   while (!Worklist.empty()) {
5771     Instruction *I = Worklist.pop_back_val();
5772     if (!Visited.insert(I).second)
5773       continue;
5774 
5775     ValueExprMapType::iterator It =
5776       ValueExprMap.find_as(static_cast<Value *>(I));
5777     if (It != ValueExprMap.end()) {
5778       eraseValueFromMap(It->first);
5779       forgetMemoizedResults(It->second);
5780       if (PHINode *PN = dyn_cast<PHINode>(I))
5781         ConstantEvolutionLoopExitValue.erase(PN);
5782     }
5783 
5784     PushDefUseChildren(I, Worklist);
5785   }
5786 
5787   // Forget all contained loops too, to avoid dangling entries in the
5788   // ValuesAtScopes map.
5789   for (Loop *I : *L)
5790     forgetLoop(I);
5791 
5792   LoopPropertiesCache.erase(L);
5793 }
5794 
5795 void ScalarEvolution::forgetValue(Value *V) {
5796   Instruction *I = dyn_cast<Instruction>(V);
5797   if (!I) return;
5798 
5799   // Drop information about expressions based on loop-header PHIs.
5800   SmallVector<Instruction *, 16> Worklist;
5801   Worklist.push_back(I);
5802 
5803   SmallPtrSet<Instruction *, 8> Visited;
5804   while (!Worklist.empty()) {
5805     I = Worklist.pop_back_val();
5806     if (!Visited.insert(I).second)
5807       continue;
5808 
5809     ValueExprMapType::iterator It =
5810       ValueExprMap.find_as(static_cast<Value *>(I));
5811     if (It != ValueExprMap.end()) {
5812       eraseValueFromMap(It->first);
5813       forgetMemoizedResults(It->second);
5814       if (PHINode *PN = dyn_cast<PHINode>(I))
5815         ConstantEvolutionLoopExitValue.erase(PN);
5816     }
5817 
5818     PushDefUseChildren(I, Worklist);
5819   }
5820 }
5821 
5822 /// Get the exact loop backedge taken count considering all loop exits. A
5823 /// computable result can only be returned for loops with a single exit.
5824 /// Returning the minimum taken count among all exits is incorrect because one
5825 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5826 /// the limit of each loop test is never skipped. This is a valid assumption as
5827 /// long as the loop exits via that test. For precise results, it is the
5828 /// caller's responsibility to specify the relevant loop exit using
5829 /// getExact(ExitingBlock, SE).
5830 const SCEV *
5831 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5832                                              SCEVUnionPredicate *Preds) const {
5833   // If any exits were not computable, the loop is not computable.
5834   if (!isComplete() || ExitNotTaken.empty())
5835     return SE->getCouldNotCompute();
5836 
5837   const SCEV *BECount = nullptr;
5838   for (auto &ENT : ExitNotTaken) {
5839     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5840 
5841     if (!BECount)
5842       BECount = ENT.ExactNotTaken;
5843     else if (BECount != ENT.ExactNotTaken)
5844       return SE->getCouldNotCompute();
5845     if (Preds && !ENT.hasAlwaysTruePredicate())
5846       Preds->add(ENT.Predicate.get());
5847 
5848     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5849            "Predicate should be always true!");
5850   }
5851 
5852   assert(BECount && "Invalid not taken count for loop exit");
5853   return BECount;
5854 }
5855 
5856 /// Get the exact not taken count for this loop exit.
5857 const SCEV *
5858 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5859                                              ScalarEvolution *SE) const {
5860   for (auto &ENT : ExitNotTaken)
5861     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5862       return ENT.ExactNotTaken;
5863 
5864   return SE->getCouldNotCompute();
5865 }
5866 
5867 /// getMax - Get the max backedge taken count for the loop.
5868 const SCEV *
5869 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5870   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5871     return !ENT.hasAlwaysTruePredicate();
5872   };
5873 
5874   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5875     return SE->getCouldNotCompute();
5876 
5877   return getMax();
5878 }
5879 
5880 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5881   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5882     return !ENT.hasAlwaysTruePredicate();
5883   };
5884   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5885 }
5886 
5887 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5888                                                     ScalarEvolution *SE) const {
5889   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5890       SE->hasOperand(getMax(), S))
5891     return true;
5892 
5893   for (auto &ENT : ExitNotTaken)
5894     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5895         SE->hasOperand(ENT.ExactNotTaken, S))
5896       return true;
5897 
5898   return false;
5899 }
5900 
5901 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5902 /// computable exit into a persistent ExitNotTakenInfo array.
5903 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5904     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5905         &&ExitCounts,
5906     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5907     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5908   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5909   ExitNotTaken.reserve(ExitCounts.size());
5910   std::transform(
5911       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5912       [&](const EdgeExitInfo &EEI) {
5913         BasicBlock *ExitBB = EEI.first;
5914         const ExitLimit &EL = EEI.second;
5915         if (EL.Predicates.empty())
5916           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5917 
5918         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5919         for (auto *Pred : EL.Predicates)
5920           Predicate->add(Pred);
5921 
5922         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5923       });
5924 }
5925 
5926 /// Invalidate this result and free the ExitNotTakenInfo array.
5927 void ScalarEvolution::BackedgeTakenInfo::clear() {
5928   ExitNotTaken.clear();
5929 }
5930 
5931 /// Compute the number of times the backedge of the specified loop will execute.
5932 ScalarEvolution::BackedgeTakenInfo
5933 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5934                                            bool AllowPredicates) {
5935   SmallVector<BasicBlock *, 8> ExitingBlocks;
5936   L->getExitingBlocks(ExitingBlocks);
5937 
5938   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5939 
5940   SmallVector<EdgeExitInfo, 4> ExitCounts;
5941   bool CouldComputeBECount = true;
5942   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5943   const SCEV *MustExitMaxBECount = nullptr;
5944   const SCEV *MayExitMaxBECount = nullptr;
5945   bool MustExitMaxOrZero = false;
5946 
5947   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5948   // and compute maxBECount.
5949   // Do a union of all the predicates here.
5950   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5951     BasicBlock *ExitBB = ExitingBlocks[i];
5952     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5953 
5954     assert((AllowPredicates || EL.Predicates.empty()) &&
5955            "Predicated exit limit when predicates are not allowed!");
5956 
5957     // 1. For each exit that can be computed, add an entry to ExitCounts.
5958     // CouldComputeBECount is true only if all exits can be computed.
5959     if (EL.ExactNotTaken == getCouldNotCompute())
5960       // We couldn't compute an exact value for this exit, so
5961       // we won't be able to compute an exact value for the loop.
5962       CouldComputeBECount = false;
5963     else
5964       ExitCounts.emplace_back(ExitBB, EL);
5965 
5966     // 2. Derive the loop's MaxBECount from each exit's max number of
5967     // non-exiting iterations. Partition the loop exits into two kinds:
5968     // LoopMustExits and LoopMayExits.
5969     //
5970     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5971     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5972     // MaxBECount is the minimum EL.MaxNotTaken of computable
5973     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5974     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5975     // computable EL.MaxNotTaken.
5976     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5977         DT.dominates(ExitBB, Latch)) {
5978       if (!MustExitMaxBECount) {
5979         MustExitMaxBECount = EL.MaxNotTaken;
5980         MustExitMaxOrZero = EL.MaxOrZero;
5981       } else {
5982         MustExitMaxBECount =
5983             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5984       }
5985     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5986       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5987         MayExitMaxBECount = EL.MaxNotTaken;
5988       else {
5989         MayExitMaxBECount =
5990             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5991       }
5992     }
5993   }
5994   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5995     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5996   // The loop backedge will be taken the maximum or zero times if there's
5997   // a single exit that must be taken the maximum or zero times.
5998   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
5999   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6000                            MaxBECount, MaxOrZero);
6001 }
6002 
6003 ScalarEvolution::ExitLimit
6004 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6005                                   bool AllowPredicates) {
6006 
6007   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6008   // at this block and remember the exit block and whether all other targets
6009   // lead to the loop header.
6010   bool MustExecuteLoopHeader = true;
6011   BasicBlock *Exit = nullptr;
6012   for (auto *SBB : successors(ExitingBlock))
6013     if (!L->contains(SBB)) {
6014       if (Exit) // Multiple exit successors.
6015         return getCouldNotCompute();
6016       Exit = SBB;
6017     } else if (SBB != L->getHeader()) {
6018       MustExecuteLoopHeader = false;
6019     }
6020 
6021   // At this point, we know we have a conditional branch that determines whether
6022   // the loop is exited.  However, we don't know if the branch is executed each
6023   // time through the loop.  If not, then the execution count of the branch will
6024   // not be equal to the trip count of the loop.
6025   //
6026   // Currently we check for this by checking to see if the Exit branch goes to
6027   // the loop header.  If so, we know it will always execute the same number of
6028   // times as the loop.  We also handle the case where the exit block *is* the
6029   // loop header.  This is common for un-rotated loops.
6030   //
6031   // If both of those tests fail, walk up the unique predecessor chain to the
6032   // header, stopping if there is an edge that doesn't exit the loop. If the
6033   // header is reached, the execution count of the branch will be equal to the
6034   // trip count of the loop.
6035   //
6036   //  More extensive analysis could be done to handle more cases here.
6037   //
6038   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6039     // The simple checks failed, try climbing the unique predecessor chain
6040     // up to the header.
6041     bool Ok = false;
6042     for (BasicBlock *BB = ExitingBlock; BB; ) {
6043       BasicBlock *Pred = BB->getUniquePredecessor();
6044       if (!Pred)
6045         return getCouldNotCompute();
6046       TerminatorInst *PredTerm = Pred->getTerminator();
6047       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6048         if (PredSucc == BB)
6049           continue;
6050         // If the predecessor has a successor that isn't BB and isn't
6051         // outside the loop, assume the worst.
6052         if (L->contains(PredSucc))
6053           return getCouldNotCompute();
6054       }
6055       if (Pred == L->getHeader()) {
6056         Ok = true;
6057         break;
6058       }
6059       BB = Pred;
6060     }
6061     if (!Ok)
6062       return getCouldNotCompute();
6063   }
6064 
6065   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6066   TerminatorInst *Term = ExitingBlock->getTerminator();
6067   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6068     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6069     // Proceed to the next level to examine the exit condition expression.
6070     return computeExitLimitFromCond(
6071         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6072         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6073   }
6074 
6075   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6076     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6077                                                 /*ControlsExit=*/IsOnlyExit);
6078 
6079   return getCouldNotCompute();
6080 }
6081 
6082 ScalarEvolution::ExitLimit
6083 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
6084                                           Value *ExitCond,
6085                                           BasicBlock *TBB,
6086                                           BasicBlock *FBB,
6087                                           bool ControlsExit,
6088                                           bool AllowPredicates) {
6089   // Check if the controlling expression for this loop is an And or Or.
6090   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6091     if (BO->getOpcode() == Instruction::And) {
6092       // Recurse on the operands of the and.
6093       bool EitherMayExit = L->contains(TBB);
6094       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
6095                                                ControlsExit && !EitherMayExit,
6096                                                AllowPredicates);
6097       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
6098                                                ControlsExit && !EitherMayExit,
6099                                                AllowPredicates);
6100       const SCEV *BECount = getCouldNotCompute();
6101       const SCEV *MaxBECount = getCouldNotCompute();
6102       if (EitherMayExit) {
6103         // Both conditions must be true for the loop to continue executing.
6104         // Choose the less conservative count.
6105         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6106             EL1.ExactNotTaken == getCouldNotCompute())
6107           BECount = getCouldNotCompute();
6108         else
6109           BECount =
6110               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6111         if (EL0.MaxNotTaken == getCouldNotCompute())
6112           MaxBECount = EL1.MaxNotTaken;
6113         else if (EL1.MaxNotTaken == getCouldNotCompute())
6114           MaxBECount = EL0.MaxNotTaken;
6115         else
6116           MaxBECount =
6117               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6118       } else {
6119         // Both conditions must be true at the same time for the loop to exit.
6120         // For now, be conservative.
6121         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6122         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6123           MaxBECount = EL0.MaxNotTaken;
6124         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6125           BECount = EL0.ExactNotTaken;
6126       }
6127 
6128       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6129       // to be more aggressive when computing BECount than when computing
6130       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6131       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6132       // to not.
6133       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6134           !isa<SCEVCouldNotCompute>(BECount))
6135         MaxBECount = BECount;
6136 
6137       return ExitLimit(BECount, MaxBECount, false,
6138                        {&EL0.Predicates, &EL1.Predicates});
6139     }
6140     if (BO->getOpcode() == Instruction::Or) {
6141       // Recurse on the operands of the or.
6142       bool EitherMayExit = L->contains(FBB);
6143       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
6144                                                ControlsExit && !EitherMayExit,
6145                                                AllowPredicates);
6146       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
6147                                                ControlsExit && !EitherMayExit,
6148                                                AllowPredicates);
6149       const SCEV *BECount = getCouldNotCompute();
6150       const SCEV *MaxBECount = getCouldNotCompute();
6151       if (EitherMayExit) {
6152         // Both conditions must be false for the loop to continue executing.
6153         // Choose the less conservative count.
6154         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6155             EL1.ExactNotTaken == getCouldNotCompute())
6156           BECount = getCouldNotCompute();
6157         else
6158           BECount =
6159               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6160         if (EL0.MaxNotTaken == getCouldNotCompute())
6161           MaxBECount = EL1.MaxNotTaken;
6162         else if (EL1.MaxNotTaken == getCouldNotCompute())
6163           MaxBECount = EL0.MaxNotTaken;
6164         else
6165           MaxBECount =
6166               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6167       } else {
6168         // Both conditions must be false at the same time for the loop to exit.
6169         // For now, be conservative.
6170         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6171         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6172           MaxBECount = EL0.MaxNotTaken;
6173         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6174           BECount = EL0.ExactNotTaken;
6175       }
6176 
6177       return ExitLimit(BECount, MaxBECount, false,
6178                        {&EL0.Predicates, &EL1.Predicates});
6179     }
6180   }
6181 
6182   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6183   // Proceed to the next level to examine the icmp.
6184   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6185     ExitLimit EL =
6186         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6187     if (EL.hasFullInfo() || !AllowPredicates)
6188       return EL;
6189 
6190     // Try again, but use SCEV predicates this time.
6191     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6192                                     /*AllowPredicates=*/true);
6193   }
6194 
6195   // Check for a constant condition. These are normally stripped out by
6196   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6197   // preserve the CFG and is temporarily leaving constant conditions
6198   // in place.
6199   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6200     if (L->contains(FBB) == !CI->getZExtValue())
6201       // The backedge is always taken.
6202       return getCouldNotCompute();
6203     else
6204       // The backedge is never taken.
6205       return getZero(CI->getType());
6206   }
6207 
6208   // If it's not an integer or pointer comparison then compute it the hard way.
6209   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6210 }
6211 
6212 ScalarEvolution::ExitLimit
6213 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6214                                           ICmpInst *ExitCond,
6215                                           BasicBlock *TBB,
6216                                           BasicBlock *FBB,
6217                                           bool ControlsExit,
6218                                           bool AllowPredicates) {
6219 
6220   // If the condition was exit on true, convert the condition to exit on false
6221   ICmpInst::Predicate Cond;
6222   if (!L->contains(FBB))
6223     Cond = ExitCond->getPredicate();
6224   else
6225     Cond = ExitCond->getInversePredicate();
6226 
6227   // Handle common loops like: for (X = "string"; *X; ++X)
6228   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6229     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6230       ExitLimit ItCnt =
6231         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6232       if (ItCnt.hasAnyInfo())
6233         return ItCnt;
6234     }
6235 
6236   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6237   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6238 
6239   // Try to evaluate any dependencies out of the loop.
6240   LHS = getSCEVAtScope(LHS, L);
6241   RHS = getSCEVAtScope(RHS, L);
6242 
6243   // At this point, we would like to compute how many iterations of the
6244   // loop the predicate will return true for these inputs.
6245   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6246     // If there is a loop-invariant, force it into the RHS.
6247     std::swap(LHS, RHS);
6248     Cond = ICmpInst::getSwappedPredicate(Cond);
6249   }
6250 
6251   // Simplify the operands before analyzing them.
6252   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6253 
6254   // If we have a comparison of a chrec against a constant, try to use value
6255   // ranges to answer this query.
6256   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6257     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6258       if (AddRec->getLoop() == L) {
6259         // Form the constant range.
6260         ConstantRange CompRange =
6261             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6262 
6263         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6264         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6265       }
6266 
6267   switch (Cond) {
6268   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6269     // Convert to: while (X-Y != 0)
6270     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6271                                 AllowPredicates);
6272     if (EL.hasAnyInfo()) return EL;
6273     break;
6274   }
6275   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6276     // Convert to: while (X-Y == 0)
6277     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6278     if (EL.hasAnyInfo()) return EL;
6279     break;
6280   }
6281   case ICmpInst::ICMP_SLT:
6282   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6283     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6284     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6285                                     AllowPredicates);
6286     if (EL.hasAnyInfo()) return EL;
6287     break;
6288   }
6289   case ICmpInst::ICMP_SGT:
6290   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6291     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6292     ExitLimit EL =
6293         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6294                             AllowPredicates);
6295     if (EL.hasAnyInfo()) return EL;
6296     break;
6297   }
6298   default:
6299     break;
6300   }
6301 
6302   auto *ExhaustiveCount =
6303       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6304 
6305   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6306     return ExhaustiveCount;
6307 
6308   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6309                                       ExitCond->getOperand(1), L, Cond);
6310 }
6311 
6312 ScalarEvolution::ExitLimit
6313 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6314                                                       SwitchInst *Switch,
6315                                                       BasicBlock *ExitingBlock,
6316                                                       bool ControlsExit) {
6317   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6318 
6319   // Give up if the exit is the default dest of a switch.
6320   if (Switch->getDefaultDest() == ExitingBlock)
6321     return getCouldNotCompute();
6322 
6323   assert(L->contains(Switch->getDefaultDest()) &&
6324          "Default case must not exit the loop!");
6325   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6326   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6327 
6328   // while (X != Y) --> while (X-Y != 0)
6329   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6330   if (EL.hasAnyInfo())
6331     return EL;
6332 
6333   return getCouldNotCompute();
6334 }
6335 
6336 static ConstantInt *
6337 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6338                                 ScalarEvolution &SE) {
6339   const SCEV *InVal = SE.getConstant(C);
6340   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6341   assert(isa<SCEVConstant>(Val) &&
6342          "Evaluation of SCEV at constant didn't fold correctly?");
6343   return cast<SCEVConstant>(Val)->getValue();
6344 }
6345 
6346 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6347 /// compute the backedge execution count.
6348 ScalarEvolution::ExitLimit
6349 ScalarEvolution::computeLoadConstantCompareExitLimit(
6350   LoadInst *LI,
6351   Constant *RHS,
6352   const Loop *L,
6353   ICmpInst::Predicate predicate) {
6354 
6355   if (LI->isVolatile()) return getCouldNotCompute();
6356 
6357   // Check to see if the loaded pointer is a getelementptr of a global.
6358   // TODO: Use SCEV instead of manually grubbing with GEPs.
6359   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6360   if (!GEP) return getCouldNotCompute();
6361 
6362   // Make sure that it is really a constant global we are gepping, with an
6363   // initializer, and make sure the first IDX is really 0.
6364   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6365   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6366       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6367       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6368     return getCouldNotCompute();
6369 
6370   // Okay, we allow one non-constant index into the GEP instruction.
6371   Value *VarIdx = nullptr;
6372   std::vector<Constant*> Indexes;
6373   unsigned VarIdxNum = 0;
6374   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6375     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6376       Indexes.push_back(CI);
6377     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6378       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6379       VarIdx = GEP->getOperand(i);
6380       VarIdxNum = i-2;
6381       Indexes.push_back(nullptr);
6382     }
6383 
6384   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6385   if (!VarIdx)
6386     return getCouldNotCompute();
6387 
6388   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6389   // Check to see if X is a loop variant variable value now.
6390   const SCEV *Idx = getSCEV(VarIdx);
6391   Idx = getSCEVAtScope(Idx, L);
6392 
6393   // We can only recognize very limited forms of loop index expressions, in
6394   // particular, only affine AddRec's like {C1,+,C2}.
6395   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6396   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6397       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6398       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6399     return getCouldNotCompute();
6400 
6401   unsigned MaxSteps = MaxBruteForceIterations;
6402   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6403     ConstantInt *ItCst = ConstantInt::get(
6404                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6405     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6406 
6407     // Form the GEP offset.
6408     Indexes[VarIdxNum] = Val;
6409 
6410     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6411                                                          Indexes);
6412     if (!Result) break;  // Cannot compute!
6413 
6414     // Evaluate the condition for this iteration.
6415     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6416     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6417     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6418       ++NumArrayLenItCounts;
6419       return getConstant(ItCst);   // Found terminating iteration!
6420     }
6421   }
6422   return getCouldNotCompute();
6423 }
6424 
6425 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6426     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6427   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6428   if (!RHS)
6429     return getCouldNotCompute();
6430 
6431   const BasicBlock *Latch = L->getLoopLatch();
6432   if (!Latch)
6433     return getCouldNotCompute();
6434 
6435   const BasicBlock *Predecessor = L->getLoopPredecessor();
6436   if (!Predecessor)
6437     return getCouldNotCompute();
6438 
6439   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6440   // Return LHS in OutLHS and shift_opt in OutOpCode.
6441   auto MatchPositiveShift =
6442       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6443 
6444     using namespace PatternMatch;
6445 
6446     ConstantInt *ShiftAmt;
6447     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6448       OutOpCode = Instruction::LShr;
6449     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6450       OutOpCode = Instruction::AShr;
6451     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6452       OutOpCode = Instruction::Shl;
6453     else
6454       return false;
6455 
6456     return ShiftAmt->getValue().isStrictlyPositive();
6457   };
6458 
6459   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6460   //
6461   // loop:
6462   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6463   //   %iv.shifted = lshr i32 %iv, <positive constant>
6464   //
6465   // Return true on a successful match.  Return the corresponding PHI node (%iv
6466   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6467   auto MatchShiftRecurrence =
6468       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6469     Optional<Instruction::BinaryOps> PostShiftOpCode;
6470 
6471     {
6472       Instruction::BinaryOps OpC;
6473       Value *V;
6474 
6475       // If we encounter a shift instruction, "peel off" the shift operation,
6476       // and remember that we did so.  Later when we inspect %iv's backedge
6477       // value, we will make sure that the backedge value uses the same
6478       // operation.
6479       //
6480       // Note: the peeled shift operation does not have to be the same
6481       // instruction as the one feeding into the PHI's backedge value.  We only
6482       // really care about it being the same *kind* of shift instruction --
6483       // that's all that is required for our later inferences to hold.
6484       if (MatchPositiveShift(LHS, V, OpC)) {
6485         PostShiftOpCode = OpC;
6486         LHS = V;
6487       }
6488     }
6489 
6490     PNOut = dyn_cast<PHINode>(LHS);
6491     if (!PNOut || PNOut->getParent() != L->getHeader())
6492       return false;
6493 
6494     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6495     Value *OpLHS;
6496 
6497     return
6498         // The backedge value for the PHI node must be a shift by a positive
6499         // amount
6500         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6501 
6502         // of the PHI node itself
6503         OpLHS == PNOut &&
6504 
6505         // and the kind of shift should be match the kind of shift we peeled
6506         // off, if any.
6507         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6508   };
6509 
6510   PHINode *PN;
6511   Instruction::BinaryOps OpCode;
6512   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6513     return getCouldNotCompute();
6514 
6515   const DataLayout &DL = getDataLayout();
6516 
6517   // The key rationale for this optimization is that for some kinds of shift
6518   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6519   // within a finite number of iterations.  If the condition guarding the
6520   // backedge (in the sense that the backedge is taken if the condition is true)
6521   // is false for the value the shift recurrence stabilizes to, then we know
6522   // that the backedge is taken only a finite number of times.
6523 
6524   ConstantInt *StableValue = nullptr;
6525   switch (OpCode) {
6526   default:
6527     llvm_unreachable("Impossible case!");
6528 
6529   case Instruction::AShr: {
6530     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6531     // bitwidth(K) iterations.
6532     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6533     bool KnownZero, KnownOne;
6534     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6535                    Predecessor->getTerminator(), &DT);
6536     auto *Ty = cast<IntegerType>(RHS->getType());
6537     if (KnownZero)
6538       StableValue = ConstantInt::get(Ty, 0);
6539     else if (KnownOne)
6540       StableValue = ConstantInt::get(Ty, -1, true);
6541     else
6542       return getCouldNotCompute();
6543 
6544     break;
6545   }
6546   case Instruction::LShr:
6547   case Instruction::Shl:
6548     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6549     // stabilize to 0 in at most bitwidth(K) iterations.
6550     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6551     break;
6552   }
6553 
6554   auto *Result =
6555       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6556   assert(Result->getType()->isIntegerTy(1) &&
6557          "Otherwise cannot be an operand to a branch instruction");
6558 
6559   if (Result->isZeroValue()) {
6560     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6561     const SCEV *UpperBound =
6562         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6563     return ExitLimit(getCouldNotCompute(), UpperBound, false);
6564   }
6565 
6566   return getCouldNotCompute();
6567 }
6568 
6569 /// Return true if we can constant fold an instruction of the specified type,
6570 /// assuming that all operands were constants.
6571 static bool CanConstantFold(const Instruction *I) {
6572   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6573       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6574       isa<LoadInst>(I))
6575     return true;
6576 
6577   if (const CallInst *CI = dyn_cast<CallInst>(I))
6578     if (const Function *F = CI->getCalledFunction())
6579       return canConstantFoldCallTo(F);
6580   return false;
6581 }
6582 
6583 /// Determine whether this instruction can constant evolve within this loop
6584 /// assuming its operands can all constant evolve.
6585 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6586   // An instruction outside of the loop can't be derived from a loop PHI.
6587   if (!L->contains(I)) return false;
6588 
6589   if (isa<PHINode>(I)) {
6590     // We don't currently keep track of the control flow needed to evaluate
6591     // PHIs, so we cannot handle PHIs inside of loops.
6592     return L->getHeader() == I->getParent();
6593   }
6594 
6595   // If we won't be able to constant fold this expression even if the operands
6596   // are constants, bail early.
6597   return CanConstantFold(I);
6598 }
6599 
6600 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6601 /// recursing through each instruction operand until reaching a loop header phi.
6602 static PHINode *
6603 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6604                                DenseMap<Instruction *, PHINode *> &PHIMap,
6605                                unsigned Depth) {
6606   if (Depth > MaxConstantEvolvingDepth)
6607     return nullptr;
6608 
6609   // Otherwise, we can evaluate this instruction if all of its operands are
6610   // constant or derived from a PHI node themselves.
6611   PHINode *PHI = nullptr;
6612   for (Value *Op : UseInst->operands()) {
6613     if (isa<Constant>(Op)) continue;
6614 
6615     Instruction *OpInst = dyn_cast<Instruction>(Op);
6616     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6617 
6618     PHINode *P = dyn_cast<PHINode>(OpInst);
6619     if (!P)
6620       // If this operand is already visited, reuse the prior result.
6621       // We may have P != PHI if this is the deepest point at which the
6622       // inconsistent paths meet.
6623       P = PHIMap.lookup(OpInst);
6624     if (!P) {
6625       // Recurse and memoize the results, whether a phi is found or not.
6626       // This recursive call invalidates pointers into PHIMap.
6627       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6628       PHIMap[OpInst] = P;
6629     }
6630     if (!P)
6631       return nullptr;  // Not evolving from PHI
6632     if (PHI && PHI != P)
6633       return nullptr;  // Evolving from multiple different PHIs.
6634     PHI = P;
6635   }
6636   // This is a expression evolving from a constant PHI!
6637   return PHI;
6638 }
6639 
6640 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6641 /// in the loop that V is derived from.  We allow arbitrary operations along the
6642 /// way, but the operands of an operation must either be constants or a value
6643 /// derived from a constant PHI.  If this expression does not fit with these
6644 /// constraints, return null.
6645 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6646   Instruction *I = dyn_cast<Instruction>(V);
6647   if (!I || !canConstantEvolve(I, L)) return nullptr;
6648 
6649   if (PHINode *PN = dyn_cast<PHINode>(I))
6650     return PN;
6651 
6652   // Record non-constant instructions contained by the loop.
6653   DenseMap<Instruction *, PHINode *> PHIMap;
6654   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6655 }
6656 
6657 /// EvaluateExpression - Given an expression that passes the
6658 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6659 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6660 /// reason, return null.
6661 static Constant *EvaluateExpression(Value *V, const Loop *L,
6662                                     DenseMap<Instruction *, Constant *> &Vals,
6663                                     const DataLayout &DL,
6664                                     const TargetLibraryInfo *TLI) {
6665   // Convenient constant check, but redundant for recursive calls.
6666   if (Constant *C = dyn_cast<Constant>(V)) return C;
6667   Instruction *I = dyn_cast<Instruction>(V);
6668   if (!I) return nullptr;
6669 
6670   if (Constant *C = Vals.lookup(I)) return C;
6671 
6672   // An instruction inside the loop depends on a value outside the loop that we
6673   // weren't given a mapping for, or a value such as a call inside the loop.
6674   if (!canConstantEvolve(I, L)) return nullptr;
6675 
6676   // An unmapped PHI can be due to a branch or another loop inside this loop,
6677   // or due to this not being the initial iteration through a loop where we
6678   // couldn't compute the evolution of this particular PHI last time.
6679   if (isa<PHINode>(I)) return nullptr;
6680 
6681   std::vector<Constant*> Operands(I->getNumOperands());
6682 
6683   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6684     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6685     if (!Operand) {
6686       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6687       if (!Operands[i]) return nullptr;
6688       continue;
6689     }
6690     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6691     Vals[Operand] = C;
6692     if (!C) return nullptr;
6693     Operands[i] = C;
6694   }
6695 
6696   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6697     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6698                                            Operands[1], DL, TLI);
6699   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6700     if (!LI->isVolatile())
6701       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6702   }
6703   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6704 }
6705 
6706 
6707 // If every incoming value to PN except the one for BB is a specific Constant,
6708 // return that, else return nullptr.
6709 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6710   Constant *IncomingVal = nullptr;
6711 
6712   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6713     if (PN->getIncomingBlock(i) == BB)
6714       continue;
6715 
6716     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6717     if (!CurrentVal)
6718       return nullptr;
6719 
6720     if (IncomingVal != CurrentVal) {
6721       if (IncomingVal)
6722         return nullptr;
6723       IncomingVal = CurrentVal;
6724     }
6725   }
6726 
6727   return IncomingVal;
6728 }
6729 
6730 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6731 /// in the header of its containing loop, we know the loop executes a
6732 /// constant number of times, and the PHI node is just a recurrence
6733 /// involving constants, fold it.
6734 Constant *
6735 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6736                                                    const APInt &BEs,
6737                                                    const Loop *L) {
6738   auto I = ConstantEvolutionLoopExitValue.find(PN);
6739   if (I != ConstantEvolutionLoopExitValue.end())
6740     return I->second;
6741 
6742   if (BEs.ugt(MaxBruteForceIterations))
6743     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6744 
6745   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6746 
6747   DenseMap<Instruction *, Constant *> CurrentIterVals;
6748   BasicBlock *Header = L->getHeader();
6749   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6750 
6751   BasicBlock *Latch = L->getLoopLatch();
6752   if (!Latch)
6753     return nullptr;
6754 
6755   for (auto &I : *Header) {
6756     PHINode *PHI = dyn_cast<PHINode>(&I);
6757     if (!PHI) break;
6758     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6759     if (!StartCST) continue;
6760     CurrentIterVals[PHI] = StartCST;
6761   }
6762   if (!CurrentIterVals.count(PN))
6763     return RetVal = nullptr;
6764 
6765   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6766 
6767   // Execute the loop symbolically to determine the exit value.
6768   if (BEs.getActiveBits() >= 32)
6769     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6770 
6771   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6772   unsigned IterationNum = 0;
6773   const DataLayout &DL = getDataLayout();
6774   for (; ; ++IterationNum) {
6775     if (IterationNum == NumIterations)
6776       return RetVal = CurrentIterVals[PN];  // Got exit value!
6777 
6778     // Compute the value of the PHIs for the next iteration.
6779     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6780     DenseMap<Instruction *, Constant *> NextIterVals;
6781     Constant *NextPHI =
6782         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6783     if (!NextPHI)
6784       return nullptr;        // Couldn't evaluate!
6785     NextIterVals[PN] = NextPHI;
6786 
6787     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6788 
6789     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6790     // cease to be able to evaluate one of them or if they stop evolving,
6791     // because that doesn't necessarily prevent us from computing PN.
6792     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6793     for (const auto &I : CurrentIterVals) {
6794       PHINode *PHI = dyn_cast<PHINode>(I.first);
6795       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6796       PHIsToCompute.emplace_back(PHI, I.second);
6797     }
6798     // We use two distinct loops because EvaluateExpression may invalidate any
6799     // iterators into CurrentIterVals.
6800     for (const auto &I : PHIsToCompute) {
6801       PHINode *PHI = I.first;
6802       Constant *&NextPHI = NextIterVals[PHI];
6803       if (!NextPHI) {   // Not already computed.
6804         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6805         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6806       }
6807       if (NextPHI != I.second)
6808         StoppedEvolving = false;
6809     }
6810 
6811     // If all entries in CurrentIterVals == NextIterVals then we can stop
6812     // iterating, the loop can't continue to change.
6813     if (StoppedEvolving)
6814       return RetVal = CurrentIterVals[PN];
6815 
6816     CurrentIterVals.swap(NextIterVals);
6817   }
6818 }
6819 
6820 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6821                                                           Value *Cond,
6822                                                           bool ExitWhen) {
6823   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6824   if (!PN) return getCouldNotCompute();
6825 
6826   // If the loop is canonicalized, the PHI will have exactly two entries.
6827   // That's the only form we support here.
6828   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6829 
6830   DenseMap<Instruction *, Constant *> CurrentIterVals;
6831   BasicBlock *Header = L->getHeader();
6832   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6833 
6834   BasicBlock *Latch = L->getLoopLatch();
6835   assert(Latch && "Should follow from NumIncomingValues == 2!");
6836 
6837   for (auto &I : *Header) {
6838     PHINode *PHI = dyn_cast<PHINode>(&I);
6839     if (!PHI)
6840       break;
6841     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6842     if (!StartCST) continue;
6843     CurrentIterVals[PHI] = StartCST;
6844   }
6845   if (!CurrentIterVals.count(PN))
6846     return getCouldNotCompute();
6847 
6848   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6849   // the loop symbolically to determine when the condition gets a value of
6850   // "ExitWhen".
6851   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6852   const DataLayout &DL = getDataLayout();
6853   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6854     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6855         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6856 
6857     // Couldn't symbolically evaluate.
6858     if (!CondVal) return getCouldNotCompute();
6859 
6860     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6861       ++NumBruteForceTripCountsComputed;
6862       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6863     }
6864 
6865     // Update all the PHI nodes for the next iteration.
6866     DenseMap<Instruction *, Constant *> NextIterVals;
6867 
6868     // Create a list of which PHIs we need to compute. We want to do this before
6869     // calling EvaluateExpression on them because that may invalidate iterators
6870     // into CurrentIterVals.
6871     SmallVector<PHINode *, 8> PHIsToCompute;
6872     for (const auto &I : CurrentIterVals) {
6873       PHINode *PHI = dyn_cast<PHINode>(I.first);
6874       if (!PHI || PHI->getParent() != Header) continue;
6875       PHIsToCompute.push_back(PHI);
6876     }
6877     for (PHINode *PHI : PHIsToCompute) {
6878       Constant *&NextPHI = NextIterVals[PHI];
6879       if (NextPHI) continue;    // Already computed!
6880 
6881       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6882       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6883     }
6884     CurrentIterVals.swap(NextIterVals);
6885   }
6886 
6887   // Too many iterations were needed to evaluate.
6888   return getCouldNotCompute();
6889 }
6890 
6891 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6892   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6893       ValuesAtScopes[V];
6894   // Check to see if we've folded this expression at this loop before.
6895   for (auto &LS : Values)
6896     if (LS.first == L)
6897       return LS.second ? LS.second : V;
6898 
6899   Values.emplace_back(L, nullptr);
6900 
6901   // Otherwise compute it.
6902   const SCEV *C = computeSCEVAtScope(V, L);
6903   for (auto &LS : reverse(ValuesAtScopes[V]))
6904     if (LS.first == L) {
6905       LS.second = C;
6906       break;
6907     }
6908   return C;
6909 }
6910 
6911 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6912 /// will return Constants for objects which aren't represented by a
6913 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6914 /// Returns NULL if the SCEV isn't representable as a Constant.
6915 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6916   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6917     case scCouldNotCompute:
6918     case scAddRecExpr:
6919       break;
6920     case scConstant:
6921       return cast<SCEVConstant>(V)->getValue();
6922     case scUnknown:
6923       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6924     case scSignExtend: {
6925       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6926       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6927         return ConstantExpr::getSExt(CastOp, SS->getType());
6928       break;
6929     }
6930     case scZeroExtend: {
6931       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6932       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6933         return ConstantExpr::getZExt(CastOp, SZ->getType());
6934       break;
6935     }
6936     case scTruncate: {
6937       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6938       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6939         return ConstantExpr::getTrunc(CastOp, ST->getType());
6940       break;
6941     }
6942     case scAddExpr: {
6943       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6944       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6945         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6946           unsigned AS = PTy->getAddressSpace();
6947           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6948           C = ConstantExpr::getBitCast(C, DestPtrTy);
6949         }
6950         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6951           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6952           if (!C2) return nullptr;
6953 
6954           // First pointer!
6955           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6956             unsigned AS = C2->getType()->getPointerAddressSpace();
6957             std::swap(C, C2);
6958             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6959             // The offsets have been converted to bytes.  We can add bytes to an
6960             // i8* by GEP with the byte count in the first index.
6961             C = ConstantExpr::getBitCast(C, DestPtrTy);
6962           }
6963 
6964           // Don't bother trying to sum two pointers. We probably can't
6965           // statically compute a load that results from it anyway.
6966           if (C2->getType()->isPointerTy())
6967             return nullptr;
6968 
6969           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6970             if (PTy->getElementType()->isStructTy())
6971               C2 = ConstantExpr::getIntegerCast(
6972                   C2, Type::getInt32Ty(C->getContext()), true);
6973             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6974           } else
6975             C = ConstantExpr::getAdd(C, C2);
6976         }
6977         return C;
6978       }
6979       break;
6980     }
6981     case scMulExpr: {
6982       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6983       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6984         // Don't bother with pointers at all.
6985         if (C->getType()->isPointerTy()) return nullptr;
6986         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6987           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6988           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6989           C = ConstantExpr::getMul(C, C2);
6990         }
6991         return C;
6992       }
6993       break;
6994     }
6995     case scUDivExpr: {
6996       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6997       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6998         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6999           if (LHS->getType() == RHS->getType())
7000             return ConstantExpr::getUDiv(LHS, RHS);
7001       break;
7002     }
7003     case scSMaxExpr:
7004     case scUMaxExpr:
7005       break; // TODO: smax, umax.
7006   }
7007   return nullptr;
7008 }
7009 
7010 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7011   if (isa<SCEVConstant>(V)) return V;
7012 
7013   // If this instruction is evolved from a constant-evolving PHI, compute the
7014   // exit value from the loop without using SCEVs.
7015   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7016     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7017       const Loop *LI = this->LI[I->getParent()];
7018       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7019         if (PHINode *PN = dyn_cast<PHINode>(I))
7020           if (PN->getParent() == LI->getHeader()) {
7021             // Okay, there is no closed form solution for the PHI node.  Check
7022             // to see if the loop that contains it has a known backedge-taken
7023             // count.  If so, we may be able to force computation of the exit
7024             // value.
7025             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7026             if (const SCEVConstant *BTCC =
7027                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7028               // Okay, we know how many times the containing loop executes.  If
7029               // this is a constant evolving PHI node, get the final value at
7030               // the specified iteration number.
7031               Constant *RV =
7032                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7033               if (RV) return getSCEV(RV);
7034             }
7035           }
7036 
7037       // Okay, this is an expression that we cannot symbolically evaluate
7038       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7039       // the arguments into constants, and if so, try to constant propagate the
7040       // result.  This is particularly useful for computing loop exit values.
7041       if (CanConstantFold(I)) {
7042         SmallVector<Constant *, 4> Operands;
7043         bool MadeImprovement = false;
7044         for (Value *Op : I->operands()) {
7045           if (Constant *C = dyn_cast<Constant>(Op)) {
7046             Operands.push_back(C);
7047             continue;
7048           }
7049 
7050           // If any of the operands is non-constant and if they are
7051           // non-integer and non-pointer, don't even try to analyze them
7052           // with scev techniques.
7053           if (!isSCEVable(Op->getType()))
7054             return V;
7055 
7056           const SCEV *OrigV = getSCEV(Op);
7057           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7058           MadeImprovement |= OrigV != OpV;
7059 
7060           Constant *C = BuildConstantFromSCEV(OpV);
7061           if (!C) return V;
7062           if (C->getType() != Op->getType())
7063             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7064                                                               Op->getType(),
7065                                                               false),
7066                                       C, Op->getType());
7067           Operands.push_back(C);
7068         }
7069 
7070         // Check to see if getSCEVAtScope actually made an improvement.
7071         if (MadeImprovement) {
7072           Constant *C = nullptr;
7073           const DataLayout &DL = getDataLayout();
7074           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7075             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7076                                                 Operands[1], DL, &TLI);
7077           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7078             if (!LI->isVolatile())
7079               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7080           } else
7081             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7082           if (!C) return V;
7083           return getSCEV(C);
7084         }
7085       }
7086     }
7087 
7088     // This is some other type of SCEVUnknown, just return it.
7089     return V;
7090   }
7091 
7092   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7093     // Avoid performing the look-up in the common case where the specified
7094     // expression has no loop-variant portions.
7095     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7096       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7097       if (OpAtScope != Comm->getOperand(i)) {
7098         // Okay, at least one of these operands is loop variant but might be
7099         // foldable.  Build a new instance of the folded commutative expression.
7100         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7101                                             Comm->op_begin()+i);
7102         NewOps.push_back(OpAtScope);
7103 
7104         for (++i; i != e; ++i) {
7105           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7106           NewOps.push_back(OpAtScope);
7107         }
7108         if (isa<SCEVAddExpr>(Comm))
7109           return getAddExpr(NewOps);
7110         if (isa<SCEVMulExpr>(Comm))
7111           return getMulExpr(NewOps);
7112         if (isa<SCEVSMaxExpr>(Comm))
7113           return getSMaxExpr(NewOps);
7114         if (isa<SCEVUMaxExpr>(Comm))
7115           return getUMaxExpr(NewOps);
7116         llvm_unreachable("Unknown commutative SCEV type!");
7117       }
7118     }
7119     // If we got here, all operands are loop invariant.
7120     return Comm;
7121   }
7122 
7123   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7124     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7125     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7126     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7127       return Div;   // must be loop invariant
7128     return getUDivExpr(LHS, RHS);
7129   }
7130 
7131   // If this is a loop recurrence for a loop that does not contain L, then we
7132   // are dealing with the final value computed by the loop.
7133   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7134     // First, attempt to evaluate each operand.
7135     // Avoid performing the look-up in the common case where the specified
7136     // expression has no loop-variant portions.
7137     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7138       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7139       if (OpAtScope == AddRec->getOperand(i))
7140         continue;
7141 
7142       // Okay, at least one of these operands is loop variant but might be
7143       // foldable.  Build a new instance of the folded commutative expression.
7144       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7145                                           AddRec->op_begin()+i);
7146       NewOps.push_back(OpAtScope);
7147       for (++i; i != e; ++i)
7148         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7149 
7150       const SCEV *FoldedRec =
7151         getAddRecExpr(NewOps, AddRec->getLoop(),
7152                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7153       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7154       // The addrec may be folded to a nonrecurrence, for example, if the
7155       // induction variable is multiplied by zero after constant folding. Go
7156       // ahead and return the folded value.
7157       if (!AddRec)
7158         return FoldedRec;
7159       break;
7160     }
7161 
7162     // If the scope is outside the addrec's loop, evaluate it by using the
7163     // loop exit value of the addrec.
7164     if (!AddRec->getLoop()->contains(L)) {
7165       // To evaluate this recurrence, we need to know how many times the AddRec
7166       // loop iterates.  Compute this now.
7167       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7168       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7169 
7170       // Then, evaluate the AddRec.
7171       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7172     }
7173 
7174     return AddRec;
7175   }
7176 
7177   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7178     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7179     if (Op == Cast->getOperand())
7180       return Cast;  // must be loop invariant
7181     return getZeroExtendExpr(Op, Cast->getType());
7182   }
7183 
7184   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7185     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7186     if (Op == Cast->getOperand())
7187       return Cast;  // must be loop invariant
7188     return getSignExtendExpr(Op, Cast->getType());
7189   }
7190 
7191   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7192     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7193     if (Op == Cast->getOperand())
7194       return Cast;  // must be loop invariant
7195     return getTruncateExpr(Op, Cast->getType());
7196   }
7197 
7198   llvm_unreachable("Unknown SCEV type!");
7199 }
7200 
7201 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7202   return getSCEVAtScope(getSCEV(V), L);
7203 }
7204 
7205 /// Finds the minimum unsigned root of the following equation:
7206 ///
7207 ///     A * X = B (mod N)
7208 ///
7209 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7210 /// A and B isn't important.
7211 ///
7212 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7213 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7214                                                ScalarEvolution &SE) {
7215   uint32_t BW = A.getBitWidth();
7216   assert(BW == SE.getTypeSizeInBits(B->getType()));
7217   assert(A != 0 && "A must be non-zero.");
7218 
7219   // 1. D = gcd(A, N)
7220   //
7221   // The gcd of A and N may have only one prime factor: 2. The number of
7222   // trailing zeros in A is its multiplicity
7223   uint32_t Mult2 = A.countTrailingZeros();
7224   // D = 2^Mult2
7225 
7226   // 2. Check if B is divisible by D.
7227   //
7228   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7229   // is not less than multiplicity of this prime factor for D.
7230   if (SE.GetMinTrailingZeros(B) < Mult2)
7231     return SE.getCouldNotCompute();
7232 
7233   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7234   // modulo (N / D).
7235   //
7236   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7237   // (N / D) in general. The inverse itself always fits into BW bits, though,
7238   // so we immediately truncate it.
7239   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7240   APInt Mod(BW + 1, 0);
7241   Mod.setBit(BW - Mult2);  // Mod = N / D
7242   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7243 
7244   // 4. Compute the minimum unsigned root of the equation:
7245   // I * (B / D) mod (N / D)
7246   // To simplify the computation, we factor out the divide by D:
7247   // (I * B mod N) / D
7248   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7249   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7250 }
7251 
7252 /// Find the roots of the quadratic equation for the given quadratic chrec
7253 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7254 /// two SCEVCouldNotCompute objects.
7255 ///
7256 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7257 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7258   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7259   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7260   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7261   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7262 
7263   // We currently can only solve this if the coefficients are constants.
7264   if (!LC || !MC || !NC)
7265     return None;
7266 
7267   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7268   const APInt &L = LC->getAPInt();
7269   const APInt &M = MC->getAPInt();
7270   const APInt &N = NC->getAPInt();
7271   APInt Two(BitWidth, 2);
7272   APInt Four(BitWidth, 4);
7273 
7274   {
7275     using namespace APIntOps;
7276     const APInt& C = L;
7277     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7278     // The B coefficient is M-N/2
7279     APInt B(M);
7280     B -= N.sdiv(Two);
7281 
7282     // The A coefficient is N/2
7283     APInt A(N.sdiv(Two));
7284 
7285     // Compute the B^2-4ac term.
7286     APInt SqrtTerm(B);
7287     SqrtTerm *= B;
7288     SqrtTerm -= Four * (A * C);
7289 
7290     if (SqrtTerm.isNegative()) {
7291       // The loop is provably infinite.
7292       return None;
7293     }
7294 
7295     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7296     // integer value or else APInt::sqrt() will assert.
7297     APInt SqrtVal(SqrtTerm.sqrt());
7298 
7299     // Compute the two solutions for the quadratic formula.
7300     // The divisions must be performed as signed divisions.
7301     APInt NegB(-B);
7302     APInt TwoA(A << 1);
7303     if (TwoA.isMinValue())
7304       return None;
7305 
7306     LLVMContext &Context = SE.getContext();
7307 
7308     ConstantInt *Solution1 =
7309       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7310     ConstantInt *Solution2 =
7311       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7312 
7313     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7314                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7315   } // end APIntOps namespace
7316 }
7317 
7318 ScalarEvolution::ExitLimit
7319 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7320                               bool AllowPredicates) {
7321 
7322   // This is only used for loops with a "x != y" exit test. The exit condition
7323   // is now expressed as a single expression, V = x-y. So the exit test is
7324   // effectively V != 0.  We know and take advantage of the fact that this
7325   // expression only being used in a comparison by zero context.
7326 
7327   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7328   // If the value is a constant
7329   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7330     // If the value is already zero, the branch will execute zero times.
7331     if (C->getValue()->isZero()) return C;
7332     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7333   }
7334 
7335   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7336   if (!AddRec && AllowPredicates)
7337     // Try to make this an AddRec using runtime tests, in the first X
7338     // iterations of this loop, where X is the SCEV expression found by the
7339     // algorithm below.
7340     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7341 
7342   if (!AddRec || AddRec->getLoop() != L)
7343     return getCouldNotCompute();
7344 
7345   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7346   // the quadratic equation to solve it.
7347   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7348     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7349       const SCEVConstant *R1 = Roots->first;
7350       const SCEVConstant *R2 = Roots->second;
7351       // Pick the smallest positive root value.
7352       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7353               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7354         if (!CB->getZExtValue())
7355           std::swap(R1, R2); // R1 is the minimum root now.
7356 
7357         // We can only use this value if the chrec ends up with an exact zero
7358         // value at this index.  When solving for "X*X != 5", for example, we
7359         // should not accept a root of 2.
7360         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7361         if (Val->isZero())
7362           // We found a quadratic root!
7363           return ExitLimit(R1, R1, false, Predicates);
7364       }
7365     }
7366     return getCouldNotCompute();
7367   }
7368 
7369   // Otherwise we can only handle this if it is affine.
7370   if (!AddRec->isAffine())
7371     return getCouldNotCompute();
7372 
7373   // If this is an affine expression, the execution count of this branch is
7374   // the minimum unsigned root of the following equation:
7375   //
7376   //     Start + Step*N = 0 (mod 2^BW)
7377   //
7378   // equivalent to:
7379   //
7380   //             Step*N = -Start (mod 2^BW)
7381   //
7382   // where BW is the common bit width of Start and Step.
7383 
7384   // Get the initial value for the loop.
7385   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7386   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7387 
7388   // For now we handle only constant steps.
7389   //
7390   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7391   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7392   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7393   // We have not yet seen any such cases.
7394   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7395   if (!StepC || StepC->getValue()->equalsInt(0))
7396     return getCouldNotCompute();
7397 
7398   // For positive steps (counting up until unsigned overflow):
7399   //   N = -Start/Step (as unsigned)
7400   // For negative steps (counting down to zero):
7401   //   N = Start/-Step
7402   // First compute the unsigned distance from zero in the direction of Step.
7403   bool CountDown = StepC->getAPInt().isNegative();
7404   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7405 
7406   // Handle unitary steps, which cannot wraparound.
7407   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7408   //   N = Distance (as unsigned)
7409   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7410     APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7411 
7412     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7413     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7414     // case, and see if we can improve the bound.
7415     //
7416     // Explicitly handling this here is necessary because getUnsignedRange
7417     // isn't context-sensitive; it doesn't know that we only care about the
7418     // range inside the loop.
7419     const SCEV *Zero = getZero(Distance->getType());
7420     const SCEV *One = getOne(Distance->getType());
7421     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7422     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7423       // If Distance + 1 doesn't overflow, we can compute the maximum distance
7424       // as "unsigned_max(Distance + 1) - 1".
7425       ConstantRange CR = getUnsignedRange(DistancePlusOne);
7426       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7427     }
7428     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7429   }
7430 
7431   // If the condition controls loop exit (the loop exits only if the expression
7432   // is true) and the addition is no-wrap we can use unsigned divide to
7433   // compute the backedge count.  In this case, the step may not divide the
7434   // distance, but we don't care because if the condition is "missed" the loop
7435   // will have undefined behavior due to wrapping.
7436   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7437       loopHasNoAbnormalExits(AddRec->getLoop())) {
7438     const SCEV *Exact =
7439         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7440     return ExitLimit(Exact, Exact, false, Predicates);
7441   }
7442 
7443   // Solve the general equation.
7444   const SCEV *E = SolveLinEquationWithOverflow(
7445       StepC->getAPInt(), getNegativeSCEV(Start), *this);
7446   return ExitLimit(E, E, false, Predicates);
7447 }
7448 
7449 ScalarEvolution::ExitLimit
7450 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7451   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7452   // handle them yet except for the trivial case.  This could be expanded in the
7453   // future as needed.
7454 
7455   // If the value is a constant, check to see if it is known to be non-zero
7456   // already.  If so, the backedge will execute zero times.
7457   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7458     if (!C->getValue()->isNullValue())
7459       return getZero(C->getType());
7460     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7461   }
7462 
7463   // We could implement others, but I really doubt anyone writes loops like
7464   // this, and if they did, they would already be constant folded.
7465   return getCouldNotCompute();
7466 }
7467 
7468 std::pair<BasicBlock *, BasicBlock *>
7469 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7470   // If the block has a unique predecessor, then there is no path from the
7471   // predecessor to the block that does not go through the direct edge
7472   // from the predecessor to the block.
7473   if (BasicBlock *Pred = BB->getSinglePredecessor())
7474     return {Pred, BB};
7475 
7476   // A loop's header is defined to be a block that dominates the loop.
7477   // If the header has a unique predecessor outside the loop, it must be
7478   // a block that has exactly one successor that can reach the loop.
7479   if (Loop *L = LI.getLoopFor(BB))
7480     return {L->getLoopPredecessor(), L->getHeader()};
7481 
7482   return {nullptr, nullptr};
7483 }
7484 
7485 /// SCEV structural equivalence is usually sufficient for testing whether two
7486 /// expressions are equal, however for the purposes of looking for a condition
7487 /// guarding a loop, it can be useful to be a little more general, since a
7488 /// front-end may have replicated the controlling expression.
7489 ///
7490 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7491   // Quick check to see if they are the same SCEV.
7492   if (A == B) return true;
7493 
7494   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7495     // Not all instructions that are "identical" compute the same value.  For
7496     // instance, two distinct alloca instructions allocating the same type are
7497     // identical and do not read memory; but compute distinct values.
7498     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7499   };
7500 
7501   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7502   // two different instructions with the same value. Check for this case.
7503   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7504     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7505       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7506         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7507           if (ComputesEqualValues(AI, BI))
7508             return true;
7509 
7510   // Otherwise assume they may have a different value.
7511   return false;
7512 }
7513 
7514 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7515                                            const SCEV *&LHS, const SCEV *&RHS,
7516                                            unsigned Depth) {
7517   bool Changed = false;
7518 
7519   // If we hit the max recursion limit bail out.
7520   if (Depth >= 3)
7521     return false;
7522 
7523   // Canonicalize a constant to the right side.
7524   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7525     // Check for both operands constant.
7526     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7527       if (ConstantExpr::getICmp(Pred,
7528                                 LHSC->getValue(),
7529                                 RHSC->getValue())->isNullValue())
7530         goto trivially_false;
7531       else
7532         goto trivially_true;
7533     }
7534     // Otherwise swap the operands to put the constant on the right.
7535     std::swap(LHS, RHS);
7536     Pred = ICmpInst::getSwappedPredicate(Pred);
7537     Changed = true;
7538   }
7539 
7540   // If we're comparing an addrec with a value which is loop-invariant in the
7541   // addrec's loop, put the addrec on the left. Also make a dominance check,
7542   // as both operands could be addrecs loop-invariant in each other's loop.
7543   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7544     const Loop *L = AR->getLoop();
7545     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7546       std::swap(LHS, RHS);
7547       Pred = ICmpInst::getSwappedPredicate(Pred);
7548       Changed = true;
7549     }
7550   }
7551 
7552   // If there's a constant operand, canonicalize comparisons with boundary
7553   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7554   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7555     const APInt &RA = RC->getAPInt();
7556 
7557     bool SimplifiedByConstantRange = false;
7558 
7559     if (!ICmpInst::isEquality(Pred)) {
7560       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7561       if (ExactCR.isFullSet())
7562         goto trivially_true;
7563       else if (ExactCR.isEmptySet())
7564         goto trivially_false;
7565 
7566       APInt NewRHS;
7567       CmpInst::Predicate NewPred;
7568       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7569           ICmpInst::isEquality(NewPred)) {
7570         // We were able to convert an inequality to an equality.
7571         Pred = NewPred;
7572         RHS = getConstant(NewRHS);
7573         Changed = SimplifiedByConstantRange = true;
7574       }
7575     }
7576 
7577     if (!SimplifiedByConstantRange) {
7578       switch (Pred) {
7579       default:
7580         break;
7581       case ICmpInst::ICMP_EQ:
7582       case ICmpInst::ICMP_NE:
7583         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7584         if (!RA)
7585           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7586             if (const SCEVMulExpr *ME =
7587                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7588               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7589                   ME->getOperand(0)->isAllOnesValue()) {
7590                 RHS = AE->getOperand(1);
7591                 LHS = ME->getOperand(1);
7592                 Changed = true;
7593               }
7594         break;
7595 
7596 
7597         // The "Should have been caught earlier!" messages refer to the fact
7598         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7599         // should have fired on the corresponding cases, and canonicalized the
7600         // check to trivially_true or trivially_false.
7601 
7602       case ICmpInst::ICMP_UGE:
7603         assert(!RA.isMinValue() && "Should have been caught earlier!");
7604         Pred = ICmpInst::ICMP_UGT;
7605         RHS = getConstant(RA - 1);
7606         Changed = true;
7607         break;
7608       case ICmpInst::ICMP_ULE:
7609         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7610         Pred = ICmpInst::ICMP_ULT;
7611         RHS = getConstant(RA + 1);
7612         Changed = true;
7613         break;
7614       case ICmpInst::ICMP_SGE:
7615         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7616         Pred = ICmpInst::ICMP_SGT;
7617         RHS = getConstant(RA - 1);
7618         Changed = true;
7619         break;
7620       case ICmpInst::ICMP_SLE:
7621         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7622         Pred = ICmpInst::ICMP_SLT;
7623         RHS = getConstant(RA + 1);
7624         Changed = true;
7625         break;
7626       }
7627     }
7628   }
7629 
7630   // Check for obvious equality.
7631   if (HasSameValue(LHS, RHS)) {
7632     if (ICmpInst::isTrueWhenEqual(Pred))
7633       goto trivially_true;
7634     if (ICmpInst::isFalseWhenEqual(Pred))
7635       goto trivially_false;
7636   }
7637 
7638   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7639   // adding or subtracting 1 from one of the operands.
7640   switch (Pred) {
7641   case ICmpInst::ICMP_SLE:
7642     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7643       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7644                        SCEV::FlagNSW);
7645       Pred = ICmpInst::ICMP_SLT;
7646       Changed = true;
7647     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7648       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7649                        SCEV::FlagNSW);
7650       Pred = ICmpInst::ICMP_SLT;
7651       Changed = true;
7652     }
7653     break;
7654   case ICmpInst::ICMP_SGE:
7655     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7656       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7657                        SCEV::FlagNSW);
7658       Pred = ICmpInst::ICMP_SGT;
7659       Changed = true;
7660     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7661       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7662                        SCEV::FlagNSW);
7663       Pred = ICmpInst::ICMP_SGT;
7664       Changed = true;
7665     }
7666     break;
7667   case ICmpInst::ICMP_ULE:
7668     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7669       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7670                        SCEV::FlagNUW);
7671       Pred = ICmpInst::ICMP_ULT;
7672       Changed = true;
7673     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7674       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7675       Pred = ICmpInst::ICMP_ULT;
7676       Changed = true;
7677     }
7678     break;
7679   case ICmpInst::ICMP_UGE:
7680     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7681       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7682       Pred = ICmpInst::ICMP_UGT;
7683       Changed = true;
7684     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7685       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7686                        SCEV::FlagNUW);
7687       Pred = ICmpInst::ICMP_UGT;
7688       Changed = true;
7689     }
7690     break;
7691   default:
7692     break;
7693   }
7694 
7695   // TODO: More simplifications are possible here.
7696 
7697   // Recursively simplify until we either hit a recursion limit or nothing
7698   // changes.
7699   if (Changed)
7700     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7701 
7702   return Changed;
7703 
7704 trivially_true:
7705   // Return 0 == 0.
7706   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7707   Pred = ICmpInst::ICMP_EQ;
7708   return true;
7709 
7710 trivially_false:
7711   // Return 0 != 0.
7712   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7713   Pred = ICmpInst::ICMP_NE;
7714   return true;
7715 }
7716 
7717 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7718   return getSignedRange(S).getSignedMax().isNegative();
7719 }
7720 
7721 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7722   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7723 }
7724 
7725 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7726   return !getSignedRange(S).getSignedMin().isNegative();
7727 }
7728 
7729 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7730   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7731 }
7732 
7733 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7734   return isKnownNegative(S) || isKnownPositive(S);
7735 }
7736 
7737 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7738                                        const SCEV *LHS, const SCEV *RHS) {
7739   // Canonicalize the inputs first.
7740   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7741 
7742   // If LHS or RHS is an addrec, check to see if the condition is true in
7743   // every iteration of the loop.
7744   // If LHS and RHS are both addrec, both conditions must be true in
7745   // every iteration of the loop.
7746   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7747   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7748   bool LeftGuarded = false;
7749   bool RightGuarded = false;
7750   if (LAR) {
7751     const Loop *L = LAR->getLoop();
7752     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7753         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7754       if (!RAR) return true;
7755       LeftGuarded = true;
7756     }
7757   }
7758   if (RAR) {
7759     const Loop *L = RAR->getLoop();
7760     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7761         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7762       if (!LAR) return true;
7763       RightGuarded = true;
7764     }
7765   }
7766   if (LeftGuarded && RightGuarded)
7767     return true;
7768 
7769   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7770     return true;
7771 
7772   // Otherwise see what can be done with known constant ranges.
7773   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7774 }
7775 
7776 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7777                                            ICmpInst::Predicate Pred,
7778                                            bool &Increasing) {
7779   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7780 
7781 #ifndef NDEBUG
7782   // Verify an invariant: inverting the predicate should turn a monotonically
7783   // increasing change to a monotonically decreasing one, and vice versa.
7784   bool IncreasingSwapped;
7785   bool ResultSwapped = isMonotonicPredicateImpl(
7786       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7787 
7788   assert(Result == ResultSwapped && "should be able to analyze both!");
7789   if (ResultSwapped)
7790     assert(Increasing == !IncreasingSwapped &&
7791            "monotonicity should flip as we flip the predicate");
7792 #endif
7793 
7794   return Result;
7795 }
7796 
7797 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7798                                                ICmpInst::Predicate Pred,
7799                                                bool &Increasing) {
7800 
7801   // A zero step value for LHS means the induction variable is essentially a
7802   // loop invariant value. We don't really depend on the predicate actually
7803   // flipping from false to true (for increasing predicates, and the other way
7804   // around for decreasing predicates), all we care about is that *if* the
7805   // predicate changes then it only changes from false to true.
7806   //
7807   // A zero step value in itself is not very useful, but there may be places
7808   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7809   // as general as possible.
7810 
7811   switch (Pred) {
7812   default:
7813     return false; // Conservative answer
7814 
7815   case ICmpInst::ICMP_UGT:
7816   case ICmpInst::ICMP_UGE:
7817   case ICmpInst::ICMP_ULT:
7818   case ICmpInst::ICMP_ULE:
7819     if (!LHS->hasNoUnsignedWrap())
7820       return false;
7821 
7822     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7823     return true;
7824 
7825   case ICmpInst::ICMP_SGT:
7826   case ICmpInst::ICMP_SGE:
7827   case ICmpInst::ICMP_SLT:
7828   case ICmpInst::ICMP_SLE: {
7829     if (!LHS->hasNoSignedWrap())
7830       return false;
7831 
7832     const SCEV *Step = LHS->getStepRecurrence(*this);
7833 
7834     if (isKnownNonNegative(Step)) {
7835       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7836       return true;
7837     }
7838 
7839     if (isKnownNonPositive(Step)) {
7840       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7841       return true;
7842     }
7843 
7844     return false;
7845   }
7846 
7847   }
7848 
7849   llvm_unreachable("switch has default clause!");
7850 }
7851 
7852 bool ScalarEvolution::isLoopInvariantPredicate(
7853     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7854     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7855     const SCEV *&InvariantRHS) {
7856 
7857   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7858   if (!isLoopInvariant(RHS, L)) {
7859     if (!isLoopInvariant(LHS, L))
7860       return false;
7861 
7862     std::swap(LHS, RHS);
7863     Pred = ICmpInst::getSwappedPredicate(Pred);
7864   }
7865 
7866   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7867   if (!ArLHS || ArLHS->getLoop() != L)
7868     return false;
7869 
7870   bool Increasing;
7871   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7872     return false;
7873 
7874   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7875   // true as the loop iterates, and the backedge is control dependent on
7876   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7877   //
7878   //   * if the predicate was false in the first iteration then the predicate
7879   //     is never evaluated again, since the loop exits without taking the
7880   //     backedge.
7881   //   * if the predicate was true in the first iteration then it will
7882   //     continue to be true for all future iterations since it is
7883   //     monotonically increasing.
7884   //
7885   // For both the above possibilities, we can replace the loop varying
7886   // predicate with its value on the first iteration of the loop (which is
7887   // loop invariant).
7888   //
7889   // A similar reasoning applies for a monotonically decreasing predicate, by
7890   // replacing true with false and false with true in the above two bullets.
7891 
7892   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7893 
7894   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7895     return false;
7896 
7897   InvariantPred = Pred;
7898   InvariantLHS = ArLHS->getStart();
7899   InvariantRHS = RHS;
7900   return true;
7901 }
7902 
7903 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7904     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7905   if (HasSameValue(LHS, RHS))
7906     return ICmpInst::isTrueWhenEqual(Pred);
7907 
7908   // This code is split out from isKnownPredicate because it is called from
7909   // within isLoopEntryGuardedByCond.
7910 
7911   auto CheckRanges =
7912       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7913     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7914         .contains(RangeLHS);
7915   };
7916 
7917   // The check at the top of the function catches the case where the values are
7918   // known to be equal.
7919   if (Pred == CmpInst::ICMP_EQ)
7920     return false;
7921 
7922   if (Pred == CmpInst::ICMP_NE)
7923     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7924            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7925            isKnownNonZero(getMinusSCEV(LHS, RHS));
7926 
7927   if (CmpInst::isSigned(Pred))
7928     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7929 
7930   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7931 }
7932 
7933 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7934                                                     const SCEV *LHS,
7935                                                     const SCEV *RHS) {
7936 
7937   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7938   // Return Y via OutY.
7939   auto MatchBinaryAddToConst =
7940       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7941              SCEV::NoWrapFlags ExpectedFlags) {
7942     const SCEV *NonConstOp, *ConstOp;
7943     SCEV::NoWrapFlags FlagsPresent;
7944 
7945     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7946         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7947       return false;
7948 
7949     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7950     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7951   };
7952 
7953   APInt C;
7954 
7955   switch (Pred) {
7956   default:
7957     break;
7958 
7959   case ICmpInst::ICMP_SGE:
7960     std::swap(LHS, RHS);
7961   case ICmpInst::ICMP_SLE:
7962     // X s<= (X + C)<nsw> if C >= 0
7963     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7964       return true;
7965 
7966     // (X + C)<nsw> s<= X if C <= 0
7967     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7968         !C.isStrictlyPositive())
7969       return true;
7970     break;
7971 
7972   case ICmpInst::ICMP_SGT:
7973     std::swap(LHS, RHS);
7974   case ICmpInst::ICMP_SLT:
7975     // X s< (X + C)<nsw> if C > 0
7976     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7977         C.isStrictlyPositive())
7978       return true;
7979 
7980     // (X + C)<nsw> s< X if C < 0
7981     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7982       return true;
7983     break;
7984   }
7985 
7986   return false;
7987 }
7988 
7989 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7990                                                    const SCEV *LHS,
7991                                                    const SCEV *RHS) {
7992   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7993     return false;
7994 
7995   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7996   // the stack can result in exponential time complexity.
7997   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7998 
7999   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8000   //
8001   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8002   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8003   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8004   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8005   // use isKnownPredicate later if needed.
8006   return isKnownNonNegative(RHS) &&
8007          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8008          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8009 }
8010 
8011 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8012                                         ICmpInst::Predicate Pred,
8013                                         const SCEV *LHS, const SCEV *RHS) {
8014   // No need to even try if we know the module has no guards.
8015   if (!HasGuards)
8016     return false;
8017 
8018   return any_of(*BB, [&](Instruction &I) {
8019     using namespace llvm::PatternMatch;
8020 
8021     Value *Condition;
8022     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8023                          m_Value(Condition))) &&
8024            isImpliedCond(Pred, LHS, RHS, Condition, false);
8025   });
8026 }
8027 
8028 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8029 /// protected by a conditional between LHS and RHS.  This is used to
8030 /// to eliminate casts.
8031 bool
8032 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8033                                              ICmpInst::Predicate Pred,
8034                                              const SCEV *LHS, const SCEV *RHS) {
8035   // Interpret a null as meaning no loop, where there is obviously no guard
8036   // (interprocedural conditions notwithstanding).
8037   if (!L) return true;
8038 
8039   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8040     return true;
8041 
8042   BasicBlock *Latch = L->getLoopLatch();
8043   if (!Latch)
8044     return false;
8045 
8046   BranchInst *LoopContinuePredicate =
8047     dyn_cast<BranchInst>(Latch->getTerminator());
8048   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8049       isImpliedCond(Pred, LHS, RHS,
8050                     LoopContinuePredicate->getCondition(),
8051                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8052     return true;
8053 
8054   // We don't want more than one activation of the following loops on the stack
8055   // -- that can lead to O(n!) time complexity.
8056   if (WalkingBEDominatingConds)
8057     return false;
8058 
8059   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8060 
8061   // See if we can exploit a trip count to prove the predicate.
8062   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8063   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8064   if (LatchBECount != getCouldNotCompute()) {
8065     // We know that Latch branches back to the loop header exactly
8066     // LatchBECount times.  This means the backdege condition at Latch is
8067     // equivalent to  "{0,+,1} u< LatchBECount".
8068     Type *Ty = LatchBECount->getType();
8069     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8070     const SCEV *LoopCounter =
8071       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8072     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8073                       LatchBECount))
8074       return true;
8075   }
8076 
8077   // Check conditions due to any @llvm.assume intrinsics.
8078   for (auto &AssumeVH : AC.assumptions()) {
8079     if (!AssumeVH)
8080       continue;
8081     auto *CI = cast<CallInst>(AssumeVH);
8082     if (!DT.dominates(CI, Latch->getTerminator()))
8083       continue;
8084 
8085     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8086       return true;
8087   }
8088 
8089   // If the loop is not reachable from the entry block, we risk running into an
8090   // infinite loop as we walk up into the dom tree.  These loops do not matter
8091   // anyway, so we just return a conservative answer when we see them.
8092   if (!DT.isReachableFromEntry(L->getHeader()))
8093     return false;
8094 
8095   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8096     return true;
8097 
8098   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8099        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8100 
8101     assert(DTN && "should reach the loop header before reaching the root!");
8102 
8103     BasicBlock *BB = DTN->getBlock();
8104     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8105       return true;
8106 
8107     BasicBlock *PBB = BB->getSinglePredecessor();
8108     if (!PBB)
8109       continue;
8110 
8111     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8112     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8113       continue;
8114 
8115     Value *Condition = ContinuePredicate->getCondition();
8116 
8117     // If we have an edge `E` within the loop body that dominates the only
8118     // latch, the condition guarding `E` also guards the backedge.  This
8119     // reasoning works only for loops with a single latch.
8120 
8121     BasicBlockEdge DominatingEdge(PBB, BB);
8122     if (DominatingEdge.isSingleEdge()) {
8123       // We're constructively (and conservatively) enumerating edges within the
8124       // loop body that dominate the latch.  The dominator tree better agree
8125       // with us on this:
8126       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8127 
8128       if (isImpliedCond(Pred, LHS, RHS, Condition,
8129                         BB != ContinuePredicate->getSuccessor(0)))
8130         return true;
8131     }
8132   }
8133 
8134   return false;
8135 }
8136 
8137 bool
8138 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8139                                           ICmpInst::Predicate Pred,
8140                                           const SCEV *LHS, const SCEV *RHS) {
8141   // Interpret a null as meaning no loop, where there is obviously no guard
8142   // (interprocedural conditions notwithstanding).
8143   if (!L) return false;
8144 
8145   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8146     return true;
8147 
8148   // Starting at the loop predecessor, climb up the predecessor chain, as long
8149   // as there are predecessors that can be found that have unique successors
8150   // leading to the original header.
8151   for (std::pair<BasicBlock *, BasicBlock *>
8152          Pair(L->getLoopPredecessor(), L->getHeader());
8153        Pair.first;
8154        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8155 
8156     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8157       return true;
8158 
8159     BranchInst *LoopEntryPredicate =
8160       dyn_cast<BranchInst>(Pair.first->getTerminator());
8161     if (!LoopEntryPredicate ||
8162         LoopEntryPredicate->isUnconditional())
8163       continue;
8164 
8165     if (isImpliedCond(Pred, LHS, RHS,
8166                       LoopEntryPredicate->getCondition(),
8167                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8168       return true;
8169   }
8170 
8171   // Check conditions due to any @llvm.assume intrinsics.
8172   for (auto &AssumeVH : AC.assumptions()) {
8173     if (!AssumeVH)
8174       continue;
8175     auto *CI = cast<CallInst>(AssumeVH);
8176     if (!DT.dominates(CI, L->getHeader()))
8177       continue;
8178 
8179     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8180       return true;
8181   }
8182 
8183   return false;
8184 }
8185 
8186 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8187                                     const SCEV *LHS, const SCEV *RHS,
8188                                     Value *FoundCondValue,
8189                                     bool Inverse) {
8190   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8191     return false;
8192 
8193   auto ClearOnExit =
8194       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8195 
8196   // Recursively handle And and Or conditions.
8197   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8198     if (BO->getOpcode() == Instruction::And) {
8199       if (!Inverse)
8200         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8201                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8202     } else if (BO->getOpcode() == Instruction::Or) {
8203       if (Inverse)
8204         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8205                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8206     }
8207   }
8208 
8209   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8210   if (!ICI) return false;
8211 
8212   // Now that we found a conditional branch that dominates the loop or controls
8213   // the loop latch. Check to see if it is the comparison we are looking for.
8214   ICmpInst::Predicate FoundPred;
8215   if (Inverse)
8216     FoundPred = ICI->getInversePredicate();
8217   else
8218     FoundPred = ICI->getPredicate();
8219 
8220   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8221   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8222 
8223   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8224 }
8225 
8226 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8227                                     const SCEV *RHS,
8228                                     ICmpInst::Predicate FoundPred,
8229                                     const SCEV *FoundLHS,
8230                                     const SCEV *FoundRHS) {
8231   // Balance the types.
8232   if (getTypeSizeInBits(LHS->getType()) <
8233       getTypeSizeInBits(FoundLHS->getType())) {
8234     if (CmpInst::isSigned(Pred)) {
8235       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8236       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8237     } else {
8238       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8239       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8240     }
8241   } else if (getTypeSizeInBits(LHS->getType()) >
8242       getTypeSizeInBits(FoundLHS->getType())) {
8243     if (CmpInst::isSigned(FoundPred)) {
8244       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8245       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8246     } else {
8247       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8248       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8249     }
8250   }
8251 
8252   // Canonicalize the query to match the way instcombine will have
8253   // canonicalized the comparison.
8254   if (SimplifyICmpOperands(Pred, LHS, RHS))
8255     if (LHS == RHS)
8256       return CmpInst::isTrueWhenEqual(Pred);
8257   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8258     if (FoundLHS == FoundRHS)
8259       return CmpInst::isFalseWhenEqual(FoundPred);
8260 
8261   // Check to see if we can make the LHS or RHS match.
8262   if (LHS == FoundRHS || RHS == FoundLHS) {
8263     if (isa<SCEVConstant>(RHS)) {
8264       std::swap(FoundLHS, FoundRHS);
8265       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8266     } else {
8267       std::swap(LHS, RHS);
8268       Pred = ICmpInst::getSwappedPredicate(Pred);
8269     }
8270   }
8271 
8272   // Check whether the found predicate is the same as the desired predicate.
8273   if (FoundPred == Pred)
8274     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8275 
8276   // Check whether swapping the found predicate makes it the same as the
8277   // desired predicate.
8278   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8279     if (isa<SCEVConstant>(RHS))
8280       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8281     else
8282       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8283                                    RHS, LHS, FoundLHS, FoundRHS);
8284   }
8285 
8286   // Unsigned comparison is the same as signed comparison when both the operands
8287   // are non-negative.
8288   if (CmpInst::isUnsigned(FoundPred) &&
8289       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8290       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8291     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8292 
8293   // Check if we can make progress by sharpening ranges.
8294   if (FoundPred == ICmpInst::ICMP_NE &&
8295       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8296 
8297     const SCEVConstant *C = nullptr;
8298     const SCEV *V = nullptr;
8299 
8300     if (isa<SCEVConstant>(FoundLHS)) {
8301       C = cast<SCEVConstant>(FoundLHS);
8302       V = FoundRHS;
8303     } else {
8304       C = cast<SCEVConstant>(FoundRHS);
8305       V = FoundLHS;
8306     }
8307 
8308     // The guarding predicate tells us that C != V. If the known range
8309     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8310     // range we consider has to correspond to same signedness as the
8311     // predicate we're interested in folding.
8312 
8313     APInt Min = ICmpInst::isSigned(Pred) ?
8314         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8315 
8316     if (Min == C->getAPInt()) {
8317       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8318       // This is true even if (Min + 1) wraps around -- in case of
8319       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8320 
8321       APInt SharperMin = Min + 1;
8322 
8323       switch (Pred) {
8324         case ICmpInst::ICMP_SGE:
8325         case ICmpInst::ICMP_UGE:
8326           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8327           // RHS, we're done.
8328           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8329                                     getConstant(SharperMin)))
8330             return true;
8331 
8332         case ICmpInst::ICMP_SGT:
8333         case ICmpInst::ICMP_UGT:
8334           // We know from the range information that (V `Pred` Min ||
8335           // V == Min).  We know from the guarding condition that !(V
8336           // == Min).  This gives us
8337           //
8338           //       V `Pred` Min || V == Min && !(V == Min)
8339           //   =>  V `Pred` Min
8340           //
8341           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8342 
8343           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8344             return true;
8345 
8346         default:
8347           // No change
8348           break;
8349       }
8350     }
8351   }
8352 
8353   // Check whether the actual condition is beyond sufficient.
8354   if (FoundPred == ICmpInst::ICMP_EQ)
8355     if (ICmpInst::isTrueWhenEqual(Pred))
8356       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8357         return true;
8358   if (Pred == ICmpInst::ICMP_NE)
8359     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8360       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8361         return true;
8362 
8363   // Otherwise assume the worst.
8364   return false;
8365 }
8366 
8367 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8368                                      const SCEV *&L, const SCEV *&R,
8369                                      SCEV::NoWrapFlags &Flags) {
8370   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8371   if (!AE || AE->getNumOperands() != 2)
8372     return false;
8373 
8374   L = AE->getOperand(0);
8375   R = AE->getOperand(1);
8376   Flags = AE->getNoWrapFlags();
8377   return true;
8378 }
8379 
8380 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8381                                                            const SCEV *Less) {
8382   // We avoid subtracting expressions here because this function is usually
8383   // fairly deep in the call stack (i.e. is called many times).
8384 
8385   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8386     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8387     const auto *MAR = cast<SCEVAddRecExpr>(More);
8388 
8389     if (LAR->getLoop() != MAR->getLoop())
8390       return None;
8391 
8392     // We look at affine expressions only; not for correctness but to keep
8393     // getStepRecurrence cheap.
8394     if (!LAR->isAffine() || !MAR->isAffine())
8395       return None;
8396 
8397     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8398       return None;
8399 
8400     Less = LAR->getStart();
8401     More = MAR->getStart();
8402 
8403     // fall through
8404   }
8405 
8406   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8407     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8408     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8409     return M - L;
8410   }
8411 
8412   const SCEV *L, *R;
8413   SCEV::NoWrapFlags Flags;
8414   if (splitBinaryAdd(Less, L, R, Flags))
8415     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8416       if (R == More)
8417         return -(LC->getAPInt());
8418 
8419   if (splitBinaryAdd(More, L, R, Flags))
8420     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8421       if (R == Less)
8422         return LC->getAPInt();
8423 
8424   return None;
8425 }
8426 
8427 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8428     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8429     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8430   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8431     return false;
8432 
8433   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8434   if (!AddRecLHS)
8435     return false;
8436 
8437   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8438   if (!AddRecFoundLHS)
8439     return false;
8440 
8441   // We'd like to let SCEV reason about control dependencies, so we constrain
8442   // both the inequalities to be about add recurrences on the same loop.  This
8443   // way we can use isLoopEntryGuardedByCond later.
8444 
8445   const Loop *L = AddRecFoundLHS->getLoop();
8446   if (L != AddRecLHS->getLoop())
8447     return false;
8448 
8449   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8450   //
8451   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8452   //                                                                  ... (2)
8453   //
8454   // Informal proof for (2), assuming (1) [*]:
8455   //
8456   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8457   //
8458   // Then
8459   //
8460   //       FoundLHS s< FoundRHS s< INT_MIN - C
8461   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8462   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8463   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8464   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8465   // <=>  FoundLHS + C s< FoundRHS + C
8466   //
8467   // [*]: (1) can be proved by ruling out overflow.
8468   //
8469   // [**]: This can be proved by analyzing all the four possibilities:
8470   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8471   //    (A s>= 0, B s>= 0).
8472   //
8473   // Note:
8474   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8475   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8476   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8477   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8478   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8479   // C)".
8480 
8481   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8482   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8483   if (!LDiff || !RDiff || *LDiff != *RDiff)
8484     return false;
8485 
8486   if (LDiff->isMinValue())
8487     return true;
8488 
8489   APInt FoundRHSLimit;
8490 
8491   if (Pred == CmpInst::ICMP_ULT) {
8492     FoundRHSLimit = -(*RDiff);
8493   } else {
8494     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8495     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8496   }
8497 
8498   // Try to prove (1) or (2), as needed.
8499   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8500                                   getConstant(FoundRHSLimit));
8501 }
8502 
8503 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8504                                             const SCEV *LHS, const SCEV *RHS,
8505                                             const SCEV *FoundLHS,
8506                                             const SCEV *FoundRHS) {
8507   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8508     return true;
8509 
8510   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8511     return true;
8512 
8513   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8514                                      FoundLHS, FoundRHS) ||
8515          // ~x < ~y --> x > y
8516          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8517                                      getNotSCEV(FoundRHS),
8518                                      getNotSCEV(FoundLHS));
8519 }
8520 
8521 
8522 /// If Expr computes ~A, return A else return nullptr
8523 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8524   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8525   if (!Add || Add->getNumOperands() != 2 ||
8526       !Add->getOperand(0)->isAllOnesValue())
8527     return nullptr;
8528 
8529   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8530   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8531       !AddRHS->getOperand(0)->isAllOnesValue())
8532     return nullptr;
8533 
8534   return AddRHS->getOperand(1);
8535 }
8536 
8537 
8538 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8539 template<typename MaxExprType>
8540 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8541                               const SCEV *Candidate) {
8542   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8543   if (!MaxExpr) return false;
8544 
8545   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8546 }
8547 
8548 
8549 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8550 template<typename MaxExprType>
8551 static bool IsMinConsistingOf(ScalarEvolution &SE,
8552                               const SCEV *MaybeMinExpr,
8553                               const SCEV *Candidate) {
8554   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8555   if (!MaybeMaxExpr)
8556     return false;
8557 
8558   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8559 }
8560 
8561 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8562                                            ICmpInst::Predicate Pred,
8563                                            const SCEV *LHS, const SCEV *RHS) {
8564 
8565   // If both sides are affine addrecs for the same loop, with equal
8566   // steps, and we know the recurrences don't wrap, then we only
8567   // need to check the predicate on the starting values.
8568 
8569   if (!ICmpInst::isRelational(Pred))
8570     return false;
8571 
8572   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8573   if (!LAR)
8574     return false;
8575   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8576   if (!RAR)
8577     return false;
8578   if (LAR->getLoop() != RAR->getLoop())
8579     return false;
8580   if (!LAR->isAffine() || !RAR->isAffine())
8581     return false;
8582 
8583   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8584     return false;
8585 
8586   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8587                          SCEV::FlagNSW : SCEV::FlagNUW;
8588   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8589     return false;
8590 
8591   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8592 }
8593 
8594 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8595 /// expression?
8596 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8597                                         ICmpInst::Predicate Pred,
8598                                         const SCEV *LHS, const SCEV *RHS) {
8599   switch (Pred) {
8600   default:
8601     return false;
8602 
8603   case ICmpInst::ICMP_SGE:
8604     std::swap(LHS, RHS);
8605     LLVM_FALLTHROUGH;
8606   case ICmpInst::ICMP_SLE:
8607     return
8608       // min(A, ...) <= A
8609       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8610       // A <= max(A, ...)
8611       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8612 
8613   case ICmpInst::ICMP_UGE:
8614     std::swap(LHS, RHS);
8615     LLVM_FALLTHROUGH;
8616   case ICmpInst::ICMP_ULE:
8617     return
8618       // min(A, ...) <= A
8619       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8620       // A <= max(A, ...)
8621       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8622   }
8623 
8624   llvm_unreachable("covered switch fell through?!");
8625 }
8626 
8627 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
8628                                              const SCEV *LHS, const SCEV *RHS,
8629                                              const SCEV *FoundLHS,
8630                                              const SCEV *FoundRHS,
8631                                              unsigned Depth) {
8632   assert(getTypeSizeInBits(LHS->getType()) ==
8633              getTypeSizeInBits(RHS->getType()) &&
8634          "LHS and RHS have different sizes?");
8635   assert(getTypeSizeInBits(FoundLHS->getType()) ==
8636              getTypeSizeInBits(FoundRHS->getType()) &&
8637          "FoundLHS and FoundRHS have different sizes?");
8638   // We want to avoid hurting the compile time with analysis of too big trees.
8639   if (Depth > MaxSCEVOperationsImplicationDepth)
8640     return false;
8641   // We only want to work with ICMP_SGT comparison so far.
8642   // TODO: Extend to ICMP_UGT?
8643   if (Pred == ICmpInst::ICMP_SLT) {
8644     Pred = ICmpInst::ICMP_SGT;
8645     std::swap(LHS, RHS);
8646     std::swap(FoundLHS, FoundRHS);
8647   }
8648   if (Pred != ICmpInst::ICMP_SGT)
8649     return false;
8650 
8651   auto GetOpFromSExt = [&](const SCEV *S) {
8652     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
8653       return Ext->getOperand();
8654     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
8655     // the constant in some cases.
8656     return S;
8657   };
8658 
8659   // Acquire values from extensions.
8660   auto *OrigFoundLHS = FoundLHS;
8661   LHS = GetOpFromSExt(LHS);
8662   FoundLHS = GetOpFromSExt(FoundLHS);
8663 
8664   // Is the SGT predicate can be proved trivially or using the found context.
8665   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
8666     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
8667            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
8668                                   FoundRHS, Depth + 1);
8669   };
8670 
8671   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
8672     // We want to avoid creation of any new non-constant SCEV. Since we are
8673     // going to compare the operands to RHS, we should be certain that we don't
8674     // need any size extensions for this. So let's decline all cases when the
8675     // sizes of types of LHS and RHS do not match.
8676     // TODO: Maybe try to get RHS from sext to catch more cases?
8677     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
8678       return false;
8679 
8680     // Should not overflow.
8681     if (!LHSAddExpr->hasNoSignedWrap())
8682       return false;
8683 
8684     auto *LL = LHSAddExpr->getOperand(0);
8685     auto *LR = LHSAddExpr->getOperand(1);
8686     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
8687 
8688     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
8689     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
8690       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
8691     };
8692     // Try to prove the following rule:
8693     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
8694     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
8695     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
8696       return true;
8697   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
8698     Value *LL, *LR;
8699     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
8700     using namespace llvm::PatternMatch;
8701     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
8702       // Rules for division.
8703       // We are going to perform some comparisons with Denominator and its
8704       // derivative expressions. In general case, creating a SCEV for it may
8705       // lead to a complex analysis of the entire graph, and in particular it
8706       // can request trip count recalculation for the same loop. This would
8707       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
8708       // this, we only want to create SCEVs that are constants in this section.
8709       // So we bail if Denominator is not a constant.
8710       if (!isa<ConstantInt>(LR))
8711         return false;
8712 
8713       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
8714 
8715       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
8716       // then a SCEV for the numerator already exists and matches with FoundLHS.
8717       auto *Numerator = getExistingSCEV(LL);
8718       if (!Numerator || Numerator->getType() != FoundLHS->getType())
8719         return false;
8720 
8721       // Make sure that the numerator matches with FoundLHS and the denominator
8722       // is positive.
8723       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
8724         return false;
8725 
8726       auto *DTy = Denominator->getType();
8727       auto *FRHSTy = FoundRHS->getType();
8728       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
8729         // One of types is a pointer and another one is not. We cannot extend
8730         // them properly to a wider type, so let us just reject this case.
8731         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
8732         // to avoid this check.
8733         return false;
8734 
8735       // Given that:
8736       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
8737       auto *WTy = getWiderType(DTy, FRHSTy);
8738       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
8739       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
8740 
8741       // Try to prove the following rule:
8742       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
8743       // For example, given that FoundLHS > 2. It means that FoundLHS is at
8744       // least 3. If we divide it by Denominator < 4, we will have at least 1.
8745       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
8746       if (isKnownNonPositive(RHS) &&
8747           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
8748         return true;
8749 
8750       // Try to prove the following rule:
8751       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
8752       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
8753       // If we divide it by Denominator > 2, then:
8754       // 1. If FoundLHS is negative, then the result is 0.
8755       // 2. If FoundLHS is non-negative, then the result is non-negative.
8756       // Anyways, the result is non-negative.
8757       auto *MinusOne = getNegativeSCEV(getOne(WTy));
8758       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
8759       if (isKnownNegative(RHS) &&
8760           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
8761         return true;
8762     }
8763   }
8764 
8765   return false;
8766 }
8767 
8768 bool
8769 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
8770                                            const SCEV *LHS, const SCEV *RHS) {
8771   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8772          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8773          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8774          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8775 }
8776 
8777 bool
8778 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8779                                              const SCEV *LHS, const SCEV *RHS,
8780                                              const SCEV *FoundLHS,
8781                                              const SCEV *FoundRHS) {
8782   switch (Pred) {
8783   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8784   case ICmpInst::ICMP_EQ:
8785   case ICmpInst::ICMP_NE:
8786     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8787       return true;
8788     break;
8789   case ICmpInst::ICMP_SLT:
8790   case ICmpInst::ICMP_SLE:
8791     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8792         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8793       return true;
8794     break;
8795   case ICmpInst::ICMP_SGT:
8796   case ICmpInst::ICMP_SGE:
8797     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8798         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8799       return true;
8800     break;
8801   case ICmpInst::ICMP_ULT:
8802   case ICmpInst::ICMP_ULE:
8803     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8804         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8805       return true;
8806     break;
8807   case ICmpInst::ICMP_UGT:
8808   case ICmpInst::ICMP_UGE:
8809     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8810         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8811       return true;
8812     break;
8813   }
8814 
8815   // Maybe it can be proved via operations?
8816   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
8817     return true;
8818 
8819   return false;
8820 }
8821 
8822 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8823                                                      const SCEV *LHS,
8824                                                      const SCEV *RHS,
8825                                                      const SCEV *FoundLHS,
8826                                                      const SCEV *FoundRHS) {
8827   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8828     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8829     // reduce the compile time impact of this optimization.
8830     return false;
8831 
8832   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8833   if (!Addend)
8834     return false;
8835 
8836   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8837 
8838   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8839   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8840   ConstantRange FoundLHSRange =
8841       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8842 
8843   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8844   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8845 
8846   // We can also compute the range of values for `LHS` that satisfy the
8847   // consequent, "`LHS` `Pred` `RHS`":
8848   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8849   ConstantRange SatisfyingLHSRange =
8850       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8851 
8852   // The antecedent implies the consequent if every value of `LHS` that
8853   // satisfies the antecedent also satisfies the consequent.
8854   return SatisfyingLHSRange.contains(LHSRange);
8855 }
8856 
8857 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8858                                          bool IsSigned, bool NoWrap) {
8859   assert(isKnownPositive(Stride) && "Positive stride expected!");
8860 
8861   if (NoWrap) return false;
8862 
8863   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8864   const SCEV *One = getOne(Stride->getType());
8865 
8866   if (IsSigned) {
8867     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8868     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8869     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8870                                 .getSignedMax();
8871 
8872     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8873     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8874   }
8875 
8876   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8877   APInt MaxValue = APInt::getMaxValue(BitWidth);
8878   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8879                               .getUnsignedMax();
8880 
8881   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8882   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8883 }
8884 
8885 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8886                                          bool IsSigned, bool NoWrap) {
8887   if (NoWrap) return false;
8888 
8889   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8890   const SCEV *One = getOne(Stride->getType());
8891 
8892   if (IsSigned) {
8893     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8894     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8895     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8896                                .getSignedMax();
8897 
8898     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8899     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8900   }
8901 
8902   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8903   APInt MinValue = APInt::getMinValue(BitWidth);
8904   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8905                             .getUnsignedMax();
8906 
8907   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8908   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8909 }
8910 
8911 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8912                                             bool Equality) {
8913   const SCEV *One = getOne(Step->getType());
8914   Delta = Equality ? getAddExpr(Delta, Step)
8915                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8916   return getUDivExpr(Delta, Step);
8917 }
8918 
8919 ScalarEvolution::ExitLimit
8920 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8921                                   const Loop *L, bool IsSigned,
8922                                   bool ControlsExit, bool AllowPredicates) {
8923   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8924   // We handle only IV < Invariant
8925   if (!isLoopInvariant(RHS, L))
8926     return getCouldNotCompute();
8927 
8928   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8929   bool PredicatedIV = false;
8930 
8931   if (!IV && AllowPredicates) {
8932     // Try to make this an AddRec using runtime tests, in the first X
8933     // iterations of this loop, where X is the SCEV expression found by the
8934     // algorithm below.
8935     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8936     PredicatedIV = true;
8937   }
8938 
8939   // Avoid weird loops
8940   if (!IV || IV->getLoop() != L || !IV->isAffine())
8941     return getCouldNotCompute();
8942 
8943   bool NoWrap = ControlsExit &&
8944                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8945 
8946   const SCEV *Stride = IV->getStepRecurrence(*this);
8947 
8948   bool PositiveStride = isKnownPositive(Stride);
8949 
8950   // Avoid negative or zero stride values.
8951   if (!PositiveStride) {
8952     // We can compute the correct backedge taken count for loops with unknown
8953     // strides if we can prove that the loop is not an infinite loop with side
8954     // effects. Here's the loop structure we are trying to handle -
8955     //
8956     // i = start
8957     // do {
8958     //   A[i] = i;
8959     //   i += s;
8960     // } while (i < end);
8961     //
8962     // The backedge taken count for such loops is evaluated as -
8963     // (max(end, start + stride) - start - 1) /u stride
8964     //
8965     // The additional preconditions that we need to check to prove correctness
8966     // of the above formula is as follows -
8967     //
8968     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8969     //    NoWrap flag).
8970     // b) loop is single exit with no side effects.
8971     //
8972     //
8973     // Precondition a) implies that if the stride is negative, this is a single
8974     // trip loop. The backedge taken count formula reduces to zero in this case.
8975     //
8976     // Precondition b) implies that the unknown stride cannot be zero otherwise
8977     // we have UB.
8978     //
8979     // The positive stride case is the same as isKnownPositive(Stride) returning
8980     // true (original behavior of the function).
8981     //
8982     // We want to make sure that the stride is truly unknown as there are edge
8983     // cases where ScalarEvolution propagates no wrap flags to the
8984     // post-increment/decrement IV even though the increment/decrement operation
8985     // itself is wrapping. The computed backedge taken count may be wrong in
8986     // such cases. This is prevented by checking that the stride is not known to
8987     // be either positive or non-positive. For example, no wrap flags are
8988     // propagated to the post-increment IV of this loop with a trip count of 2 -
8989     //
8990     // unsigned char i;
8991     // for(i=127; i<128; i+=129)
8992     //   A[i] = i;
8993     //
8994     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8995         !loopHasNoSideEffects(L))
8996       return getCouldNotCompute();
8997 
8998   } else if (!Stride->isOne() &&
8999              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9000     // Avoid proven overflow cases: this will ensure that the backedge taken
9001     // count will not generate any unsigned overflow. Relaxed no-overflow
9002     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9003     // undefined behaviors like the case of C language.
9004     return getCouldNotCompute();
9005 
9006   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9007                                       : ICmpInst::ICMP_ULT;
9008   const SCEV *Start = IV->getStart();
9009   const SCEV *End = RHS;
9010   // If the backedge is taken at least once, then it will be taken
9011   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9012   // is the LHS value of the less-than comparison the first time it is evaluated
9013   // and End is the RHS.
9014   const SCEV *BECountIfBackedgeTaken =
9015     computeBECount(getMinusSCEV(End, Start), Stride, false);
9016   // If the loop entry is guarded by the result of the backedge test of the
9017   // first loop iteration, then we know the backedge will be taken at least
9018   // once and so the backedge taken count is as above. If not then we use the
9019   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9020   // as if the backedge is taken at least once max(End,Start) is End and so the
9021   // result is as above, and if not max(End,Start) is Start so we get a backedge
9022   // count of zero.
9023   const SCEV *BECount;
9024   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9025     BECount = BECountIfBackedgeTaken;
9026   else {
9027     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9028     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9029   }
9030 
9031   const SCEV *MaxBECount;
9032   bool MaxOrZero = false;
9033   if (isa<SCEVConstant>(BECount))
9034     MaxBECount = BECount;
9035   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9036     // If we know exactly how many times the backedge will be taken if it's
9037     // taken at least once, then the backedge count will either be that or
9038     // zero.
9039     MaxBECount = BECountIfBackedgeTaken;
9040     MaxOrZero = true;
9041   } else {
9042     // Calculate the maximum backedge count based on the range of values
9043     // permitted by Start, End, and Stride.
9044     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
9045                               : getUnsignedRange(Start).getUnsignedMin();
9046 
9047     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9048 
9049     APInt StrideForMaxBECount;
9050 
9051     if (PositiveStride)
9052       StrideForMaxBECount =
9053         IsSigned ? getSignedRange(Stride).getSignedMin()
9054                  : getUnsignedRange(Stride).getUnsignedMin();
9055     else
9056       // Using a stride of 1 is safe when computing max backedge taken count for
9057       // a loop with unknown stride.
9058       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9059 
9060     APInt Limit =
9061       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9062                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9063 
9064     // Although End can be a MAX expression we estimate MaxEnd considering only
9065     // the case End = RHS. This is safe because in the other case (End - Start)
9066     // is zero, leading to a zero maximum backedge taken count.
9067     APInt MaxEnd =
9068       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
9069                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
9070 
9071     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9072                                 getConstant(StrideForMaxBECount), false);
9073   }
9074 
9075   if (isa<SCEVCouldNotCompute>(MaxBECount))
9076     MaxBECount = BECount;
9077 
9078   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9079 }
9080 
9081 ScalarEvolution::ExitLimit
9082 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9083                                      const Loop *L, bool IsSigned,
9084                                      bool ControlsExit, bool AllowPredicates) {
9085   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9086   // We handle only IV > Invariant
9087   if (!isLoopInvariant(RHS, L))
9088     return getCouldNotCompute();
9089 
9090   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9091   if (!IV && AllowPredicates)
9092     // Try to make this an AddRec using runtime tests, in the first X
9093     // iterations of this loop, where X is the SCEV expression found by the
9094     // algorithm below.
9095     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9096 
9097   // Avoid weird loops
9098   if (!IV || IV->getLoop() != L || !IV->isAffine())
9099     return getCouldNotCompute();
9100 
9101   bool NoWrap = ControlsExit &&
9102                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9103 
9104   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9105 
9106   // Avoid negative or zero stride values
9107   if (!isKnownPositive(Stride))
9108     return getCouldNotCompute();
9109 
9110   // Avoid proven overflow cases: this will ensure that the backedge taken count
9111   // will not generate any unsigned overflow. Relaxed no-overflow conditions
9112   // exploit NoWrapFlags, allowing to optimize in presence of undefined
9113   // behaviors like the case of C language.
9114   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9115     return getCouldNotCompute();
9116 
9117   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9118                                       : ICmpInst::ICMP_UGT;
9119 
9120   const SCEV *Start = IV->getStart();
9121   const SCEV *End = RHS;
9122   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9123     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9124 
9125   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9126 
9127   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
9128                             : getUnsignedRange(Start).getUnsignedMax();
9129 
9130   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
9131                              : getUnsignedRange(Stride).getUnsignedMin();
9132 
9133   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9134   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9135                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
9136 
9137   // Although End can be a MIN expression we estimate MinEnd considering only
9138   // the case End = RHS. This is safe because in the other case (Start - End)
9139   // is zero, leading to a zero maximum backedge taken count.
9140   APInt MinEnd =
9141     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
9142              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
9143 
9144 
9145   const SCEV *MaxBECount = getCouldNotCompute();
9146   if (isa<SCEVConstant>(BECount))
9147     MaxBECount = BECount;
9148   else
9149     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9150                                 getConstant(MinStride), false);
9151 
9152   if (isa<SCEVCouldNotCompute>(MaxBECount))
9153     MaxBECount = BECount;
9154 
9155   return ExitLimit(BECount, MaxBECount, false, Predicates);
9156 }
9157 
9158 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9159                                                     ScalarEvolution &SE) const {
9160   if (Range.isFullSet())  // Infinite loop.
9161     return SE.getCouldNotCompute();
9162 
9163   // If the start is a non-zero constant, shift the range to simplify things.
9164   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9165     if (!SC->getValue()->isZero()) {
9166       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9167       Operands[0] = SE.getZero(SC->getType());
9168       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9169                                              getNoWrapFlags(FlagNW));
9170       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9171         return ShiftedAddRec->getNumIterationsInRange(
9172             Range.subtract(SC->getAPInt()), SE);
9173       // This is strange and shouldn't happen.
9174       return SE.getCouldNotCompute();
9175     }
9176 
9177   // The only time we can solve this is when we have all constant indices.
9178   // Otherwise, we cannot determine the overflow conditions.
9179   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9180     return SE.getCouldNotCompute();
9181 
9182   // Okay at this point we know that all elements of the chrec are constants and
9183   // that the start element is zero.
9184 
9185   // First check to see if the range contains zero.  If not, the first
9186   // iteration exits.
9187   unsigned BitWidth = SE.getTypeSizeInBits(getType());
9188   if (!Range.contains(APInt(BitWidth, 0)))
9189     return SE.getZero(getType());
9190 
9191   if (isAffine()) {
9192     // If this is an affine expression then we have this situation:
9193     //   Solve {0,+,A} in Range  ===  Ax in Range
9194 
9195     // We know that zero is in the range.  If A is positive then we know that
9196     // the upper value of the range must be the first possible exit value.
9197     // If A is negative then the lower of the range is the last possible loop
9198     // value.  Also note that we already checked for a full range.
9199     APInt One(BitWidth,1);
9200     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9201     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
9202 
9203     // The exit value should be (End+A)/A.
9204     APInt ExitVal = (End + A).udiv(A);
9205     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9206 
9207     // Evaluate at the exit value.  If we really did fall out of the valid
9208     // range, then we computed our trip count, otherwise wrap around or other
9209     // things must have happened.
9210     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9211     if (Range.contains(Val->getValue()))
9212       return SE.getCouldNotCompute();  // Something strange happened
9213 
9214     // Ensure that the previous value is in the range.  This is a sanity check.
9215     assert(Range.contains(
9216            EvaluateConstantChrecAtConstant(this,
9217            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
9218            "Linear scev computation is off in a bad way!");
9219     return SE.getConstant(ExitValue);
9220   } else if (isQuadratic()) {
9221     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9222     // quadratic equation to solve it.  To do this, we must frame our problem in
9223     // terms of figuring out when zero is crossed, instead of when
9224     // Range.getUpper() is crossed.
9225     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9226     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9227     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9228 
9229     // Next, solve the constructed addrec
9230     if (auto Roots =
9231             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9232       const SCEVConstant *R1 = Roots->first;
9233       const SCEVConstant *R2 = Roots->second;
9234       // Pick the smallest positive root value.
9235       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9236               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9237         if (!CB->getZExtValue())
9238           std::swap(R1, R2); // R1 is the minimum root now.
9239 
9240         // Make sure the root is not off by one.  The returned iteration should
9241         // not be in the range, but the previous one should be.  When solving
9242         // for "X*X < 5", for example, we should not return a root of 2.
9243         ConstantInt *R1Val =
9244             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9245         if (Range.contains(R1Val->getValue())) {
9246           // The next iteration must be out of the range...
9247           ConstantInt *NextVal =
9248               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9249 
9250           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9251           if (!Range.contains(R1Val->getValue()))
9252             return SE.getConstant(NextVal);
9253           return SE.getCouldNotCompute(); // Something strange happened
9254         }
9255 
9256         // If R1 was not in the range, then it is a good return value.  Make
9257         // sure that R1-1 WAS in the range though, just in case.
9258         ConstantInt *NextVal =
9259             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9260         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9261         if (Range.contains(R1Val->getValue()))
9262           return R1;
9263         return SE.getCouldNotCompute(); // Something strange happened
9264       }
9265     }
9266   }
9267 
9268   return SE.getCouldNotCompute();
9269 }
9270 
9271 // Return true when S contains at least an undef value.
9272 static inline bool containsUndefs(const SCEV *S) {
9273   return SCEVExprContains(S, [](const SCEV *S) {
9274     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9275       return isa<UndefValue>(SU->getValue());
9276     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9277       return isa<UndefValue>(SC->getValue());
9278     return false;
9279   });
9280 }
9281 
9282 namespace {
9283 // Collect all steps of SCEV expressions.
9284 struct SCEVCollectStrides {
9285   ScalarEvolution &SE;
9286   SmallVectorImpl<const SCEV *> &Strides;
9287 
9288   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9289       : SE(SE), Strides(S) {}
9290 
9291   bool follow(const SCEV *S) {
9292     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9293       Strides.push_back(AR->getStepRecurrence(SE));
9294     return true;
9295   }
9296   bool isDone() const { return false; }
9297 };
9298 
9299 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9300 struct SCEVCollectTerms {
9301   SmallVectorImpl<const SCEV *> &Terms;
9302 
9303   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9304       : Terms(T) {}
9305 
9306   bool follow(const SCEV *S) {
9307     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9308         isa<SCEVSignExtendExpr>(S)) {
9309       if (!containsUndefs(S))
9310         Terms.push_back(S);
9311 
9312       // Stop recursion: once we collected a term, do not walk its operands.
9313       return false;
9314     }
9315 
9316     // Keep looking.
9317     return true;
9318   }
9319   bool isDone() const { return false; }
9320 };
9321 
9322 // Check if a SCEV contains an AddRecExpr.
9323 struct SCEVHasAddRec {
9324   bool &ContainsAddRec;
9325 
9326   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9327    ContainsAddRec = false;
9328   }
9329 
9330   bool follow(const SCEV *S) {
9331     if (isa<SCEVAddRecExpr>(S)) {
9332       ContainsAddRec = true;
9333 
9334       // Stop recursion: once we collected a term, do not walk its operands.
9335       return false;
9336     }
9337 
9338     // Keep looking.
9339     return true;
9340   }
9341   bool isDone() const { return false; }
9342 };
9343 
9344 // Find factors that are multiplied with an expression that (possibly as a
9345 // subexpression) contains an AddRecExpr. In the expression:
9346 //
9347 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9348 //
9349 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9350 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9351 // parameters as they form a product with an induction variable.
9352 //
9353 // This collector expects all array size parameters to be in the same MulExpr.
9354 // It might be necessary to later add support for collecting parameters that are
9355 // spread over different nested MulExpr.
9356 struct SCEVCollectAddRecMultiplies {
9357   SmallVectorImpl<const SCEV *> &Terms;
9358   ScalarEvolution &SE;
9359 
9360   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9361       : Terms(T), SE(SE) {}
9362 
9363   bool follow(const SCEV *S) {
9364     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9365       bool HasAddRec = false;
9366       SmallVector<const SCEV *, 0> Operands;
9367       for (auto Op : Mul->operands()) {
9368         if (isa<SCEVUnknown>(Op)) {
9369           Operands.push_back(Op);
9370         } else {
9371           bool ContainsAddRec;
9372           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9373           visitAll(Op, ContiansAddRec);
9374           HasAddRec |= ContainsAddRec;
9375         }
9376       }
9377       if (Operands.size() == 0)
9378         return true;
9379 
9380       if (!HasAddRec)
9381         return false;
9382 
9383       Terms.push_back(SE.getMulExpr(Operands));
9384       // Stop recursion: once we collected a term, do not walk its operands.
9385       return false;
9386     }
9387 
9388     // Keep looking.
9389     return true;
9390   }
9391   bool isDone() const { return false; }
9392 };
9393 }
9394 
9395 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9396 /// two places:
9397 ///   1) The strides of AddRec expressions.
9398 ///   2) Unknowns that are multiplied with AddRec expressions.
9399 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9400     SmallVectorImpl<const SCEV *> &Terms) {
9401   SmallVector<const SCEV *, 4> Strides;
9402   SCEVCollectStrides StrideCollector(*this, Strides);
9403   visitAll(Expr, StrideCollector);
9404 
9405   DEBUG({
9406       dbgs() << "Strides:\n";
9407       for (const SCEV *S : Strides)
9408         dbgs() << *S << "\n";
9409     });
9410 
9411   for (const SCEV *S : Strides) {
9412     SCEVCollectTerms TermCollector(Terms);
9413     visitAll(S, TermCollector);
9414   }
9415 
9416   DEBUG({
9417       dbgs() << "Terms:\n";
9418       for (const SCEV *T : Terms)
9419         dbgs() << *T << "\n";
9420     });
9421 
9422   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9423   visitAll(Expr, MulCollector);
9424 }
9425 
9426 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9427                                    SmallVectorImpl<const SCEV *> &Terms,
9428                                    SmallVectorImpl<const SCEV *> &Sizes) {
9429   int Last = Terms.size() - 1;
9430   const SCEV *Step = Terms[Last];
9431 
9432   // End of recursion.
9433   if (Last == 0) {
9434     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9435       SmallVector<const SCEV *, 2> Qs;
9436       for (const SCEV *Op : M->operands())
9437         if (!isa<SCEVConstant>(Op))
9438           Qs.push_back(Op);
9439 
9440       Step = SE.getMulExpr(Qs);
9441     }
9442 
9443     Sizes.push_back(Step);
9444     return true;
9445   }
9446 
9447   for (const SCEV *&Term : Terms) {
9448     // Normalize the terms before the next call to findArrayDimensionsRec.
9449     const SCEV *Q, *R;
9450     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9451 
9452     // Bail out when GCD does not evenly divide one of the terms.
9453     if (!R->isZero())
9454       return false;
9455 
9456     Term = Q;
9457   }
9458 
9459   // Remove all SCEVConstants.
9460   Terms.erase(
9461       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9462       Terms.end());
9463 
9464   if (Terms.size() > 0)
9465     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9466       return false;
9467 
9468   Sizes.push_back(Step);
9469   return true;
9470 }
9471 
9472 
9473 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9474 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9475   for (const SCEV *T : Terms)
9476     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9477       return true;
9478   return false;
9479 }
9480 
9481 // Return the number of product terms in S.
9482 static inline int numberOfTerms(const SCEV *S) {
9483   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9484     return Expr->getNumOperands();
9485   return 1;
9486 }
9487 
9488 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9489   if (isa<SCEVConstant>(T))
9490     return nullptr;
9491 
9492   if (isa<SCEVUnknown>(T))
9493     return T;
9494 
9495   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9496     SmallVector<const SCEV *, 2> Factors;
9497     for (const SCEV *Op : M->operands())
9498       if (!isa<SCEVConstant>(Op))
9499         Factors.push_back(Op);
9500 
9501     return SE.getMulExpr(Factors);
9502   }
9503 
9504   return T;
9505 }
9506 
9507 /// Return the size of an element read or written by Inst.
9508 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9509   Type *Ty;
9510   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9511     Ty = Store->getValueOperand()->getType();
9512   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9513     Ty = Load->getType();
9514   else
9515     return nullptr;
9516 
9517   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9518   return getSizeOfExpr(ETy, Ty);
9519 }
9520 
9521 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9522                                           SmallVectorImpl<const SCEV *> &Sizes,
9523                                           const SCEV *ElementSize) const {
9524   if (Terms.size() < 1 || !ElementSize)
9525     return;
9526 
9527   // Early return when Terms do not contain parameters: we do not delinearize
9528   // non parametric SCEVs.
9529   if (!containsParameters(Terms))
9530     return;
9531 
9532   DEBUG({
9533       dbgs() << "Terms:\n";
9534       for (const SCEV *T : Terms)
9535         dbgs() << *T << "\n";
9536     });
9537 
9538   // Remove duplicates.
9539   std::sort(Terms.begin(), Terms.end());
9540   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9541 
9542   // Put larger terms first.
9543   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9544     return numberOfTerms(LHS) > numberOfTerms(RHS);
9545   });
9546 
9547   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9548 
9549   // Try to divide all terms by the element size. If term is not divisible by
9550   // element size, proceed with the original term.
9551   for (const SCEV *&Term : Terms) {
9552     const SCEV *Q, *R;
9553     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9554     if (!Q->isZero())
9555       Term = Q;
9556   }
9557 
9558   SmallVector<const SCEV *, 4> NewTerms;
9559 
9560   // Remove constant factors.
9561   for (const SCEV *T : Terms)
9562     if (const SCEV *NewT = removeConstantFactors(SE, T))
9563       NewTerms.push_back(NewT);
9564 
9565   DEBUG({
9566       dbgs() << "Terms after sorting:\n";
9567       for (const SCEV *T : NewTerms)
9568         dbgs() << *T << "\n";
9569     });
9570 
9571   if (NewTerms.empty() ||
9572       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9573     Sizes.clear();
9574     return;
9575   }
9576 
9577   // The last element to be pushed into Sizes is the size of an element.
9578   Sizes.push_back(ElementSize);
9579 
9580   DEBUG({
9581       dbgs() << "Sizes:\n";
9582       for (const SCEV *S : Sizes)
9583         dbgs() << *S << "\n";
9584     });
9585 }
9586 
9587 void ScalarEvolution::computeAccessFunctions(
9588     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9589     SmallVectorImpl<const SCEV *> &Sizes) {
9590 
9591   // Early exit in case this SCEV is not an affine multivariate function.
9592   if (Sizes.empty())
9593     return;
9594 
9595   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9596     if (!AR->isAffine())
9597       return;
9598 
9599   const SCEV *Res = Expr;
9600   int Last = Sizes.size() - 1;
9601   for (int i = Last; i >= 0; i--) {
9602     const SCEV *Q, *R;
9603     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9604 
9605     DEBUG({
9606         dbgs() << "Res: " << *Res << "\n";
9607         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9608         dbgs() << "Res divided by Sizes[i]:\n";
9609         dbgs() << "Quotient: " << *Q << "\n";
9610         dbgs() << "Remainder: " << *R << "\n";
9611       });
9612 
9613     Res = Q;
9614 
9615     // Do not record the last subscript corresponding to the size of elements in
9616     // the array.
9617     if (i == Last) {
9618 
9619       // Bail out if the remainder is too complex.
9620       if (isa<SCEVAddRecExpr>(R)) {
9621         Subscripts.clear();
9622         Sizes.clear();
9623         return;
9624       }
9625 
9626       continue;
9627     }
9628 
9629     // Record the access function for the current subscript.
9630     Subscripts.push_back(R);
9631   }
9632 
9633   // Also push in last position the remainder of the last division: it will be
9634   // the access function of the innermost dimension.
9635   Subscripts.push_back(Res);
9636 
9637   std::reverse(Subscripts.begin(), Subscripts.end());
9638 
9639   DEBUG({
9640       dbgs() << "Subscripts:\n";
9641       for (const SCEV *S : Subscripts)
9642         dbgs() << *S << "\n";
9643     });
9644 }
9645 
9646 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9647 /// sizes of an array access. Returns the remainder of the delinearization that
9648 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9649 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9650 /// expressions in the stride and base of a SCEV corresponding to the
9651 /// computation of a GCD (greatest common divisor) of base and stride.  When
9652 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9653 ///
9654 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9655 ///
9656 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9657 ///
9658 ///    for (long i = 0; i < n; i++)
9659 ///      for (long j = 0; j < m; j++)
9660 ///        for (long k = 0; k < o; k++)
9661 ///          A[i][j][k] = 1.0;
9662 ///  }
9663 ///
9664 /// the delinearization input is the following AddRec SCEV:
9665 ///
9666 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9667 ///
9668 /// From this SCEV, we are able to say that the base offset of the access is %A
9669 /// because it appears as an offset that does not divide any of the strides in
9670 /// the loops:
9671 ///
9672 ///  CHECK: Base offset: %A
9673 ///
9674 /// and then SCEV->delinearize determines the size of some of the dimensions of
9675 /// the array as these are the multiples by which the strides are happening:
9676 ///
9677 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9678 ///
9679 /// Note that the outermost dimension remains of UnknownSize because there are
9680 /// no strides that would help identifying the size of the last dimension: when
9681 /// the array has been statically allocated, one could compute the size of that
9682 /// dimension by dividing the overall size of the array by the size of the known
9683 /// dimensions: %m * %o * 8.
9684 ///
9685 /// Finally delinearize provides the access functions for the array reference
9686 /// that does correspond to A[i][j][k] of the above C testcase:
9687 ///
9688 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9689 ///
9690 /// The testcases are checking the output of a function pass:
9691 /// DelinearizationPass that walks through all loads and stores of a function
9692 /// asking for the SCEV of the memory access with respect to all enclosing
9693 /// loops, calling SCEV->delinearize on that and printing the results.
9694 
9695 void ScalarEvolution::delinearize(const SCEV *Expr,
9696                                  SmallVectorImpl<const SCEV *> &Subscripts,
9697                                  SmallVectorImpl<const SCEV *> &Sizes,
9698                                  const SCEV *ElementSize) {
9699   // First step: collect parametric terms.
9700   SmallVector<const SCEV *, 4> Terms;
9701   collectParametricTerms(Expr, Terms);
9702 
9703   if (Terms.empty())
9704     return;
9705 
9706   // Second step: find subscript sizes.
9707   findArrayDimensions(Terms, Sizes, ElementSize);
9708 
9709   if (Sizes.empty())
9710     return;
9711 
9712   // Third step: compute the access functions for each subscript.
9713   computeAccessFunctions(Expr, Subscripts, Sizes);
9714 
9715   if (Subscripts.empty())
9716     return;
9717 
9718   DEBUG({
9719       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9720       dbgs() << "ArrayDecl[UnknownSize]";
9721       for (const SCEV *S : Sizes)
9722         dbgs() << "[" << *S << "]";
9723 
9724       dbgs() << "\nArrayRef";
9725       for (const SCEV *S : Subscripts)
9726         dbgs() << "[" << *S << "]";
9727       dbgs() << "\n";
9728     });
9729 }
9730 
9731 //===----------------------------------------------------------------------===//
9732 //                   SCEVCallbackVH Class Implementation
9733 //===----------------------------------------------------------------------===//
9734 
9735 void ScalarEvolution::SCEVCallbackVH::deleted() {
9736   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9737   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9738     SE->ConstantEvolutionLoopExitValue.erase(PN);
9739   SE->eraseValueFromMap(getValPtr());
9740   // this now dangles!
9741 }
9742 
9743 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9744   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9745 
9746   // Forget all the expressions associated with users of the old value,
9747   // so that future queries will recompute the expressions using the new
9748   // value.
9749   Value *Old = getValPtr();
9750   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9751   SmallPtrSet<User *, 8> Visited;
9752   while (!Worklist.empty()) {
9753     User *U = Worklist.pop_back_val();
9754     // Deleting the Old value will cause this to dangle. Postpone
9755     // that until everything else is done.
9756     if (U == Old)
9757       continue;
9758     if (!Visited.insert(U).second)
9759       continue;
9760     if (PHINode *PN = dyn_cast<PHINode>(U))
9761       SE->ConstantEvolutionLoopExitValue.erase(PN);
9762     SE->eraseValueFromMap(U);
9763     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9764   }
9765   // Delete the Old value.
9766   if (PHINode *PN = dyn_cast<PHINode>(Old))
9767     SE->ConstantEvolutionLoopExitValue.erase(PN);
9768   SE->eraseValueFromMap(Old);
9769   // this now dangles!
9770 }
9771 
9772 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9773   : CallbackVH(V), SE(se) {}
9774 
9775 //===----------------------------------------------------------------------===//
9776 //                   ScalarEvolution Class Implementation
9777 //===----------------------------------------------------------------------===//
9778 
9779 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9780                                  AssumptionCache &AC, DominatorTree &DT,
9781                                  LoopInfo &LI)
9782     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9783       CouldNotCompute(new SCEVCouldNotCompute()),
9784       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9785       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9786       FirstUnknown(nullptr) {
9787 
9788   // To use guards for proving predicates, we need to scan every instruction in
9789   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9790   // time if the IR does not actually contain any calls to
9791   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9792   //
9793   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9794   // to _add_ guards to the module when there weren't any before, and wants
9795   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9796   // efficient in lieu of being smart in that rather obscure case.
9797 
9798   auto *GuardDecl = F.getParent()->getFunction(
9799       Intrinsic::getName(Intrinsic::experimental_guard));
9800   HasGuards = GuardDecl && !GuardDecl->use_empty();
9801 }
9802 
9803 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9804     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9805       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9806       ValueExprMap(std::move(Arg.ValueExprMap)),
9807       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9808       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9809       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
9810       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9811       PredicatedBackedgeTakenCounts(
9812           std::move(Arg.PredicatedBackedgeTakenCounts)),
9813       ConstantEvolutionLoopExitValue(
9814           std::move(Arg.ConstantEvolutionLoopExitValue)),
9815       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9816       LoopDispositions(std::move(Arg.LoopDispositions)),
9817       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9818       BlockDispositions(std::move(Arg.BlockDispositions)),
9819       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9820       SignedRanges(std::move(Arg.SignedRanges)),
9821       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9822       UniquePreds(std::move(Arg.UniquePreds)),
9823       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9824       FirstUnknown(Arg.FirstUnknown) {
9825   Arg.FirstUnknown = nullptr;
9826 }
9827 
9828 ScalarEvolution::~ScalarEvolution() {
9829   // Iterate through all the SCEVUnknown instances and call their
9830   // destructors, so that they release their references to their values.
9831   for (SCEVUnknown *U = FirstUnknown; U;) {
9832     SCEVUnknown *Tmp = U;
9833     U = U->Next;
9834     Tmp->~SCEVUnknown();
9835   }
9836   FirstUnknown = nullptr;
9837 
9838   ExprValueMap.clear();
9839   ValueExprMap.clear();
9840   HasRecMap.clear();
9841 
9842   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9843   // that a loop had multiple computable exits.
9844   for (auto &BTCI : BackedgeTakenCounts)
9845     BTCI.second.clear();
9846   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9847     BTCI.second.clear();
9848 
9849   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9850   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9851   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9852 }
9853 
9854 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9855   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9856 }
9857 
9858 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9859                           const Loop *L) {
9860   // Print all inner loops first
9861   for (Loop *I : *L)
9862     PrintLoopInfo(OS, SE, I);
9863 
9864   OS << "Loop ";
9865   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9866   OS << ": ";
9867 
9868   SmallVector<BasicBlock *, 8> ExitBlocks;
9869   L->getExitBlocks(ExitBlocks);
9870   if (ExitBlocks.size() != 1)
9871     OS << "<multiple exits> ";
9872 
9873   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9874     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9875   } else {
9876     OS << "Unpredictable backedge-taken count. ";
9877   }
9878 
9879   OS << "\n"
9880         "Loop ";
9881   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9882   OS << ": ";
9883 
9884   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9885     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9886     if (SE->isBackedgeTakenCountMaxOrZero(L))
9887       OS << ", actual taken count either this or zero.";
9888   } else {
9889     OS << "Unpredictable max backedge-taken count. ";
9890   }
9891 
9892   OS << "\n"
9893         "Loop ";
9894   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9895   OS << ": ";
9896 
9897   SCEVUnionPredicate Pred;
9898   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9899   if (!isa<SCEVCouldNotCompute>(PBT)) {
9900     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9901     OS << " Predicates:\n";
9902     Pred.print(OS, 4);
9903   } else {
9904     OS << "Unpredictable predicated backedge-taken count. ";
9905   }
9906   OS << "\n";
9907 
9908   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9909     OS << "Loop ";
9910     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9911     OS << ": ";
9912     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
9913   }
9914 }
9915 
9916 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9917   switch (LD) {
9918   case ScalarEvolution::LoopVariant:
9919     return "Variant";
9920   case ScalarEvolution::LoopInvariant:
9921     return "Invariant";
9922   case ScalarEvolution::LoopComputable:
9923     return "Computable";
9924   }
9925   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9926 }
9927 
9928 void ScalarEvolution::print(raw_ostream &OS) const {
9929   // ScalarEvolution's implementation of the print method is to print
9930   // out SCEV values of all instructions that are interesting. Doing
9931   // this potentially causes it to create new SCEV objects though,
9932   // which technically conflicts with the const qualifier. This isn't
9933   // observable from outside the class though, so casting away the
9934   // const isn't dangerous.
9935   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9936 
9937   OS << "Classifying expressions for: ";
9938   F.printAsOperand(OS, /*PrintType=*/false);
9939   OS << "\n";
9940   for (Instruction &I : instructions(F))
9941     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9942       OS << I << '\n';
9943       OS << "  -->  ";
9944       const SCEV *SV = SE.getSCEV(&I);
9945       SV->print(OS);
9946       if (!isa<SCEVCouldNotCompute>(SV)) {
9947         OS << " U: ";
9948         SE.getUnsignedRange(SV).print(OS);
9949         OS << " S: ";
9950         SE.getSignedRange(SV).print(OS);
9951       }
9952 
9953       const Loop *L = LI.getLoopFor(I.getParent());
9954 
9955       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9956       if (AtUse != SV) {
9957         OS << "  -->  ";
9958         AtUse->print(OS);
9959         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9960           OS << " U: ";
9961           SE.getUnsignedRange(AtUse).print(OS);
9962           OS << " S: ";
9963           SE.getSignedRange(AtUse).print(OS);
9964         }
9965       }
9966 
9967       if (L) {
9968         OS << "\t\t" "Exits: ";
9969         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9970         if (!SE.isLoopInvariant(ExitValue, L)) {
9971           OS << "<<Unknown>>";
9972         } else {
9973           OS << *ExitValue;
9974         }
9975 
9976         bool First = true;
9977         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9978           if (First) {
9979             OS << "\t\t" "LoopDispositions: { ";
9980             First = false;
9981           } else {
9982             OS << ", ";
9983           }
9984 
9985           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9986           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9987         }
9988 
9989         for (auto *InnerL : depth_first(L)) {
9990           if (InnerL == L)
9991             continue;
9992           if (First) {
9993             OS << "\t\t" "LoopDispositions: { ";
9994             First = false;
9995           } else {
9996             OS << ", ";
9997           }
9998 
9999           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10000           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10001         }
10002 
10003         OS << " }";
10004       }
10005 
10006       OS << "\n";
10007     }
10008 
10009   OS << "Determining loop execution counts for: ";
10010   F.printAsOperand(OS, /*PrintType=*/false);
10011   OS << "\n";
10012   for (Loop *I : LI)
10013     PrintLoopInfo(OS, &SE, I);
10014 }
10015 
10016 ScalarEvolution::LoopDisposition
10017 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10018   auto &Values = LoopDispositions[S];
10019   for (auto &V : Values) {
10020     if (V.getPointer() == L)
10021       return V.getInt();
10022   }
10023   Values.emplace_back(L, LoopVariant);
10024   LoopDisposition D = computeLoopDisposition(S, L);
10025   auto &Values2 = LoopDispositions[S];
10026   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10027     if (V.getPointer() == L) {
10028       V.setInt(D);
10029       break;
10030     }
10031   }
10032   return D;
10033 }
10034 
10035 ScalarEvolution::LoopDisposition
10036 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10037   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10038   case scConstant:
10039     return LoopInvariant;
10040   case scTruncate:
10041   case scZeroExtend:
10042   case scSignExtend:
10043     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10044   case scAddRecExpr: {
10045     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10046 
10047     // If L is the addrec's loop, it's computable.
10048     if (AR->getLoop() == L)
10049       return LoopComputable;
10050 
10051     // Add recurrences are never invariant in the function-body (null loop).
10052     if (!L)
10053       return LoopVariant;
10054 
10055     // This recurrence is variant w.r.t. L if L contains AR's loop.
10056     if (L->contains(AR->getLoop()))
10057       return LoopVariant;
10058 
10059     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10060     if (AR->getLoop()->contains(L))
10061       return LoopInvariant;
10062 
10063     // This recurrence is variant w.r.t. L if any of its operands
10064     // are variant.
10065     for (auto *Op : AR->operands())
10066       if (!isLoopInvariant(Op, L))
10067         return LoopVariant;
10068 
10069     // Otherwise it's loop-invariant.
10070     return LoopInvariant;
10071   }
10072   case scAddExpr:
10073   case scMulExpr:
10074   case scUMaxExpr:
10075   case scSMaxExpr: {
10076     bool HasVarying = false;
10077     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10078       LoopDisposition D = getLoopDisposition(Op, L);
10079       if (D == LoopVariant)
10080         return LoopVariant;
10081       if (D == LoopComputable)
10082         HasVarying = true;
10083     }
10084     return HasVarying ? LoopComputable : LoopInvariant;
10085   }
10086   case scUDivExpr: {
10087     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10088     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10089     if (LD == LoopVariant)
10090       return LoopVariant;
10091     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10092     if (RD == LoopVariant)
10093       return LoopVariant;
10094     return (LD == LoopInvariant && RD == LoopInvariant) ?
10095            LoopInvariant : LoopComputable;
10096   }
10097   case scUnknown:
10098     // All non-instruction values are loop invariant.  All instructions are loop
10099     // invariant if they are not contained in the specified loop.
10100     // Instructions are never considered invariant in the function body
10101     // (null loop) because they are defined within the "loop".
10102     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10103       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10104     return LoopInvariant;
10105   case scCouldNotCompute:
10106     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10107   }
10108   llvm_unreachable("Unknown SCEV kind!");
10109 }
10110 
10111 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10112   return getLoopDisposition(S, L) == LoopInvariant;
10113 }
10114 
10115 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10116   return getLoopDisposition(S, L) == LoopComputable;
10117 }
10118 
10119 ScalarEvolution::BlockDisposition
10120 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10121   auto &Values = BlockDispositions[S];
10122   for (auto &V : Values) {
10123     if (V.getPointer() == BB)
10124       return V.getInt();
10125   }
10126   Values.emplace_back(BB, DoesNotDominateBlock);
10127   BlockDisposition D = computeBlockDisposition(S, BB);
10128   auto &Values2 = BlockDispositions[S];
10129   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10130     if (V.getPointer() == BB) {
10131       V.setInt(D);
10132       break;
10133     }
10134   }
10135   return D;
10136 }
10137 
10138 ScalarEvolution::BlockDisposition
10139 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10140   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10141   case scConstant:
10142     return ProperlyDominatesBlock;
10143   case scTruncate:
10144   case scZeroExtend:
10145   case scSignExtend:
10146     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10147   case scAddRecExpr: {
10148     // This uses a "dominates" query instead of "properly dominates" query
10149     // to test for proper dominance too, because the instruction which
10150     // produces the addrec's value is a PHI, and a PHI effectively properly
10151     // dominates its entire containing block.
10152     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10153     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10154       return DoesNotDominateBlock;
10155 
10156     // Fall through into SCEVNAryExpr handling.
10157     LLVM_FALLTHROUGH;
10158   }
10159   case scAddExpr:
10160   case scMulExpr:
10161   case scUMaxExpr:
10162   case scSMaxExpr: {
10163     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10164     bool Proper = true;
10165     for (const SCEV *NAryOp : NAry->operands()) {
10166       BlockDisposition D = getBlockDisposition(NAryOp, BB);
10167       if (D == DoesNotDominateBlock)
10168         return DoesNotDominateBlock;
10169       if (D == DominatesBlock)
10170         Proper = false;
10171     }
10172     return Proper ? ProperlyDominatesBlock : DominatesBlock;
10173   }
10174   case scUDivExpr: {
10175     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10176     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10177     BlockDisposition LD = getBlockDisposition(LHS, BB);
10178     if (LD == DoesNotDominateBlock)
10179       return DoesNotDominateBlock;
10180     BlockDisposition RD = getBlockDisposition(RHS, BB);
10181     if (RD == DoesNotDominateBlock)
10182       return DoesNotDominateBlock;
10183     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10184       ProperlyDominatesBlock : DominatesBlock;
10185   }
10186   case scUnknown:
10187     if (Instruction *I =
10188           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10189       if (I->getParent() == BB)
10190         return DominatesBlock;
10191       if (DT.properlyDominates(I->getParent(), BB))
10192         return ProperlyDominatesBlock;
10193       return DoesNotDominateBlock;
10194     }
10195     return ProperlyDominatesBlock;
10196   case scCouldNotCompute:
10197     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10198   }
10199   llvm_unreachable("Unknown SCEV kind!");
10200 }
10201 
10202 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10203   return getBlockDisposition(S, BB) >= DominatesBlock;
10204 }
10205 
10206 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10207   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10208 }
10209 
10210 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10211   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10212 }
10213 
10214 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10215   ValuesAtScopes.erase(S);
10216   LoopDispositions.erase(S);
10217   BlockDispositions.erase(S);
10218   UnsignedRanges.erase(S);
10219   SignedRanges.erase(S);
10220   ExprValueMap.erase(S);
10221   HasRecMap.erase(S);
10222   MinTrailingZerosCache.erase(S);
10223 
10224   auto RemoveSCEVFromBackedgeMap =
10225       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10226         for (auto I = Map.begin(), E = Map.end(); I != E;) {
10227           BackedgeTakenInfo &BEInfo = I->second;
10228           if (BEInfo.hasOperand(S, this)) {
10229             BEInfo.clear();
10230             Map.erase(I++);
10231           } else
10232             ++I;
10233         }
10234       };
10235 
10236   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10237   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10238 }
10239 
10240 typedef DenseMap<const Loop *, std::string> VerifyMap;
10241 
10242 /// replaceSubString - Replaces all occurrences of From in Str with To.
10243 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
10244   size_t Pos = 0;
10245   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
10246     Str.replace(Pos, From.size(), To.data(), To.size());
10247     Pos += To.size();
10248   }
10249 }
10250 
10251 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
10252 static void
10253 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
10254   std::string &S = Map[L];
10255   if (S.empty()) {
10256     raw_string_ostream OS(S);
10257     SE.getBackedgeTakenCount(L)->print(OS);
10258 
10259     // false and 0 are semantically equivalent. This can happen in dead loops.
10260     replaceSubString(OS.str(), "false", "0");
10261     // Remove wrap flags, their use in SCEV is highly fragile.
10262     // FIXME: Remove this when SCEV gets smarter about them.
10263     replaceSubString(OS.str(), "<nw>", "");
10264     replaceSubString(OS.str(), "<nsw>", "");
10265     replaceSubString(OS.str(), "<nuw>", "");
10266   }
10267 
10268   for (auto *R : reverse(*L))
10269     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
10270 }
10271 
10272 void ScalarEvolution::verify() const {
10273   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10274 
10275   // Gather stringified backedge taken counts for all loops using SCEV's caches.
10276   // FIXME: It would be much better to store actual values instead of strings,
10277   //        but SCEV pointers will change if we drop the caches.
10278   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
10279   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10280     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10281 
10282   // Gather stringified backedge taken counts for all loops using a fresh
10283   // ScalarEvolution object.
10284   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10285   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10286     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10287 
10288   // Now compare whether they're the same with and without caches. This allows
10289   // verifying that no pass changed the cache.
10290   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10291          "New loops suddenly appeared!");
10292 
10293   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10294                            OldE = BackedgeDumpsOld.end(),
10295                            NewI = BackedgeDumpsNew.begin();
10296        OldI != OldE; ++OldI, ++NewI) {
10297     assert(OldI->first == NewI->first && "Loop order changed!");
10298 
10299     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10300     // changes.
10301     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10302     // means that a pass is buggy or SCEV has to learn a new pattern but is
10303     // usually not harmful.
10304     if (OldI->second != NewI->second &&
10305         OldI->second.find("undef") == std::string::npos &&
10306         NewI->second.find("undef") == std::string::npos &&
10307         OldI->second != "***COULDNOTCOMPUTE***" &&
10308         NewI->second != "***COULDNOTCOMPUTE***") {
10309       dbgs() << "SCEVValidator: SCEV for loop '"
10310              << OldI->first->getHeader()->getName()
10311              << "' changed from '" << OldI->second
10312              << "' to '" << NewI->second << "'!\n";
10313       std::abort();
10314     }
10315   }
10316 
10317   // TODO: Verify more things.
10318 }
10319 
10320 bool ScalarEvolution::invalidate(
10321     Function &F, const PreservedAnalyses &PA,
10322     FunctionAnalysisManager::Invalidator &Inv) {
10323   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10324   // of its dependencies is invalidated.
10325   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10326   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10327          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10328          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10329          Inv.invalidate<LoopAnalysis>(F, PA);
10330 }
10331 
10332 AnalysisKey ScalarEvolutionAnalysis::Key;
10333 
10334 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10335                                              FunctionAnalysisManager &AM) {
10336   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10337                          AM.getResult<AssumptionAnalysis>(F),
10338                          AM.getResult<DominatorTreeAnalysis>(F),
10339                          AM.getResult<LoopAnalysis>(F));
10340 }
10341 
10342 PreservedAnalyses
10343 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10344   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10345   return PreservedAnalyses::all();
10346 }
10347 
10348 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10349                       "Scalar Evolution Analysis", false, true)
10350 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10351 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10352 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10353 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10354 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10355                     "Scalar Evolution Analysis", false, true)
10356 char ScalarEvolutionWrapperPass::ID = 0;
10357 
10358 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10359   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10360 }
10361 
10362 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10363   SE.reset(new ScalarEvolution(
10364       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10365       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10366       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10367       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10368   return false;
10369 }
10370 
10371 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10372 
10373 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10374   SE->print(OS);
10375 }
10376 
10377 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10378   if (!VerifySCEV)
10379     return;
10380 
10381   SE->verify();
10382 }
10383 
10384 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10385   AU.setPreservesAll();
10386   AU.addRequiredTransitive<AssumptionCacheTracker>();
10387   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10388   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10389   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10390 }
10391 
10392 const SCEVPredicate *
10393 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10394                                    const SCEVConstant *RHS) {
10395   FoldingSetNodeID ID;
10396   // Unique this node based on the arguments
10397   ID.AddInteger(SCEVPredicate::P_Equal);
10398   ID.AddPointer(LHS);
10399   ID.AddPointer(RHS);
10400   void *IP = nullptr;
10401   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10402     return S;
10403   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10404       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10405   UniquePreds.InsertNode(Eq, IP);
10406   return Eq;
10407 }
10408 
10409 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10410     const SCEVAddRecExpr *AR,
10411     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10412   FoldingSetNodeID ID;
10413   // Unique this node based on the arguments
10414   ID.AddInteger(SCEVPredicate::P_Wrap);
10415   ID.AddPointer(AR);
10416   ID.AddInteger(AddedFlags);
10417   void *IP = nullptr;
10418   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10419     return S;
10420   auto *OF = new (SCEVAllocator)
10421       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10422   UniquePreds.InsertNode(OF, IP);
10423   return OF;
10424 }
10425 
10426 namespace {
10427 
10428 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10429 public:
10430   /// Rewrites \p S in the context of a loop L and the SCEV predication
10431   /// infrastructure.
10432   ///
10433   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10434   /// equivalences present in \p Pred.
10435   ///
10436   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10437   /// \p NewPreds such that the result will be an AddRecExpr.
10438   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10439                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10440                              SCEVUnionPredicate *Pred) {
10441     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10442     return Rewriter.visit(S);
10443   }
10444 
10445   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10446                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10447                         SCEVUnionPredicate *Pred)
10448       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10449 
10450   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10451     if (Pred) {
10452       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10453       for (auto *Pred : ExprPreds)
10454         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10455           if (IPred->getLHS() == Expr)
10456             return IPred->getRHS();
10457     }
10458 
10459     return Expr;
10460   }
10461 
10462   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10463     const SCEV *Operand = visit(Expr->getOperand());
10464     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10465     if (AR && AR->getLoop() == L && AR->isAffine()) {
10466       // This couldn't be folded because the operand didn't have the nuw
10467       // flag. Add the nusw flag as an assumption that we could make.
10468       const SCEV *Step = AR->getStepRecurrence(SE);
10469       Type *Ty = Expr->getType();
10470       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10471         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10472                                 SE.getSignExtendExpr(Step, Ty), L,
10473                                 AR->getNoWrapFlags());
10474     }
10475     return SE.getZeroExtendExpr(Operand, Expr->getType());
10476   }
10477 
10478   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10479     const SCEV *Operand = visit(Expr->getOperand());
10480     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10481     if (AR && AR->getLoop() == L && AR->isAffine()) {
10482       // This couldn't be folded because the operand didn't have the nsw
10483       // flag. Add the nssw flag as an assumption that we could make.
10484       const SCEV *Step = AR->getStepRecurrence(SE);
10485       Type *Ty = Expr->getType();
10486       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10487         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10488                                 SE.getSignExtendExpr(Step, Ty), L,
10489                                 AR->getNoWrapFlags());
10490     }
10491     return SE.getSignExtendExpr(Operand, Expr->getType());
10492   }
10493 
10494 private:
10495   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10496                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10497     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10498     if (!NewPreds) {
10499       // Check if we've already made this assumption.
10500       return Pred && Pred->implies(A);
10501     }
10502     NewPreds->insert(A);
10503     return true;
10504   }
10505 
10506   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10507   SCEVUnionPredicate *Pred;
10508   const Loop *L;
10509 };
10510 } // end anonymous namespace
10511 
10512 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10513                                                    SCEVUnionPredicate &Preds) {
10514   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10515 }
10516 
10517 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10518     const SCEV *S, const Loop *L,
10519     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10520 
10521   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10522   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10523   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10524 
10525   if (!AddRec)
10526     return nullptr;
10527 
10528   // Since the transformation was successful, we can now transfer the SCEV
10529   // predicates.
10530   for (auto *P : TransformPreds)
10531     Preds.insert(P);
10532 
10533   return AddRec;
10534 }
10535 
10536 /// SCEV predicates
10537 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10538                              SCEVPredicateKind Kind)
10539     : FastID(ID), Kind(Kind) {}
10540 
10541 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10542                                        const SCEVUnknown *LHS,
10543                                        const SCEVConstant *RHS)
10544     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10545 
10546 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10547   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10548 
10549   if (!Op)
10550     return false;
10551 
10552   return Op->LHS == LHS && Op->RHS == RHS;
10553 }
10554 
10555 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10556 
10557 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10558 
10559 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10560   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10561 }
10562 
10563 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10564                                      const SCEVAddRecExpr *AR,
10565                                      IncrementWrapFlags Flags)
10566     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10567 
10568 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10569 
10570 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10571   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10572 
10573   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10574 }
10575 
10576 bool SCEVWrapPredicate::isAlwaysTrue() const {
10577   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10578   IncrementWrapFlags IFlags = Flags;
10579 
10580   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10581     IFlags = clearFlags(IFlags, IncrementNSSW);
10582 
10583   return IFlags == IncrementAnyWrap;
10584 }
10585 
10586 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10587   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10588   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10589     OS << "<nusw>";
10590   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10591     OS << "<nssw>";
10592   OS << "\n";
10593 }
10594 
10595 SCEVWrapPredicate::IncrementWrapFlags
10596 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10597                                    ScalarEvolution &SE) {
10598   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10599   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10600 
10601   // We can safely transfer the NSW flag as NSSW.
10602   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10603     ImpliedFlags = IncrementNSSW;
10604 
10605   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10606     // If the increment is positive, the SCEV NUW flag will also imply the
10607     // WrapPredicate NUSW flag.
10608     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10609       if (Step->getValue()->getValue().isNonNegative())
10610         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10611   }
10612 
10613   return ImpliedFlags;
10614 }
10615 
10616 /// Union predicates don't get cached so create a dummy set ID for it.
10617 SCEVUnionPredicate::SCEVUnionPredicate()
10618     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10619 
10620 bool SCEVUnionPredicate::isAlwaysTrue() const {
10621   return all_of(Preds,
10622                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10623 }
10624 
10625 ArrayRef<const SCEVPredicate *>
10626 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10627   auto I = SCEVToPreds.find(Expr);
10628   if (I == SCEVToPreds.end())
10629     return ArrayRef<const SCEVPredicate *>();
10630   return I->second;
10631 }
10632 
10633 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10634   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10635     return all_of(Set->Preds,
10636                   [this](const SCEVPredicate *I) { return this->implies(I); });
10637 
10638   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10639   if (ScevPredsIt == SCEVToPreds.end())
10640     return false;
10641   auto &SCEVPreds = ScevPredsIt->second;
10642 
10643   return any_of(SCEVPreds,
10644                 [N](const SCEVPredicate *I) { return I->implies(N); });
10645 }
10646 
10647 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10648 
10649 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10650   for (auto Pred : Preds)
10651     Pred->print(OS, Depth);
10652 }
10653 
10654 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10655   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10656     for (auto Pred : Set->Preds)
10657       add(Pred);
10658     return;
10659   }
10660 
10661   if (implies(N))
10662     return;
10663 
10664   const SCEV *Key = N->getExpr();
10665   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10666                 " associated expression!");
10667 
10668   SCEVToPreds[Key].push_back(N);
10669   Preds.push_back(N);
10670 }
10671 
10672 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10673                                                      Loop &L)
10674     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10675 
10676 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10677   const SCEV *Expr = SE.getSCEV(V);
10678   RewriteEntry &Entry = RewriteMap[Expr];
10679 
10680   // If we already have an entry and the version matches, return it.
10681   if (Entry.second && Generation == Entry.first)
10682     return Entry.second;
10683 
10684   // We found an entry but it's stale. Rewrite the stale entry
10685   // according to the current predicate.
10686   if (Entry.second)
10687     Expr = Entry.second;
10688 
10689   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10690   Entry = {Generation, NewSCEV};
10691 
10692   return NewSCEV;
10693 }
10694 
10695 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10696   if (!BackedgeCount) {
10697     SCEVUnionPredicate BackedgePred;
10698     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10699     addPredicate(BackedgePred);
10700   }
10701   return BackedgeCount;
10702 }
10703 
10704 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10705   if (Preds.implies(&Pred))
10706     return;
10707   Preds.add(&Pred);
10708   updateGeneration();
10709 }
10710 
10711 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10712   return Preds;
10713 }
10714 
10715 void PredicatedScalarEvolution::updateGeneration() {
10716   // If the generation number wrapped recompute everything.
10717   if (++Generation == 0) {
10718     for (auto &II : RewriteMap) {
10719       const SCEV *Rewritten = II.second.second;
10720       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10721     }
10722   }
10723 }
10724 
10725 void PredicatedScalarEvolution::setNoOverflow(
10726     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10727   const SCEV *Expr = getSCEV(V);
10728   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10729 
10730   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10731 
10732   // Clear the statically implied flags.
10733   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10734   addPredicate(*SE.getWrapPredicate(AR, Flags));
10735 
10736   auto II = FlagsMap.insert({V, Flags});
10737   if (!II.second)
10738     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10739 }
10740 
10741 bool PredicatedScalarEvolution::hasNoOverflow(
10742     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10743   const SCEV *Expr = getSCEV(V);
10744   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10745 
10746   Flags = SCEVWrapPredicate::clearFlags(
10747       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10748 
10749   auto II = FlagsMap.find(V);
10750 
10751   if (II != FlagsMap.end())
10752     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10753 
10754   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10755 }
10756 
10757 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10758   const SCEV *Expr = this->getSCEV(V);
10759   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10760   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10761 
10762   if (!New)
10763     return nullptr;
10764 
10765   for (auto *P : NewPreds)
10766     Preds.add(P);
10767 
10768   updateGeneration();
10769   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10770   return New;
10771 }
10772 
10773 PredicatedScalarEvolution::PredicatedScalarEvolution(
10774     const PredicatedScalarEvolution &Init)
10775     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10776       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10777   for (const auto &I : Init.FlagsMap)
10778     FlagsMap.insert(I);
10779 }
10780 
10781 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10782   // For each block.
10783   for (auto *BB : L.getBlocks())
10784     for (auto &I : *BB) {
10785       if (!SE.isSCEVable(I.getType()))
10786         continue;
10787 
10788       auto *Expr = SE.getSCEV(&I);
10789       auto II = RewriteMap.find(Expr);
10790 
10791       if (II == RewriteMap.end())
10792         continue;
10793 
10794       // Don't print things that are not interesting.
10795       if (II->second.second == Expr)
10796         continue;
10797 
10798       OS.indent(Depth) << "[PSE]" << I << ":\n";
10799       OS.indent(Depth + 2) << *Expr << "\n";
10800       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10801     }
10802 }
10803