1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/Pass.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Compiler.h"
118 #include "llvm/Support/Debug.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/KnownBits.h"
121 #include "llvm/Support/SaveAndRestore.h"
122 #include "llvm/Support/raw_ostream.h"
123 #include <algorithm>
124 #include <cassert>
125 #include <climits>
126 #include <cstddef>
127 #include <cstdint>
128 #include <cstdlib>
129 #include <map>
130 #include <memory>
131 #include <tuple>
132 #include <utility>
133 #include <vector>
134 
135 using namespace llvm;
136 
137 #define DEBUG_TYPE "scalar-evolution"
138 
139 STATISTIC(NumArrayLenItCounts,
140           "Number of trip counts computed with array length");
141 STATISTIC(NumTripCountsComputed,
142           "Number of loops with predictable loop counts");
143 STATISTIC(NumTripCountsNotComputed,
144           "Number of loops without predictable loop counts");
145 STATISTIC(NumBruteForceTripCountsComputed,
146           "Number of loops with trip counts computed by force");
147 
148 static cl::opt<unsigned>
149 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
150                         cl::desc("Maximum number of iterations SCEV will "
151                                  "symbolically execute a constant "
152                                  "derived loop"),
153                         cl::init(100));
154 
155 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
156 static cl::opt<bool> VerifySCEV(
157     "verify-scev", cl::Hidden,
158     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
159 static cl::opt<bool>
160     VerifySCEVMap("verify-scev-maps", cl::Hidden,
161                   cl::desc("Verify no dangling value in ScalarEvolution's "
162                            "ExprValueMap (slow)"));
163 
164 static cl::opt<unsigned> MulOpsInlineThreshold(
165     "scev-mulops-inline-threshold", cl::Hidden,
166     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
167     cl::init(32));
168 
169 static cl::opt<unsigned> AddOpsInlineThreshold(
170     "scev-addops-inline-threshold", cl::Hidden,
171     cl::desc("Threshold for inlining addition operands into a SCEV"),
172     cl::init(500));
173 
174 static cl::opt<unsigned> MaxSCEVCompareDepth(
175     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
176     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
177     cl::init(32));
178 
179 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
180     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
181     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
182     cl::init(2));
183 
184 static cl::opt<unsigned> MaxValueCompareDepth(
185     "scalar-evolution-max-value-compare-depth", cl::Hidden,
186     cl::desc("Maximum depth of recursive value complexity comparisons"),
187     cl::init(2));
188 
189 static cl::opt<unsigned>
190     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
191                   cl::desc("Maximum depth of recursive arithmetics"),
192                   cl::init(32));
193 
194 static cl::opt<unsigned> MaxConstantEvolvingDepth(
195     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
196     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
197 
198 static cl::opt<unsigned>
199     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
200                 cl::desc("Maximum depth of recursive SExt/ZExt"),
201                 cl::init(8));
202 
203 static cl::opt<unsigned>
204     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
205                   cl::desc("Max coefficients in AddRec during evolving"),
206                   cl::init(16));
207 
208 //===----------------------------------------------------------------------===//
209 //                           SCEV class definitions
210 //===----------------------------------------------------------------------===//
211 
212 //===----------------------------------------------------------------------===//
213 // Implementation of the SCEV class.
214 //
215 
216 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
217 LLVM_DUMP_METHOD void SCEV::dump() const {
218   print(dbgs());
219   dbgs() << '\n';
220 }
221 #endif
222 
223 void SCEV::print(raw_ostream &OS) const {
224   switch (static_cast<SCEVTypes>(getSCEVType())) {
225   case scConstant:
226     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
227     return;
228   case scTruncate: {
229     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
230     const SCEV *Op = Trunc->getOperand();
231     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
232        << *Trunc->getType() << ")";
233     return;
234   }
235   case scZeroExtend: {
236     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
237     const SCEV *Op = ZExt->getOperand();
238     OS << "(zext " << *Op->getType() << " " << *Op << " to "
239        << *ZExt->getType() << ")";
240     return;
241   }
242   case scSignExtend: {
243     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
244     const SCEV *Op = SExt->getOperand();
245     OS << "(sext " << *Op->getType() << " " << *Op << " to "
246        << *SExt->getType() << ")";
247     return;
248   }
249   case scAddRecExpr: {
250     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
251     OS << "{" << *AR->getOperand(0);
252     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
253       OS << ",+," << *AR->getOperand(i);
254     OS << "}<";
255     if (AR->hasNoUnsignedWrap())
256       OS << "nuw><";
257     if (AR->hasNoSignedWrap())
258       OS << "nsw><";
259     if (AR->hasNoSelfWrap() &&
260         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
261       OS << "nw><";
262     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
263     OS << ">";
264     return;
265   }
266   case scAddExpr:
267   case scMulExpr:
268   case scUMaxExpr:
269   case scSMaxExpr: {
270     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
271     const char *OpStr = nullptr;
272     switch (NAry->getSCEVType()) {
273     case scAddExpr: OpStr = " + "; break;
274     case scMulExpr: OpStr = " * "; break;
275     case scUMaxExpr: OpStr = " umax "; break;
276     case scSMaxExpr: OpStr = " smax "; break;
277     }
278     OS << "(";
279     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
280          I != E; ++I) {
281       OS << **I;
282       if (std::next(I) != E)
283         OS << OpStr;
284     }
285     OS << ")";
286     switch (NAry->getSCEVType()) {
287     case scAddExpr:
288     case scMulExpr:
289       if (NAry->hasNoUnsignedWrap())
290         OS << "<nuw>";
291       if (NAry->hasNoSignedWrap())
292         OS << "<nsw>";
293     }
294     return;
295   }
296   case scUDivExpr: {
297     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
298     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
299     return;
300   }
301   case scUnknown: {
302     const SCEVUnknown *U = cast<SCEVUnknown>(this);
303     Type *AllocTy;
304     if (U->isSizeOf(AllocTy)) {
305       OS << "sizeof(" << *AllocTy << ")";
306       return;
307     }
308     if (U->isAlignOf(AllocTy)) {
309       OS << "alignof(" << *AllocTy << ")";
310       return;
311     }
312 
313     Type *CTy;
314     Constant *FieldNo;
315     if (U->isOffsetOf(CTy, FieldNo)) {
316       OS << "offsetof(" << *CTy << ", ";
317       FieldNo->printAsOperand(OS, false);
318       OS << ")";
319       return;
320     }
321 
322     // Otherwise just print it normally.
323     U->getValue()->printAsOperand(OS, false);
324     return;
325   }
326   case scCouldNotCompute:
327     OS << "***COULDNOTCOMPUTE***";
328     return;
329   }
330   llvm_unreachable("Unknown SCEV kind!");
331 }
332 
333 Type *SCEV::getType() const {
334   switch (static_cast<SCEVTypes>(getSCEVType())) {
335   case scConstant:
336     return cast<SCEVConstant>(this)->getType();
337   case scTruncate:
338   case scZeroExtend:
339   case scSignExtend:
340     return cast<SCEVCastExpr>(this)->getType();
341   case scAddRecExpr:
342   case scMulExpr:
343   case scUMaxExpr:
344   case scSMaxExpr:
345     return cast<SCEVNAryExpr>(this)->getType();
346   case scAddExpr:
347     return cast<SCEVAddExpr>(this)->getType();
348   case scUDivExpr:
349     return cast<SCEVUDivExpr>(this)->getType();
350   case scUnknown:
351     return cast<SCEVUnknown>(this)->getType();
352   case scCouldNotCompute:
353     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
354   }
355   llvm_unreachable("Unknown SCEV kind!");
356 }
357 
358 bool SCEV::isZero() const {
359   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
360     return SC->getValue()->isZero();
361   return false;
362 }
363 
364 bool SCEV::isOne() const {
365   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
366     return SC->getValue()->isOne();
367   return false;
368 }
369 
370 bool SCEV::isAllOnesValue() const {
371   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
372     return SC->getValue()->isMinusOne();
373   return false;
374 }
375 
376 bool SCEV::isNonConstantNegative() const {
377   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
378   if (!Mul) return false;
379 
380   // If there is a constant factor, it will be first.
381   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
382   if (!SC) return false;
383 
384   // Return true if the value is negative, this matches things like (-42 * V).
385   return SC->getAPInt().isNegative();
386 }
387 
388 SCEVCouldNotCompute::SCEVCouldNotCompute() :
389   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
390 
391 bool SCEVCouldNotCompute::classof(const SCEV *S) {
392   return S->getSCEVType() == scCouldNotCompute;
393 }
394 
395 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
396   FoldingSetNodeID ID;
397   ID.AddInteger(scConstant);
398   ID.AddPointer(V);
399   void *IP = nullptr;
400   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
401   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
402   UniqueSCEVs.InsertNode(S, IP);
403   return S;
404 }
405 
406 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
407   return getConstant(ConstantInt::get(getContext(), Val));
408 }
409 
410 const SCEV *
411 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
412   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
413   return getConstant(ConstantInt::get(ITy, V, isSigned));
414 }
415 
416 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
417                            unsigned SCEVTy, const SCEV *op, Type *ty)
418   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
419 
420 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
421                                    const SCEV *op, Type *ty)
422   : SCEVCastExpr(ID, scTruncate, op, ty) {
423   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
424          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
425          "Cannot truncate non-integer value!");
426 }
427 
428 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429                                        const SCEV *op, Type *ty)
430   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
432          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
433          "Cannot zero extend non-integer value!");
434 }
435 
436 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
437                                        const SCEV *op, Type *ty)
438   : SCEVCastExpr(ID, scSignExtend, op, ty) {
439   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
440          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
441          "Cannot sign extend non-integer value!");
442 }
443 
444 void SCEVUnknown::deleted() {
445   // Clear this SCEVUnknown from various maps.
446   SE->forgetMemoizedResults(this);
447 
448   // Remove this SCEVUnknown from the uniquing map.
449   SE->UniqueSCEVs.RemoveNode(this);
450 
451   // Release the value.
452   setValPtr(nullptr);
453 }
454 
455 void SCEVUnknown::allUsesReplacedWith(Value *New) {
456   // Remove this SCEVUnknown from the uniquing map.
457   SE->UniqueSCEVs.RemoveNode(this);
458 
459   // Update this SCEVUnknown to point to the new value. This is needed
460   // because there may still be outstanding SCEVs which still point to
461   // this SCEVUnknown.
462   setValPtr(New);
463 }
464 
465 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
466   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
467     if (VCE->getOpcode() == Instruction::PtrToInt)
468       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
469         if (CE->getOpcode() == Instruction::GetElementPtr &&
470             CE->getOperand(0)->isNullValue() &&
471             CE->getNumOperands() == 2)
472           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
473             if (CI->isOne()) {
474               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
475                                  ->getElementType();
476               return true;
477             }
478 
479   return false;
480 }
481 
482 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
483   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
484     if (VCE->getOpcode() == Instruction::PtrToInt)
485       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
486         if (CE->getOpcode() == Instruction::GetElementPtr &&
487             CE->getOperand(0)->isNullValue()) {
488           Type *Ty =
489             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
490           if (StructType *STy = dyn_cast<StructType>(Ty))
491             if (!STy->isPacked() &&
492                 CE->getNumOperands() == 3 &&
493                 CE->getOperand(1)->isNullValue()) {
494               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
495                 if (CI->isOne() &&
496                     STy->getNumElements() == 2 &&
497                     STy->getElementType(0)->isIntegerTy(1)) {
498                   AllocTy = STy->getElementType(1);
499                   return true;
500                 }
501             }
502         }
503 
504   return false;
505 }
506 
507 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
508   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
509     if (VCE->getOpcode() == Instruction::PtrToInt)
510       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
511         if (CE->getOpcode() == Instruction::GetElementPtr &&
512             CE->getNumOperands() == 3 &&
513             CE->getOperand(0)->isNullValue() &&
514             CE->getOperand(1)->isNullValue()) {
515           Type *Ty =
516             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
517           // Ignore vector types here so that ScalarEvolutionExpander doesn't
518           // emit getelementptrs that index into vectors.
519           if (Ty->isStructTy() || Ty->isArrayTy()) {
520             CTy = Ty;
521             FieldNo = CE->getOperand(2);
522             return true;
523           }
524         }
525 
526   return false;
527 }
528 
529 //===----------------------------------------------------------------------===//
530 //                               SCEV Utilities
531 //===----------------------------------------------------------------------===//
532 
533 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
534 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
535 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
536 /// have been previously deemed to be "equally complex" by this routine.  It is
537 /// intended to avoid exponential time complexity in cases like:
538 ///
539 ///   %a = f(%x, %y)
540 ///   %b = f(%a, %a)
541 ///   %c = f(%b, %b)
542 ///
543 ///   %d = f(%x, %y)
544 ///   %e = f(%d, %d)
545 ///   %f = f(%e, %e)
546 ///
547 ///   CompareValueComplexity(%f, %c)
548 ///
549 /// Since we do not continue running this routine on expression trees once we
550 /// have seen unequal values, there is no need to track them in the cache.
551 static int
552 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
553                        const LoopInfo *const LI, Value *LV, Value *RV,
554                        unsigned Depth) {
555   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
556     return 0;
557 
558   // Order pointer values after integer values. This helps SCEVExpander form
559   // GEPs.
560   bool LIsPointer = LV->getType()->isPointerTy(),
561        RIsPointer = RV->getType()->isPointerTy();
562   if (LIsPointer != RIsPointer)
563     return (int)LIsPointer - (int)RIsPointer;
564 
565   // Compare getValueID values.
566   unsigned LID = LV->getValueID(), RID = RV->getValueID();
567   if (LID != RID)
568     return (int)LID - (int)RID;
569 
570   // Sort arguments by their position.
571   if (const auto *LA = dyn_cast<Argument>(LV)) {
572     const auto *RA = cast<Argument>(RV);
573     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
574     return (int)LArgNo - (int)RArgNo;
575   }
576 
577   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
578     const auto *RGV = cast<GlobalValue>(RV);
579 
580     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
581       auto LT = GV->getLinkage();
582       return !(GlobalValue::isPrivateLinkage(LT) ||
583                GlobalValue::isInternalLinkage(LT));
584     };
585 
586     // Use the names to distinguish the two values, but only if the
587     // names are semantically important.
588     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
589       return LGV->getName().compare(RGV->getName());
590   }
591 
592   // For instructions, compare their loop depth, and their operand count.  This
593   // is pretty loose.
594   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
595     const auto *RInst = cast<Instruction>(RV);
596 
597     // Compare loop depths.
598     const BasicBlock *LParent = LInst->getParent(),
599                      *RParent = RInst->getParent();
600     if (LParent != RParent) {
601       unsigned LDepth = LI->getLoopDepth(LParent),
602                RDepth = LI->getLoopDepth(RParent);
603       if (LDepth != RDepth)
604         return (int)LDepth - (int)RDepth;
605     }
606 
607     // Compare the number of operands.
608     unsigned LNumOps = LInst->getNumOperands(),
609              RNumOps = RInst->getNumOperands();
610     if (LNumOps != RNumOps)
611       return (int)LNumOps - (int)RNumOps;
612 
613     for (unsigned Idx : seq(0u, LNumOps)) {
614       int Result =
615           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
616                                  RInst->getOperand(Idx), Depth + 1);
617       if (Result != 0)
618         return Result;
619     }
620   }
621 
622   EqCacheValue.unionSets(LV, RV);
623   return 0;
624 }
625 
626 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
627 // than RHS, respectively. A three-way result allows recursive comparisons to be
628 // more efficient.
629 static int CompareSCEVComplexity(
630     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
631     EquivalenceClasses<const Value *> &EqCacheValue,
632     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
633     DominatorTree &DT, unsigned Depth = 0) {
634   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
635   if (LHS == RHS)
636     return 0;
637 
638   // Primarily, sort the SCEVs by their getSCEVType().
639   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
640   if (LType != RType)
641     return (int)LType - (int)RType;
642 
643   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
644     return 0;
645   // Aside from the getSCEVType() ordering, the particular ordering
646   // isn't very important except that it's beneficial to be consistent,
647   // so that (a + b) and (b + a) don't end up as different expressions.
648   switch (static_cast<SCEVTypes>(LType)) {
649   case scUnknown: {
650     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
651     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
652 
653     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
654                                    RU->getValue(), Depth + 1);
655     if (X == 0)
656       EqCacheSCEV.unionSets(LHS, RHS);
657     return X;
658   }
659 
660   case scConstant: {
661     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
662     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
663 
664     // Compare constant values.
665     const APInt &LA = LC->getAPInt();
666     const APInt &RA = RC->getAPInt();
667     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
668     if (LBitWidth != RBitWidth)
669       return (int)LBitWidth - (int)RBitWidth;
670     return LA.ult(RA) ? -1 : 1;
671   }
672 
673   case scAddRecExpr: {
674     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
675     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
676 
677     // There is always a dominance between two recs that are used by one SCEV,
678     // so we can safely sort recs by loop header dominance. We require such
679     // order in getAddExpr.
680     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
681     if (LLoop != RLoop) {
682       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
683       assert(LHead != RHead && "Two loops share the same header?");
684       if (DT.dominates(LHead, RHead))
685         return 1;
686       else
687         assert(DT.dominates(RHead, LHead) &&
688                "No dominance between recurrences used by one SCEV?");
689       return -1;
690     }
691 
692     // Addrec complexity grows with operand count.
693     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
694     if (LNumOps != RNumOps)
695       return (int)LNumOps - (int)RNumOps;
696 
697     // Compare NoWrap flags.
698     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
699       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
700 
701     // Lexicographically compare.
702     for (unsigned i = 0; i != LNumOps; ++i) {
703       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
704                                     LA->getOperand(i), RA->getOperand(i), DT,
705                                     Depth + 1);
706       if (X != 0)
707         return X;
708     }
709     EqCacheSCEV.unionSets(LHS, RHS);
710     return 0;
711   }
712 
713   case scAddExpr:
714   case scMulExpr:
715   case scSMaxExpr:
716   case scUMaxExpr: {
717     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
718     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
719 
720     // Lexicographically compare n-ary expressions.
721     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
722     if (LNumOps != RNumOps)
723       return (int)LNumOps - (int)RNumOps;
724 
725     // Compare NoWrap flags.
726     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
727       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
728 
729     for (unsigned i = 0; i != LNumOps; ++i) {
730       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
731                                     LC->getOperand(i), RC->getOperand(i), DT,
732                                     Depth + 1);
733       if (X != 0)
734         return X;
735     }
736     EqCacheSCEV.unionSets(LHS, RHS);
737     return 0;
738   }
739 
740   case scUDivExpr: {
741     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
742     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
743 
744     // Lexicographically compare udiv expressions.
745     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
746                                   RC->getLHS(), DT, Depth + 1);
747     if (X != 0)
748       return X;
749     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
750                               RC->getRHS(), DT, Depth + 1);
751     if (X == 0)
752       EqCacheSCEV.unionSets(LHS, RHS);
753     return X;
754   }
755 
756   case scTruncate:
757   case scZeroExtend:
758   case scSignExtend: {
759     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
760     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
761 
762     // Compare cast expressions by operand.
763     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
764                                   LC->getOperand(), RC->getOperand(), DT,
765                                   Depth + 1);
766     if (X == 0)
767       EqCacheSCEV.unionSets(LHS, RHS);
768     return X;
769   }
770 
771   case scCouldNotCompute:
772     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
773   }
774   llvm_unreachable("Unknown SCEV kind!");
775 }
776 
777 /// Given a list of SCEV objects, order them by their complexity, and group
778 /// objects of the same complexity together by value.  When this routine is
779 /// finished, we know that any duplicates in the vector are consecutive and that
780 /// complexity is monotonically increasing.
781 ///
782 /// Note that we go take special precautions to ensure that we get deterministic
783 /// results from this routine.  In other words, we don't want the results of
784 /// this to depend on where the addresses of various SCEV objects happened to
785 /// land in memory.
786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
787                               LoopInfo *LI, DominatorTree &DT) {
788   if (Ops.size() < 2) return;  // Noop
789 
790   EquivalenceClasses<const SCEV *> EqCacheSCEV;
791   EquivalenceClasses<const Value *> EqCacheValue;
792   if (Ops.size() == 2) {
793     // This is the common case, which also happens to be trivially simple.
794     // Special case it.
795     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
796     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
797       std::swap(LHS, RHS);
798     return;
799   }
800 
801   // Do the rough sort by complexity.
802   std::stable_sort(Ops.begin(), Ops.end(),
803                    [&](const SCEV *LHS, const SCEV *RHS) {
804                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
805                                                   LHS, RHS, DT) < 0;
806                    });
807 
808   // Now that we are sorted by complexity, group elements of the same
809   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
810   // be extremely short in practice.  Note that we take this approach because we
811   // do not want to depend on the addresses of the objects we are grouping.
812   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
813     const SCEV *S = Ops[i];
814     unsigned Complexity = S->getSCEVType();
815 
816     // If there are any objects of the same complexity and same value as this
817     // one, group them.
818     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
819       if (Ops[j] == S) { // Found a duplicate.
820         // Move it to immediately after i'th element.
821         std::swap(Ops[i+1], Ops[j]);
822         ++i;   // no need to rescan it.
823         if (i == e-2) return;  // Done!
824       }
825     }
826   }
827 }
828 
829 // Returns the size of the SCEV S.
830 static inline int sizeOfSCEV(const SCEV *S) {
831   struct FindSCEVSize {
832     int Size = 0;
833 
834     FindSCEVSize() = default;
835 
836     bool follow(const SCEV *S) {
837       ++Size;
838       // Keep looking at all operands of S.
839       return true;
840     }
841 
842     bool isDone() const {
843       return false;
844     }
845   };
846 
847   FindSCEVSize F;
848   SCEVTraversal<FindSCEVSize> ST(F);
849   ST.visitAll(S);
850   return F.Size;
851 }
852 
853 namespace {
854 
855 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
856 public:
857   // Computes the Quotient and Remainder of the division of Numerator by
858   // Denominator.
859   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
860                      const SCEV *Denominator, const SCEV **Quotient,
861                      const SCEV **Remainder) {
862     assert(Numerator && Denominator && "Uninitialized SCEV");
863 
864     SCEVDivision D(SE, Numerator, Denominator);
865 
866     // Check for the trivial case here to avoid having to check for it in the
867     // rest of the code.
868     if (Numerator == Denominator) {
869       *Quotient = D.One;
870       *Remainder = D.Zero;
871       return;
872     }
873 
874     if (Numerator->isZero()) {
875       *Quotient = D.Zero;
876       *Remainder = D.Zero;
877       return;
878     }
879 
880     // A simple case when N/1. The quotient is N.
881     if (Denominator->isOne()) {
882       *Quotient = Numerator;
883       *Remainder = D.Zero;
884       return;
885     }
886 
887     // Split the Denominator when it is a product.
888     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
889       const SCEV *Q, *R;
890       *Quotient = Numerator;
891       for (const SCEV *Op : T->operands()) {
892         divide(SE, *Quotient, Op, &Q, &R);
893         *Quotient = Q;
894 
895         // Bail out when the Numerator is not divisible by one of the terms of
896         // the Denominator.
897         if (!R->isZero()) {
898           *Quotient = D.Zero;
899           *Remainder = Numerator;
900           return;
901         }
902       }
903       *Remainder = D.Zero;
904       return;
905     }
906 
907     D.visit(Numerator);
908     *Quotient = D.Quotient;
909     *Remainder = D.Remainder;
910   }
911 
912   // Except in the trivial case described above, we do not know how to divide
913   // Expr by Denominator for the following functions with empty implementation.
914   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
915   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
916   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
917   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
918   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
919   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
920   void visitUnknown(const SCEVUnknown *Numerator) {}
921   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
922 
923   void visitConstant(const SCEVConstant *Numerator) {
924     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
925       APInt NumeratorVal = Numerator->getAPInt();
926       APInt DenominatorVal = D->getAPInt();
927       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
928       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
929 
930       if (NumeratorBW > DenominatorBW)
931         DenominatorVal = DenominatorVal.sext(NumeratorBW);
932       else if (NumeratorBW < DenominatorBW)
933         NumeratorVal = NumeratorVal.sext(DenominatorBW);
934 
935       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
936       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
937       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
938       Quotient = SE.getConstant(QuotientVal);
939       Remainder = SE.getConstant(RemainderVal);
940       return;
941     }
942   }
943 
944   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
945     const SCEV *StartQ, *StartR, *StepQ, *StepR;
946     if (!Numerator->isAffine())
947       return cannotDivide(Numerator);
948     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
949     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
950     // Bail out if the types do not match.
951     Type *Ty = Denominator->getType();
952     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
953         Ty != StepQ->getType() || Ty != StepR->getType())
954       return cannotDivide(Numerator);
955     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
956                                 Numerator->getNoWrapFlags());
957     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
958                                  Numerator->getNoWrapFlags());
959   }
960 
961   void visitAddExpr(const SCEVAddExpr *Numerator) {
962     SmallVector<const SCEV *, 2> Qs, Rs;
963     Type *Ty = Denominator->getType();
964 
965     for (const SCEV *Op : Numerator->operands()) {
966       const SCEV *Q, *R;
967       divide(SE, Op, Denominator, &Q, &R);
968 
969       // Bail out if types do not match.
970       if (Ty != Q->getType() || Ty != R->getType())
971         return cannotDivide(Numerator);
972 
973       Qs.push_back(Q);
974       Rs.push_back(R);
975     }
976 
977     if (Qs.size() == 1) {
978       Quotient = Qs[0];
979       Remainder = Rs[0];
980       return;
981     }
982 
983     Quotient = SE.getAddExpr(Qs);
984     Remainder = SE.getAddExpr(Rs);
985   }
986 
987   void visitMulExpr(const SCEVMulExpr *Numerator) {
988     SmallVector<const SCEV *, 2> Qs;
989     Type *Ty = Denominator->getType();
990 
991     bool FoundDenominatorTerm = false;
992     for (const SCEV *Op : Numerator->operands()) {
993       // Bail out if types do not match.
994       if (Ty != Op->getType())
995         return cannotDivide(Numerator);
996 
997       if (FoundDenominatorTerm) {
998         Qs.push_back(Op);
999         continue;
1000       }
1001 
1002       // Check whether Denominator divides one of the product operands.
1003       const SCEV *Q, *R;
1004       divide(SE, Op, Denominator, &Q, &R);
1005       if (!R->isZero()) {
1006         Qs.push_back(Op);
1007         continue;
1008       }
1009 
1010       // Bail out if types do not match.
1011       if (Ty != Q->getType())
1012         return cannotDivide(Numerator);
1013 
1014       FoundDenominatorTerm = true;
1015       Qs.push_back(Q);
1016     }
1017 
1018     if (FoundDenominatorTerm) {
1019       Remainder = Zero;
1020       if (Qs.size() == 1)
1021         Quotient = Qs[0];
1022       else
1023         Quotient = SE.getMulExpr(Qs);
1024       return;
1025     }
1026 
1027     if (!isa<SCEVUnknown>(Denominator))
1028       return cannotDivide(Numerator);
1029 
1030     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1031     ValueToValueMap RewriteMap;
1032     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1033         cast<SCEVConstant>(Zero)->getValue();
1034     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1035 
1036     if (Remainder->isZero()) {
1037       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1038       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1039           cast<SCEVConstant>(One)->getValue();
1040       Quotient =
1041           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1042       return;
1043     }
1044 
1045     // Quotient is (Numerator - Remainder) divided by Denominator.
1046     const SCEV *Q, *R;
1047     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1048     // This SCEV does not seem to simplify: fail the division here.
1049     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1050       return cannotDivide(Numerator);
1051     divide(SE, Diff, Denominator, &Q, &R);
1052     if (R != Zero)
1053       return cannotDivide(Numerator);
1054     Quotient = Q;
1055   }
1056 
1057 private:
1058   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1059                const SCEV *Denominator)
1060       : SE(S), Denominator(Denominator) {
1061     Zero = SE.getZero(Denominator->getType());
1062     One = SE.getOne(Denominator->getType());
1063 
1064     // We generally do not know how to divide Expr by Denominator. We
1065     // initialize the division to a "cannot divide" state to simplify the rest
1066     // of the code.
1067     cannotDivide(Numerator);
1068   }
1069 
1070   // Convenience function for giving up on the division. We set the quotient to
1071   // be equal to zero and the remainder to be equal to the numerator.
1072   void cannotDivide(const SCEV *Numerator) {
1073     Quotient = Zero;
1074     Remainder = Numerator;
1075   }
1076 
1077   ScalarEvolution &SE;
1078   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1079 };
1080 
1081 } // end anonymous namespace
1082 
1083 //===----------------------------------------------------------------------===//
1084 //                      Simple SCEV method implementations
1085 //===----------------------------------------------------------------------===//
1086 
1087 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1088 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1089                                        ScalarEvolution &SE,
1090                                        Type *ResultTy) {
1091   // Handle the simplest case efficiently.
1092   if (K == 1)
1093     return SE.getTruncateOrZeroExtend(It, ResultTy);
1094 
1095   // We are using the following formula for BC(It, K):
1096   //
1097   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1098   //
1099   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1100   // overflow.  Hence, we must assure that the result of our computation is
1101   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1102   // safe in modular arithmetic.
1103   //
1104   // However, this code doesn't use exactly that formula; the formula it uses
1105   // is something like the following, where T is the number of factors of 2 in
1106   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1107   // exponentiation:
1108   //
1109   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1110   //
1111   // This formula is trivially equivalent to the previous formula.  However,
1112   // this formula can be implemented much more efficiently.  The trick is that
1113   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1114   // arithmetic.  To do exact division in modular arithmetic, all we have
1115   // to do is multiply by the inverse.  Therefore, this step can be done at
1116   // width W.
1117   //
1118   // The next issue is how to safely do the division by 2^T.  The way this
1119   // is done is by doing the multiplication step at a width of at least W + T
1120   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1121   // when we perform the division by 2^T (which is equivalent to a right shift
1122   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1123   // truncated out after the division by 2^T.
1124   //
1125   // In comparison to just directly using the first formula, this technique
1126   // is much more efficient; using the first formula requires W * K bits,
1127   // but this formula less than W + K bits. Also, the first formula requires
1128   // a division step, whereas this formula only requires multiplies and shifts.
1129   //
1130   // It doesn't matter whether the subtraction step is done in the calculation
1131   // width or the input iteration count's width; if the subtraction overflows,
1132   // the result must be zero anyway.  We prefer here to do it in the width of
1133   // the induction variable because it helps a lot for certain cases; CodeGen
1134   // isn't smart enough to ignore the overflow, which leads to much less
1135   // efficient code if the width of the subtraction is wider than the native
1136   // register width.
1137   //
1138   // (It's possible to not widen at all by pulling out factors of 2 before
1139   // the multiplication; for example, K=2 can be calculated as
1140   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1141   // extra arithmetic, so it's not an obvious win, and it gets
1142   // much more complicated for K > 3.)
1143 
1144   // Protection from insane SCEVs; this bound is conservative,
1145   // but it probably doesn't matter.
1146   if (K > 1000)
1147     return SE.getCouldNotCompute();
1148 
1149   unsigned W = SE.getTypeSizeInBits(ResultTy);
1150 
1151   // Calculate K! / 2^T and T; we divide out the factors of two before
1152   // multiplying for calculating K! / 2^T to avoid overflow.
1153   // Other overflow doesn't matter because we only care about the bottom
1154   // W bits of the result.
1155   APInt OddFactorial(W, 1);
1156   unsigned T = 1;
1157   for (unsigned i = 3; i <= K; ++i) {
1158     APInt Mult(W, i);
1159     unsigned TwoFactors = Mult.countTrailingZeros();
1160     T += TwoFactors;
1161     Mult.lshrInPlace(TwoFactors);
1162     OddFactorial *= Mult;
1163   }
1164 
1165   // We need at least W + T bits for the multiplication step
1166   unsigned CalculationBits = W + T;
1167 
1168   // Calculate 2^T, at width T+W.
1169   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1170 
1171   // Calculate the multiplicative inverse of K! / 2^T;
1172   // this multiplication factor will perform the exact division by
1173   // K! / 2^T.
1174   APInt Mod = APInt::getSignedMinValue(W+1);
1175   APInt MultiplyFactor = OddFactorial.zext(W+1);
1176   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1177   MultiplyFactor = MultiplyFactor.trunc(W);
1178 
1179   // Calculate the product, at width T+W
1180   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1181                                                       CalculationBits);
1182   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1183   for (unsigned i = 1; i != K; ++i) {
1184     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1185     Dividend = SE.getMulExpr(Dividend,
1186                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1187   }
1188 
1189   // Divide by 2^T
1190   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1191 
1192   // Truncate the result, and divide by K! / 2^T.
1193 
1194   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1195                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1196 }
1197 
1198 /// Return the value of this chain of recurrences at the specified iteration
1199 /// number.  We can evaluate this recurrence by multiplying each element in the
1200 /// chain by the binomial coefficient corresponding to it.  In other words, we
1201 /// can evaluate {A,+,B,+,C,+,D} as:
1202 ///
1203 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1204 ///
1205 /// where BC(It, k) stands for binomial coefficient.
1206 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1207                                                 ScalarEvolution &SE) const {
1208   const SCEV *Result = getStart();
1209   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1210     // The computation is correct in the face of overflow provided that the
1211     // multiplication is performed _after_ the evaluation of the binomial
1212     // coefficient.
1213     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1214     if (isa<SCEVCouldNotCompute>(Coeff))
1215       return Coeff;
1216 
1217     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1218   }
1219   return Result;
1220 }
1221 
1222 //===----------------------------------------------------------------------===//
1223 //                    SCEV Expression folder implementations
1224 //===----------------------------------------------------------------------===//
1225 
1226 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1227                                              Type *Ty) {
1228   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1229          "This is not a truncating conversion!");
1230   assert(isSCEVable(Ty) &&
1231          "This is not a conversion to a SCEVable type!");
1232   Ty = getEffectiveSCEVType(Ty);
1233 
1234   FoldingSetNodeID ID;
1235   ID.AddInteger(scTruncate);
1236   ID.AddPointer(Op);
1237   ID.AddPointer(Ty);
1238   void *IP = nullptr;
1239   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1240 
1241   // Fold if the operand is constant.
1242   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1243     return getConstant(
1244       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1245 
1246   // trunc(trunc(x)) --> trunc(x)
1247   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1248     return getTruncateExpr(ST->getOperand(), Ty);
1249 
1250   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1251   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1252     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1253 
1254   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1255   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1256     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1257 
1258   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1259   // eliminate all the truncates, or we replace other casts with truncates.
1260   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1261     SmallVector<const SCEV *, 4> Operands;
1262     bool hasTrunc = false;
1263     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1264       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1265       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1266         hasTrunc = isa<SCEVTruncateExpr>(S);
1267       Operands.push_back(S);
1268     }
1269     if (!hasTrunc)
1270       return getAddExpr(Operands);
1271     // In spite we checked in the beginning that ID is not in the cache,
1272     // it is possible that during recursion and different modification
1273     // ID came to cache, so if we found it, just return it.
1274     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1275       return S;
1276   }
1277 
1278   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1279   // eliminate all the truncates, or we replace other casts with truncates.
1280   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1281     SmallVector<const SCEV *, 4> Operands;
1282     bool hasTrunc = false;
1283     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1284       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1285       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1286         hasTrunc = isa<SCEVTruncateExpr>(S);
1287       Operands.push_back(S);
1288     }
1289     if (!hasTrunc)
1290       return getMulExpr(Operands);
1291     // In spite we checked in the beginning that ID is not in the cache,
1292     // it is possible that during recursion and different modification
1293     // ID came to cache, so if we found it, just return it.
1294     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1295       return S;
1296   }
1297 
1298   // If the input value is a chrec scev, truncate the chrec's operands.
1299   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1300     SmallVector<const SCEV *, 4> Operands;
1301     for (const SCEV *Op : AddRec->operands())
1302       Operands.push_back(getTruncateExpr(Op, Ty));
1303     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1304   }
1305 
1306   // The cast wasn't folded; create an explicit cast node. We can reuse
1307   // the existing insert position since if we get here, we won't have
1308   // made any changes which would invalidate it.
1309   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1310                                                  Op, Ty);
1311   UniqueSCEVs.InsertNode(S, IP);
1312   addToLoopUseLists(S);
1313   return S;
1314 }
1315 
1316 // Get the limit of a recurrence such that incrementing by Step cannot cause
1317 // signed overflow as long as the value of the recurrence within the
1318 // loop does not exceed this limit before incrementing.
1319 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1320                                                  ICmpInst::Predicate *Pred,
1321                                                  ScalarEvolution *SE) {
1322   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1323   if (SE->isKnownPositive(Step)) {
1324     *Pred = ICmpInst::ICMP_SLT;
1325     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1326                            SE->getSignedRangeMax(Step));
1327   }
1328   if (SE->isKnownNegative(Step)) {
1329     *Pred = ICmpInst::ICMP_SGT;
1330     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1331                            SE->getSignedRangeMin(Step));
1332   }
1333   return nullptr;
1334 }
1335 
1336 // Get the limit of a recurrence such that incrementing by Step cannot cause
1337 // unsigned overflow as long as the value of the recurrence within the loop does
1338 // not exceed this limit before incrementing.
1339 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1340                                                    ICmpInst::Predicate *Pred,
1341                                                    ScalarEvolution *SE) {
1342   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1343   *Pred = ICmpInst::ICMP_ULT;
1344 
1345   return SE->getConstant(APInt::getMinValue(BitWidth) -
1346                          SE->getUnsignedRangeMax(Step));
1347 }
1348 
1349 namespace {
1350 
1351 struct ExtendOpTraitsBase {
1352   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1353                                                           unsigned);
1354 };
1355 
1356 // Used to make code generic over signed and unsigned overflow.
1357 template <typename ExtendOp> struct ExtendOpTraits {
1358   // Members present:
1359   //
1360   // static const SCEV::NoWrapFlags WrapType;
1361   //
1362   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1363   //
1364   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1365   //                                           ICmpInst::Predicate *Pred,
1366   //                                           ScalarEvolution *SE);
1367 };
1368 
1369 template <>
1370 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1371   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1372 
1373   static const GetExtendExprTy GetExtendExpr;
1374 
1375   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1376                                              ICmpInst::Predicate *Pred,
1377                                              ScalarEvolution *SE) {
1378     return getSignedOverflowLimitForStep(Step, Pred, SE);
1379   }
1380 };
1381 
1382 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1383     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1384 
1385 template <>
1386 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1387   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1388 
1389   static const GetExtendExprTy GetExtendExpr;
1390 
1391   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1392                                              ICmpInst::Predicate *Pred,
1393                                              ScalarEvolution *SE) {
1394     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1395   }
1396 };
1397 
1398 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1399     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1400 
1401 } // end anonymous namespace
1402 
1403 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1404 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1405 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1406 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1407 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1408 // expression "Step + sext/zext(PreIncAR)" is congruent with
1409 // "sext/zext(PostIncAR)"
1410 template <typename ExtendOpTy>
1411 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1412                                         ScalarEvolution *SE, unsigned Depth) {
1413   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1414   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1415 
1416   const Loop *L = AR->getLoop();
1417   const SCEV *Start = AR->getStart();
1418   const SCEV *Step = AR->getStepRecurrence(*SE);
1419 
1420   // Check for a simple looking step prior to loop entry.
1421   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1422   if (!SA)
1423     return nullptr;
1424 
1425   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1426   // subtraction is expensive. For this purpose, perform a quick and dirty
1427   // difference, by checking for Step in the operand list.
1428   SmallVector<const SCEV *, 4> DiffOps;
1429   for (const SCEV *Op : SA->operands())
1430     if (Op != Step)
1431       DiffOps.push_back(Op);
1432 
1433   if (DiffOps.size() == SA->getNumOperands())
1434     return nullptr;
1435 
1436   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1437   // `Step`:
1438 
1439   // 1. NSW/NUW flags on the step increment.
1440   auto PreStartFlags =
1441     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1442   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1443   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1444       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1445 
1446   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1447   // "S+X does not sign/unsign-overflow".
1448   //
1449 
1450   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1451   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1452       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1453     return PreStart;
1454 
1455   // 2. Direct overflow check on the step operation's expression.
1456   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1457   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1458   const SCEV *OperandExtendedStart =
1459       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1460                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1461   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1462     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1463       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1464       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1465       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1466       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1467     }
1468     return PreStart;
1469   }
1470 
1471   // 3. Loop precondition.
1472   ICmpInst::Predicate Pred;
1473   const SCEV *OverflowLimit =
1474       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1475 
1476   if (OverflowLimit &&
1477       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1478     return PreStart;
1479 
1480   return nullptr;
1481 }
1482 
1483 // Get the normalized zero or sign extended expression for this AddRec's Start.
1484 template <typename ExtendOpTy>
1485 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1486                                         ScalarEvolution *SE,
1487                                         unsigned Depth) {
1488   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1489 
1490   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1491   if (!PreStart)
1492     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1493 
1494   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1495                                              Depth),
1496                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1497 }
1498 
1499 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1500 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1501 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1502 //
1503 // Formally:
1504 //
1505 //     {S,+,X} == {S-T,+,X} + T
1506 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1507 //
1508 // If ({S-T,+,X} + T) does not overflow  ... (1)
1509 //
1510 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1511 //
1512 // If {S-T,+,X} does not overflow  ... (2)
1513 //
1514 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1515 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1516 //
1517 // If (S-T)+T does not overflow  ... (3)
1518 //
1519 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1520 //      == {Ext(S),+,Ext(X)} == LHS
1521 //
1522 // Thus, if (1), (2) and (3) are true for some T, then
1523 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1524 //
1525 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1526 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1527 // to check for (1) and (2).
1528 //
1529 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1530 // is `Delta` (defined below).
1531 template <typename ExtendOpTy>
1532 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1533                                                 const SCEV *Step,
1534                                                 const Loop *L) {
1535   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1536 
1537   // We restrict `Start` to a constant to prevent SCEV from spending too much
1538   // time here.  It is correct (but more expensive) to continue with a
1539   // non-constant `Start` and do a general SCEV subtraction to compute
1540   // `PreStart` below.
1541   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1542   if (!StartC)
1543     return false;
1544 
1545   APInt StartAI = StartC->getAPInt();
1546 
1547   for (unsigned Delta : {-2, -1, 1, 2}) {
1548     const SCEV *PreStart = getConstant(StartAI - Delta);
1549 
1550     FoldingSetNodeID ID;
1551     ID.AddInteger(scAddRecExpr);
1552     ID.AddPointer(PreStart);
1553     ID.AddPointer(Step);
1554     ID.AddPointer(L);
1555     void *IP = nullptr;
1556     const auto *PreAR =
1557       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1558 
1559     // Give up if we don't already have the add recurrence we need because
1560     // actually constructing an add recurrence is relatively expensive.
1561     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1562       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1563       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1564       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1565           DeltaS, &Pred, this);
1566       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1567         return true;
1568     }
1569   }
1570 
1571   return false;
1572 }
1573 
1574 const SCEV *
1575 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1576   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1577          "This is not an extending conversion!");
1578   assert(isSCEVable(Ty) &&
1579          "This is not a conversion to a SCEVable type!");
1580   Ty = getEffectiveSCEVType(Ty);
1581 
1582   // Fold if the operand is constant.
1583   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1584     return getConstant(
1585       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1586 
1587   // zext(zext(x)) --> zext(x)
1588   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1589     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1590 
1591   // Before doing any expensive analysis, check to see if we've already
1592   // computed a SCEV for this Op and Ty.
1593   FoldingSetNodeID ID;
1594   ID.AddInteger(scZeroExtend);
1595   ID.AddPointer(Op);
1596   ID.AddPointer(Ty);
1597   void *IP = nullptr;
1598   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1599   if (Depth > MaxExtDepth) {
1600     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1601                                                      Op, Ty);
1602     UniqueSCEVs.InsertNode(S, IP);
1603     addToLoopUseLists(S);
1604     return S;
1605   }
1606 
1607   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1608   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1609     // It's possible the bits taken off by the truncate were all zero bits. If
1610     // so, we should be able to simplify this further.
1611     const SCEV *X = ST->getOperand();
1612     ConstantRange CR = getUnsignedRange(X);
1613     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1614     unsigned NewBits = getTypeSizeInBits(Ty);
1615     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1616             CR.zextOrTrunc(NewBits)))
1617       return getTruncateOrZeroExtend(X, Ty);
1618   }
1619 
1620   // If the input value is a chrec scev, and we can prove that the value
1621   // did not overflow the old, smaller, value, we can zero extend all of the
1622   // operands (often constants).  This allows analysis of something like
1623   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1624   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1625     if (AR->isAffine()) {
1626       const SCEV *Start = AR->getStart();
1627       const SCEV *Step = AR->getStepRecurrence(*this);
1628       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1629       const Loop *L = AR->getLoop();
1630 
1631       if (!AR->hasNoUnsignedWrap()) {
1632         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1633         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1634       }
1635 
1636       // If we have special knowledge that this addrec won't overflow,
1637       // we don't need to do any further analysis.
1638       if (AR->hasNoUnsignedWrap())
1639         return getAddRecExpr(
1640             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1641             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1642 
1643       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1644       // Note that this serves two purposes: It filters out loops that are
1645       // simply not analyzable, and it covers the case where this code is
1646       // being called from within backedge-taken count analysis, such that
1647       // attempting to ask for the backedge-taken count would likely result
1648       // in infinite recursion. In the later case, the analysis code will
1649       // cope with a conservative value, and it will take care to purge
1650       // that value once it has finished.
1651       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1652       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1653         // Manually compute the final value for AR, checking for
1654         // overflow.
1655 
1656         // Check whether the backedge-taken count can be losslessly casted to
1657         // the addrec's type. The count is always unsigned.
1658         const SCEV *CastedMaxBECount =
1659           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1660         const SCEV *RecastedMaxBECount =
1661           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1662         if (MaxBECount == RecastedMaxBECount) {
1663           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1664           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1665           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1666                                         SCEV::FlagAnyWrap, Depth + 1);
1667           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1668                                                           SCEV::FlagAnyWrap,
1669                                                           Depth + 1),
1670                                                WideTy, Depth + 1);
1671           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1672           const SCEV *WideMaxBECount =
1673             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1674           const SCEV *OperandExtendedAdd =
1675             getAddExpr(WideStart,
1676                        getMulExpr(WideMaxBECount,
1677                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1678                                   SCEV::FlagAnyWrap, Depth + 1),
1679                        SCEV::FlagAnyWrap, Depth + 1);
1680           if (ZAdd == OperandExtendedAdd) {
1681             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1682             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1683             // Return the expression with the addrec on the outside.
1684             return getAddRecExpr(
1685                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1686                                                          Depth + 1),
1687                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1688                 AR->getNoWrapFlags());
1689           }
1690           // Similar to above, only this time treat the step value as signed.
1691           // This covers loops that count down.
1692           OperandExtendedAdd =
1693             getAddExpr(WideStart,
1694                        getMulExpr(WideMaxBECount,
1695                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1696                                   SCEV::FlagAnyWrap, Depth + 1),
1697                        SCEV::FlagAnyWrap, Depth + 1);
1698           if (ZAdd == OperandExtendedAdd) {
1699             // Cache knowledge of AR NW, which is propagated to this AddRec.
1700             // Negative step causes unsigned wrap, but it still can't self-wrap.
1701             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1702             // Return the expression with the addrec on the outside.
1703             return getAddRecExpr(
1704                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1705                                                          Depth + 1),
1706                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1707                 AR->getNoWrapFlags());
1708           }
1709         }
1710       }
1711 
1712       // Normally, in the cases we can prove no-overflow via a
1713       // backedge guarding condition, we can also compute a backedge
1714       // taken count for the loop.  The exceptions are assumptions and
1715       // guards present in the loop -- SCEV is not great at exploiting
1716       // these to compute max backedge taken counts, but can still use
1717       // these to prove lack of overflow.  Use this fact to avoid
1718       // doing extra work that may not pay off.
1719       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1720           !AC.assumptions().empty()) {
1721         // If the backedge is guarded by a comparison with the pre-inc
1722         // value the addrec is safe. Also, if the entry is guarded by
1723         // a comparison with the start value and the backedge is
1724         // guarded by a comparison with the post-inc value, the addrec
1725         // is safe.
1726         if (isKnownPositive(Step)) {
1727           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1728                                       getUnsignedRangeMax(Step));
1729           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1730               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1731                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1732                                            AR->getPostIncExpr(*this), N))) {
1733             // Cache knowledge of AR NUW, which is propagated to this
1734             // AddRec.
1735             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1736             // Return the expression with the addrec on the outside.
1737             return getAddRecExpr(
1738                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1739                                                          Depth + 1),
1740                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1741                 AR->getNoWrapFlags());
1742           }
1743         } else if (isKnownNegative(Step)) {
1744           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1745                                       getSignedRangeMin(Step));
1746           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1747               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1748                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1749                                            AR->getPostIncExpr(*this), N))) {
1750             // Cache knowledge of AR NW, which is propagated to this
1751             // AddRec.  Negative step causes unsigned wrap, but it
1752             // still can't self-wrap.
1753             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1754             // Return the expression with the addrec on the outside.
1755             return getAddRecExpr(
1756                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1757                                                          Depth + 1),
1758                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1759                 AR->getNoWrapFlags());
1760           }
1761         }
1762       }
1763 
1764       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1765         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1766         return getAddRecExpr(
1767             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1768             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1769       }
1770     }
1771 
1772   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1773     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1774     if (SA->hasNoUnsignedWrap()) {
1775       // If the addition does not unsign overflow then we can, by definition,
1776       // commute the zero extension with the addition operation.
1777       SmallVector<const SCEV *, 4> Ops;
1778       for (const auto *Op : SA->operands())
1779         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1780       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1781     }
1782   }
1783 
1784   // The cast wasn't folded; create an explicit cast node.
1785   // Recompute the insert position, as it may have been invalidated.
1786   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1787   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1788                                                    Op, Ty);
1789   UniqueSCEVs.InsertNode(S, IP);
1790   addToLoopUseLists(S);
1791   return S;
1792 }
1793 
1794 const SCEV *
1795 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1796   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1797          "This is not an extending conversion!");
1798   assert(isSCEVable(Ty) &&
1799          "This is not a conversion to a SCEVable type!");
1800   Ty = getEffectiveSCEVType(Ty);
1801 
1802   // Fold if the operand is constant.
1803   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1804     return getConstant(
1805       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1806 
1807   // sext(sext(x)) --> sext(x)
1808   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1809     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1810 
1811   // sext(zext(x)) --> zext(x)
1812   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1813     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1814 
1815   // Before doing any expensive analysis, check to see if we've already
1816   // computed a SCEV for this Op and Ty.
1817   FoldingSetNodeID ID;
1818   ID.AddInteger(scSignExtend);
1819   ID.AddPointer(Op);
1820   ID.AddPointer(Ty);
1821   void *IP = nullptr;
1822   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1823   // Limit recursion depth.
1824   if (Depth > MaxExtDepth) {
1825     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1826                                                      Op, Ty);
1827     UniqueSCEVs.InsertNode(S, IP);
1828     addToLoopUseLists(S);
1829     return S;
1830   }
1831 
1832   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1833   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1834     // It's possible the bits taken off by the truncate were all sign bits. If
1835     // so, we should be able to simplify this further.
1836     const SCEV *X = ST->getOperand();
1837     ConstantRange CR = getSignedRange(X);
1838     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1839     unsigned NewBits = getTypeSizeInBits(Ty);
1840     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1841             CR.sextOrTrunc(NewBits)))
1842       return getTruncateOrSignExtend(X, Ty);
1843   }
1844 
1845   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1846   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1847     if (SA->getNumOperands() == 2) {
1848       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1849       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1850       if (SMul && SC1) {
1851         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1852           const APInt &C1 = SC1->getAPInt();
1853           const APInt &C2 = SC2->getAPInt();
1854           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1855               C2.ugt(C1) && C2.isPowerOf2())
1856             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1857                               getSignExtendExpr(SMul, Ty, Depth + 1),
1858                               SCEV::FlagAnyWrap, Depth + 1);
1859         }
1860       }
1861     }
1862 
1863     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1864     if (SA->hasNoSignedWrap()) {
1865       // If the addition does not sign overflow then we can, by definition,
1866       // commute the sign extension with the addition operation.
1867       SmallVector<const SCEV *, 4> Ops;
1868       for (const auto *Op : SA->operands())
1869         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1870       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1871     }
1872   }
1873   // If the input value is a chrec scev, and we can prove that the value
1874   // did not overflow the old, smaller, value, we can sign extend all of the
1875   // operands (often constants).  This allows analysis of something like
1876   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1877   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1878     if (AR->isAffine()) {
1879       const SCEV *Start = AR->getStart();
1880       const SCEV *Step = AR->getStepRecurrence(*this);
1881       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1882       const Loop *L = AR->getLoop();
1883 
1884       if (!AR->hasNoSignedWrap()) {
1885         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1886         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1887       }
1888 
1889       // If we have special knowledge that this addrec won't overflow,
1890       // we don't need to do any further analysis.
1891       if (AR->hasNoSignedWrap())
1892         return getAddRecExpr(
1893             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1894             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1895 
1896       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1897       // Note that this serves two purposes: It filters out loops that are
1898       // simply not analyzable, and it covers the case where this code is
1899       // being called from within backedge-taken count analysis, such that
1900       // attempting to ask for the backedge-taken count would likely result
1901       // in infinite recursion. In the later case, the analysis code will
1902       // cope with a conservative value, and it will take care to purge
1903       // that value once it has finished.
1904       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1905       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1906         // Manually compute the final value for AR, checking for
1907         // overflow.
1908 
1909         // Check whether the backedge-taken count can be losslessly casted to
1910         // the addrec's type. The count is always unsigned.
1911         const SCEV *CastedMaxBECount =
1912           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1913         const SCEV *RecastedMaxBECount =
1914           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1915         if (MaxBECount == RecastedMaxBECount) {
1916           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1917           // Check whether Start+Step*MaxBECount has no signed overflow.
1918           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1919                                         SCEV::FlagAnyWrap, Depth + 1);
1920           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1921                                                           SCEV::FlagAnyWrap,
1922                                                           Depth + 1),
1923                                                WideTy, Depth + 1);
1924           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1925           const SCEV *WideMaxBECount =
1926             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1927           const SCEV *OperandExtendedAdd =
1928             getAddExpr(WideStart,
1929                        getMulExpr(WideMaxBECount,
1930                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1931                                   SCEV::FlagAnyWrap, Depth + 1),
1932                        SCEV::FlagAnyWrap, Depth + 1);
1933           if (SAdd == OperandExtendedAdd) {
1934             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1935             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1936             // Return the expression with the addrec on the outside.
1937             return getAddRecExpr(
1938                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1939                                                          Depth + 1),
1940                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1941                 AR->getNoWrapFlags());
1942           }
1943           // Similar to above, only this time treat the step value as unsigned.
1944           // This covers loops that count up with an unsigned step.
1945           OperandExtendedAdd =
1946             getAddExpr(WideStart,
1947                        getMulExpr(WideMaxBECount,
1948                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1949                                   SCEV::FlagAnyWrap, Depth + 1),
1950                        SCEV::FlagAnyWrap, Depth + 1);
1951           if (SAdd == OperandExtendedAdd) {
1952             // If AR wraps around then
1953             //
1954             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1955             // => SAdd != OperandExtendedAdd
1956             //
1957             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1958             // (SAdd == OperandExtendedAdd => AR is NW)
1959 
1960             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1961 
1962             // Return the expression with the addrec on the outside.
1963             return getAddRecExpr(
1964                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1965                                                          Depth + 1),
1966                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1967                 AR->getNoWrapFlags());
1968           }
1969         }
1970       }
1971 
1972       // Normally, in the cases we can prove no-overflow via a
1973       // backedge guarding condition, we can also compute a backedge
1974       // taken count for the loop.  The exceptions are assumptions and
1975       // guards present in the loop -- SCEV is not great at exploiting
1976       // these to compute max backedge taken counts, but can still use
1977       // these to prove lack of overflow.  Use this fact to avoid
1978       // doing extra work that may not pay off.
1979 
1980       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1981           !AC.assumptions().empty()) {
1982         // If the backedge is guarded by a comparison with the pre-inc
1983         // value the addrec is safe. Also, if the entry is guarded by
1984         // a comparison with the start value and the backedge is
1985         // guarded by a comparison with the post-inc value, the addrec
1986         // is safe.
1987         ICmpInst::Predicate Pred;
1988         const SCEV *OverflowLimit =
1989             getSignedOverflowLimitForStep(Step, &Pred, this);
1990         if (OverflowLimit &&
1991             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1992              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1993               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1994                                           OverflowLimit)))) {
1995           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1996           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1997           return getAddRecExpr(
1998               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1999               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2000         }
2001       }
2002 
2003       // If Start and Step are constants, check if we can apply this
2004       // transformation:
2005       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2006       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2007       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2008       if (SC1 && SC2) {
2009         const APInt &C1 = SC1->getAPInt();
2010         const APInt &C2 = SC2->getAPInt();
2011         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2012             C2.isPowerOf2()) {
2013           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2014           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2015                                             AR->getNoWrapFlags());
2016           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2017                             SCEV::FlagAnyWrap, Depth + 1);
2018         }
2019       }
2020 
2021       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2022         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2023         return getAddRecExpr(
2024             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2025             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2026       }
2027     }
2028 
2029   // If the input value is provably positive and we could not simplify
2030   // away the sext build a zext instead.
2031   if (isKnownNonNegative(Op))
2032     return getZeroExtendExpr(Op, Ty, Depth + 1);
2033 
2034   // The cast wasn't folded; create an explicit cast node.
2035   // Recompute the insert position, as it may have been invalidated.
2036   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2037   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2038                                                    Op, Ty);
2039   UniqueSCEVs.InsertNode(S, IP);
2040   addToLoopUseLists(S);
2041   return S;
2042 }
2043 
2044 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2045 /// unspecified bits out to the given type.
2046 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2047                                               Type *Ty) {
2048   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2049          "This is not an extending conversion!");
2050   assert(isSCEVable(Ty) &&
2051          "This is not a conversion to a SCEVable type!");
2052   Ty = getEffectiveSCEVType(Ty);
2053 
2054   // Sign-extend negative constants.
2055   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2056     if (SC->getAPInt().isNegative())
2057       return getSignExtendExpr(Op, Ty);
2058 
2059   // Peel off a truncate cast.
2060   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2061     const SCEV *NewOp = T->getOperand();
2062     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2063       return getAnyExtendExpr(NewOp, Ty);
2064     return getTruncateOrNoop(NewOp, Ty);
2065   }
2066 
2067   // Next try a zext cast. If the cast is folded, use it.
2068   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2069   if (!isa<SCEVZeroExtendExpr>(ZExt))
2070     return ZExt;
2071 
2072   // Next try a sext cast. If the cast is folded, use it.
2073   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2074   if (!isa<SCEVSignExtendExpr>(SExt))
2075     return SExt;
2076 
2077   // Force the cast to be folded into the operands of an addrec.
2078   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2079     SmallVector<const SCEV *, 4> Ops;
2080     for (const SCEV *Op : AR->operands())
2081       Ops.push_back(getAnyExtendExpr(Op, Ty));
2082     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2083   }
2084 
2085   // If the expression is obviously signed, use the sext cast value.
2086   if (isa<SCEVSMaxExpr>(Op))
2087     return SExt;
2088 
2089   // Absent any other information, use the zext cast value.
2090   return ZExt;
2091 }
2092 
2093 /// Process the given Ops list, which is a list of operands to be added under
2094 /// the given scale, update the given map. This is a helper function for
2095 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2096 /// that would form an add expression like this:
2097 ///
2098 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2099 ///
2100 /// where A and B are constants, update the map with these values:
2101 ///
2102 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2103 ///
2104 /// and add 13 + A*B*29 to AccumulatedConstant.
2105 /// This will allow getAddRecExpr to produce this:
2106 ///
2107 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2108 ///
2109 /// This form often exposes folding opportunities that are hidden in
2110 /// the original operand list.
2111 ///
2112 /// Return true iff it appears that any interesting folding opportunities
2113 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2114 /// the common case where no interesting opportunities are present, and
2115 /// is also used as a check to avoid infinite recursion.
2116 static bool
2117 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2118                              SmallVectorImpl<const SCEV *> &NewOps,
2119                              APInt &AccumulatedConstant,
2120                              const SCEV *const *Ops, size_t NumOperands,
2121                              const APInt &Scale,
2122                              ScalarEvolution &SE) {
2123   bool Interesting = false;
2124 
2125   // Iterate over the add operands. They are sorted, with constants first.
2126   unsigned i = 0;
2127   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2128     ++i;
2129     // Pull a buried constant out to the outside.
2130     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2131       Interesting = true;
2132     AccumulatedConstant += Scale * C->getAPInt();
2133   }
2134 
2135   // Next comes everything else. We're especially interested in multiplies
2136   // here, but they're in the middle, so just visit the rest with one loop.
2137   for (; i != NumOperands; ++i) {
2138     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2139     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2140       APInt NewScale =
2141           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2142       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2143         // A multiplication of a constant with another add; recurse.
2144         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2145         Interesting |=
2146           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2147                                        Add->op_begin(), Add->getNumOperands(),
2148                                        NewScale, SE);
2149       } else {
2150         // A multiplication of a constant with some other value. Update
2151         // the map.
2152         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2153         const SCEV *Key = SE.getMulExpr(MulOps);
2154         auto Pair = M.insert({Key, NewScale});
2155         if (Pair.second) {
2156           NewOps.push_back(Pair.first->first);
2157         } else {
2158           Pair.first->second += NewScale;
2159           // The map already had an entry for this value, which may indicate
2160           // a folding opportunity.
2161           Interesting = true;
2162         }
2163       }
2164     } else {
2165       // An ordinary operand. Update the map.
2166       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2167           M.insert({Ops[i], Scale});
2168       if (Pair.second) {
2169         NewOps.push_back(Pair.first->first);
2170       } else {
2171         Pair.first->second += Scale;
2172         // The map already had an entry for this value, which may indicate
2173         // a folding opportunity.
2174         Interesting = true;
2175       }
2176     }
2177   }
2178 
2179   return Interesting;
2180 }
2181 
2182 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2183 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2184 // can't-overflow flags for the operation if possible.
2185 static SCEV::NoWrapFlags
2186 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2187                       const SmallVectorImpl<const SCEV *> &Ops,
2188                       SCEV::NoWrapFlags Flags) {
2189   using namespace std::placeholders;
2190 
2191   using OBO = OverflowingBinaryOperator;
2192 
2193   bool CanAnalyze =
2194       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2195   (void)CanAnalyze;
2196   assert(CanAnalyze && "don't call from other places!");
2197 
2198   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2199   SCEV::NoWrapFlags SignOrUnsignWrap =
2200       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2201 
2202   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2203   auto IsKnownNonNegative = [&](const SCEV *S) {
2204     return SE->isKnownNonNegative(S);
2205   };
2206 
2207   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2208     Flags =
2209         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2210 
2211   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2212 
2213   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2214       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2215 
2216     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2217     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2218 
2219     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2220     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2221       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2222           Instruction::Add, C, OBO::NoSignedWrap);
2223       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2224         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2225     }
2226     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2227       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2228           Instruction::Add, C, OBO::NoUnsignedWrap);
2229       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2230         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2231     }
2232   }
2233 
2234   return Flags;
2235 }
2236 
2237 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2238   if (!isLoopInvariant(S, L))
2239     return false;
2240   // If a value depends on a SCEVUnknown which is defined after the loop, we
2241   // conservatively assume that we cannot calculate it at the loop's entry.
2242   struct FindDominatedSCEVUnknown {
2243     bool Found = false;
2244     const Loop *L;
2245     DominatorTree &DT;
2246     LoopInfo &LI;
2247 
2248     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2249         : L(L), DT(DT), LI(LI) {}
2250 
2251     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2252       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2253         if (DT.dominates(L->getHeader(), I->getParent()))
2254           Found = true;
2255         else
2256           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2257                  "No dominance relationship between SCEV and loop?");
2258       }
2259       return false;
2260     }
2261 
2262     bool follow(const SCEV *S) {
2263       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2264       case scConstant:
2265         return false;
2266       case scAddRecExpr:
2267       case scTruncate:
2268       case scZeroExtend:
2269       case scSignExtend:
2270       case scAddExpr:
2271       case scMulExpr:
2272       case scUMaxExpr:
2273       case scSMaxExpr:
2274       case scUDivExpr:
2275         return true;
2276       case scUnknown:
2277         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2278       case scCouldNotCompute:
2279         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2280       }
2281       return false;
2282     }
2283 
2284     bool isDone() { return Found; }
2285   };
2286 
2287   FindDominatedSCEVUnknown FSU(L, DT, LI);
2288   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2289   ST.visitAll(S);
2290   return !FSU.Found;
2291 }
2292 
2293 /// Get a canonical add expression, or something simpler if possible.
2294 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2295                                         SCEV::NoWrapFlags Flags,
2296                                         unsigned Depth) {
2297   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2298          "only nuw or nsw allowed");
2299   assert(!Ops.empty() && "Cannot get empty add!");
2300   if (Ops.size() == 1) return Ops[0];
2301 #ifndef NDEBUG
2302   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2303   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2304     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2305            "SCEVAddExpr operand types don't match!");
2306 #endif
2307 
2308   // Sort by complexity, this groups all similar expression types together.
2309   GroupByComplexity(Ops, &LI, DT);
2310 
2311   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2312 
2313   // If there are any constants, fold them together.
2314   unsigned Idx = 0;
2315   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2316     ++Idx;
2317     assert(Idx < Ops.size());
2318     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2319       // We found two constants, fold them together!
2320       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2321       if (Ops.size() == 2) return Ops[0];
2322       Ops.erase(Ops.begin()+1);  // Erase the folded element
2323       LHSC = cast<SCEVConstant>(Ops[0]);
2324     }
2325 
2326     // If we are left with a constant zero being added, strip it off.
2327     if (LHSC->getValue()->isZero()) {
2328       Ops.erase(Ops.begin());
2329       --Idx;
2330     }
2331 
2332     if (Ops.size() == 1) return Ops[0];
2333   }
2334 
2335   // Limit recursion calls depth.
2336   if (Depth > MaxArithDepth)
2337     return getOrCreateAddExpr(Ops, Flags);
2338 
2339   // Okay, check to see if the same value occurs in the operand list more than
2340   // once.  If so, merge them together into an multiply expression.  Since we
2341   // sorted the list, these values are required to be adjacent.
2342   Type *Ty = Ops[0]->getType();
2343   bool FoundMatch = false;
2344   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2345     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2346       // Scan ahead to count how many equal operands there are.
2347       unsigned Count = 2;
2348       while (i+Count != e && Ops[i+Count] == Ops[i])
2349         ++Count;
2350       // Merge the values into a multiply.
2351       const SCEV *Scale = getConstant(Ty, Count);
2352       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2353       if (Ops.size() == Count)
2354         return Mul;
2355       Ops[i] = Mul;
2356       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2357       --i; e -= Count - 1;
2358       FoundMatch = true;
2359     }
2360   if (FoundMatch)
2361     return getAddExpr(Ops, Flags, Depth + 1);
2362 
2363   // Check for truncates. If all the operands are truncated from the same
2364   // type, see if factoring out the truncate would permit the result to be
2365   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2366   // if the contents of the resulting outer trunc fold to something simple.
2367   auto FindTruncSrcType = [&]() -> Type * {
2368     // We're ultimately looking to fold an addrec of truncs and muls of only
2369     // constants and truncs, so if we find any other types of SCEV
2370     // as operands of the addrec then we bail and return nullptr here.
2371     // Otherwise, we return the type of the operand of a trunc that we find.
2372     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2373       return T->getOperand()->getType();
2374     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2375       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2376       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2377         return T->getOperand()->getType();
2378     }
2379     return nullptr;
2380   };
2381   if (auto *SrcType = FindTruncSrcType()) {
2382     SmallVector<const SCEV *, 8> LargeOps;
2383     bool Ok = true;
2384     // Check all the operands to see if they can be represented in the
2385     // source type of the truncate.
2386     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2387       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2388         if (T->getOperand()->getType() != SrcType) {
2389           Ok = false;
2390           break;
2391         }
2392         LargeOps.push_back(T->getOperand());
2393       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2394         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2395       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2396         SmallVector<const SCEV *, 8> LargeMulOps;
2397         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2398           if (const SCEVTruncateExpr *T =
2399                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2400             if (T->getOperand()->getType() != SrcType) {
2401               Ok = false;
2402               break;
2403             }
2404             LargeMulOps.push_back(T->getOperand());
2405           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2406             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2407           } else {
2408             Ok = false;
2409             break;
2410           }
2411         }
2412         if (Ok)
2413           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2414       } else {
2415         Ok = false;
2416         break;
2417       }
2418     }
2419     if (Ok) {
2420       // Evaluate the expression in the larger type.
2421       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2422       // If it folds to something simple, use it. Otherwise, don't.
2423       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2424         return getTruncateExpr(Fold, Ty);
2425     }
2426   }
2427 
2428   // Skip past any other cast SCEVs.
2429   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2430     ++Idx;
2431 
2432   // If there are add operands they would be next.
2433   if (Idx < Ops.size()) {
2434     bool DeletedAdd = false;
2435     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2436       if (Ops.size() > AddOpsInlineThreshold ||
2437           Add->getNumOperands() > AddOpsInlineThreshold)
2438         break;
2439       // If we have an add, expand the add operands onto the end of the operands
2440       // list.
2441       Ops.erase(Ops.begin()+Idx);
2442       Ops.append(Add->op_begin(), Add->op_end());
2443       DeletedAdd = true;
2444     }
2445 
2446     // If we deleted at least one add, we added operands to the end of the list,
2447     // and they are not necessarily sorted.  Recurse to resort and resimplify
2448     // any operands we just acquired.
2449     if (DeletedAdd)
2450       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2451   }
2452 
2453   // Skip over the add expression until we get to a multiply.
2454   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2455     ++Idx;
2456 
2457   // Check to see if there are any folding opportunities present with
2458   // operands multiplied by constant values.
2459   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2460     uint64_t BitWidth = getTypeSizeInBits(Ty);
2461     DenseMap<const SCEV *, APInt> M;
2462     SmallVector<const SCEV *, 8> NewOps;
2463     APInt AccumulatedConstant(BitWidth, 0);
2464     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2465                                      Ops.data(), Ops.size(),
2466                                      APInt(BitWidth, 1), *this)) {
2467       struct APIntCompare {
2468         bool operator()(const APInt &LHS, const APInt &RHS) const {
2469           return LHS.ult(RHS);
2470         }
2471       };
2472 
2473       // Some interesting folding opportunity is present, so its worthwhile to
2474       // re-generate the operands list. Group the operands by constant scale,
2475       // to avoid multiplying by the same constant scale multiple times.
2476       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2477       for (const SCEV *NewOp : NewOps)
2478         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2479       // Re-generate the operands list.
2480       Ops.clear();
2481       if (AccumulatedConstant != 0)
2482         Ops.push_back(getConstant(AccumulatedConstant));
2483       for (auto &MulOp : MulOpLists)
2484         if (MulOp.first != 0)
2485           Ops.push_back(getMulExpr(
2486               getConstant(MulOp.first),
2487               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2488               SCEV::FlagAnyWrap, Depth + 1));
2489       if (Ops.empty())
2490         return getZero(Ty);
2491       if (Ops.size() == 1)
2492         return Ops[0];
2493       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2494     }
2495   }
2496 
2497   // If we are adding something to a multiply expression, make sure the
2498   // something is not already an operand of the multiply.  If so, merge it into
2499   // the multiply.
2500   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2501     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2502     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2503       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2504       if (isa<SCEVConstant>(MulOpSCEV))
2505         continue;
2506       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2507         if (MulOpSCEV == Ops[AddOp]) {
2508           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2509           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2510           if (Mul->getNumOperands() != 2) {
2511             // If the multiply has more than two operands, we must get the
2512             // Y*Z term.
2513             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2514                                                 Mul->op_begin()+MulOp);
2515             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2516             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2517           }
2518           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2519           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2520           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2521                                             SCEV::FlagAnyWrap, Depth + 1);
2522           if (Ops.size() == 2) return OuterMul;
2523           if (AddOp < Idx) {
2524             Ops.erase(Ops.begin()+AddOp);
2525             Ops.erase(Ops.begin()+Idx-1);
2526           } else {
2527             Ops.erase(Ops.begin()+Idx);
2528             Ops.erase(Ops.begin()+AddOp-1);
2529           }
2530           Ops.push_back(OuterMul);
2531           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2532         }
2533 
2534       // Check this multiply against other multiplies being added together.
2535       for (unsigned OtherMulIdx = Idx+1;
2536            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2537            ++OtherMulIdx) {
2538         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2539         // If MulOp occurs in OtherMul, we can fold the two multiplies
2540         // together.
2541         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2542              OMulOp != e; ++OMulOp)
2543           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2544             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2545             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2546             if (Mul->getNumOperands() != 2) {
2547               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2548                                                   Mul->op_begin()+MulOp);
2549               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2550               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2551             }
2552             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2553             if (OtherMul->getNumOperands() != 2) {
2554               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2555                                                   OtherMul->op_begin()+OMulOp);
2556               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2557               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2558             }
2559             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2560             const SCEV *InnerMulSum =
2561                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2562             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2563                                               SCEV::FlagAnyWrap, Depth + 1);
2564             if (Ops.size() == 2) return OuterMul;
2565             Ops.erase(Ops.begin()+Idx);
2566             Ops.erase(Ops.begin()+OtherMulIdx-1);
2567             Ops.push_back(OuterMul);
2568             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2569           }
2570       }
2571     }
2572   }
2573 
2574   // If there are any add recurrences in the operands list, see if any other
2575   // added values are loop invariant.  If so, we can fold them into the
2576   // recurrence.
2577   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2578     ++Idx;
2579 
2580   // Scan over all recurrences, trying to fold loop invariants into them.
2581   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2582     // Scan all of the other operands to this add and add them to the vector if
2583     // they are loop invariant w.r.t. the recurrence.
2584     SmallVector<const SCEV *, 8> LIOps;
2585     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2586     const Loop *AddRecLoop = AddRec->getLoop();
2587     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2588       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2589         LIOps.push_back(Ops[i]);
2590         Ops.erase(Ops.begin()+i);
2591         --i; --e;
2592       }
2593 
2594     // If we found some loop invariants, fold them into the recurrence.
2595     if (!LIOps.empty()) {
2596       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2597       LIOps.push_back(AddRec->getStart());
2598 
2599       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2600                                              AddRec->op_end());
2601       // This follows from the fact that the no-wrap flags on the outer add
2602       // expression are applicable on the 0th iteration, when the add recurrence
2603       // will be equal to its start value.
2604       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2605 
2606       // Build the new addrec. Propagate the NUW and NSW flags if both the
2607       // outer add and the inner addrec are guaranteed to have no overflow.
2608       // Always propagate NW.
2609       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2610       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2611 
2612       // If all of the other operands were loop invariant, we are done.
2613       if (Ops.size() == 1) return NewRec;
2614 
2615       // Otherwise, add the folded AddRec by the non-invariant parts.
2616       for (unsigned i = 0;; ++i)
2617         if (Ops[i] == AddRec) {
2618           Ops[i] = NewRec;
2619           break;
2620         }
2621       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2622     }
2623 
2624     // Okay, if there weren't any loop invariants to be folded, check to see if
2625     // there are multiple AddRec's with the same loop induction variable being
2626     // added together.  If so, we can fold them.
2627     for (unsigned OtherIdx = Idx+1;
2628          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2629          ++OtherIdx) {
2630       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2631       // so that the 1st found AddRecExpr is dominated by all others.
2632       assert(DT.dominates(
2633            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2634            AddRec->getLoop()->getHeader()) &&
2635         "AddRecExprs are not sorted in reverse dominance order?");
2636       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2637         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2638         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2639                                                AddRec->op_end());
2640         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2641              ++OtherIdx) {
2642           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2643           if (OtherAddRec->getLoop() == AddRecLoop) {
2644             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2645                  i != e; ++i) {
2646               if (i >= AddRecOps.size()) {
2647                 AddRecOps.append(OtherAddRec->op_begin()+i,
2648                                  OtherAddRec->op_end());
2649                 break;
2650               }
2651               SmallVector<const SCEV *, 2> TwoOps = {
2652                   AddRecOps[i], OtherAddRec->getOperand(i)};
2653               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2654             }
2655             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2656           }
2657         }
2658         // Step size has changed, so we cannot guarantee no self-wraparound.
2659         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2660         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2661       }
2662     }
2663 
2664     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2665     // next one.
2666   }
2667 
2668   // Okay, it looks like we really DO need an add expr.  Check to see if we
2669   // already have one, otherwise create a new one.
2670   return getOrCreateAddExpr(Ops, Flags);
2671 }
2672 
2673 const SCEV *
2674 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2675                                     SCEV::NoWrapFlags Flags) {
2676   FoldingSetNodeID ID;
2677   ID.AddInteger(scAddExpr);
2678   for (const SCEV *Op : Ops)
2679     ID.AddPointer(Op);
2680   void *IP = nullptr;
2681   SCEVAddExpr *S =
2682       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2683   if (!S) {
2684     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2685     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2686     S = new (SCEVAllocator)
2687         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2688     UniqueSCEVs.InsertNode(S, IP);
2689     addToLoopUseLists(S);
2690   }
2691   S->setNoWrapFlags(Flags);
2692   return S;
2693 }
2694 
2695 const SCEV *
2696 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2697                                     SCEV::NoWrapFlags Flags) {
2698   FoldingSetNodeID ID;
2699   ID.AddInteger(scMulExpr);
2700   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2701     ID.AddPointer(Ops[i]);
2702   void *IP = nullptr;
2703   SCEVMulExpr *S =
2704     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2705   if (!S) {
2706     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2707     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2708     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2709                                         O, Ops.size());
2710     UniqueSCEVs.InsertNode(S, IP);
2711     addToLoopUseLists(S);
2712   }
2713   S->setNoWrapFlags(Flags);
2714   return S;
2715 }
2716 
2717 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2718   uint64_t k = i*j;
2719   if (j > 1 && k / j != i) Overflow = true;
2720   return k;
2721 }
2722 
2723 /// Compute the result of "n choose k", the binomial coefficient.  If an
2724 /// intermediate computation overflows, Overflow will be set and the return will
2725 /// be garbage. Overflow is not cleared on absence of overflow.
2726 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2727   // We use the multiplicative formula:
2728   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2729   // At each iteration, we take the n-th term of the numeral and divide by the
2730   // (k-n)th term of the denominator.  This division will always produce an
2731   // integral result, and helps reduce the chance of overflow in the
2732   // intermediate computations. However, we can still overflow even when the
2733   // final result would fit.
2734 
2735   if (n == 0 || n == k) return 1;
2736   if (k > n) return 0;
2737 
2738   if (k > n/2)
2739     k = n-k;
2740 
2741   uint64_t r = 1;
2742   for (uint64_t i = 1; i <= k; ++i) {
2743     r = umul_ov(r, n-(i-1), Overflow);
2744     r /= i;
2745   }
2746   return r;
2747 }
2748 
2749 /// Determine if any of the operands in this SCEV are a constant or if
2750 /// any of the add or multiply expressions in this SCEV contain a constant.
2751 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2752   struct FindConstantInAddMulChain {
2753     bool FoundConstant = false;
2754 
2755     bool follow(const SCEV *S) {
2756       FoundConstant |= isa<SCEVConstant>(S);
2757       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2758     }
2759 
2760     bool isDone() const {
2761       return FoundConstant;
2762     }
2763   };
2764 
2765   FindConstantInAddMulChain F;
2766   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2767   ST.visitAll(StartExpr);
2768   return F.FoundConstant;
2769 }
2770 
2771 /// Get a canonical multiply expression, or something simpler if possible.
2772 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2773                                         SCEV::NoWrapFlags Flags,
2774                                         unsigned Depth) {
2775   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2776          "only nuw or nsw allowed");
2777   assert(!Ops.empty() && "Cannot get empty mul!");
2778   if (Ops.size() == 1) return Ops[0];
2779 #ifndef NDEBUG
2780   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2781   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2782     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2783            "SCEVMulExpr operand types don't match!");
2784 #endif
2785 
2786   // Sort by complexity, this groups all similar expression types together.
2787   GroupByComplexity(Ops, &LI, DT);
2788 
2789   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2790 
2791   // Limit recursion calls depth.
2792   if (Depth > MaxArithDepth)
2793     return getOrCreateMulExpr(Ops, Flags);
2794 
2795   // If there are any constants, fold them together.
2796   unsigned Idx = 0;
2797   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2798 
2799     // C1*(C2+V) -> C1*C2 + C1*V
2800     if (Ops.size() == 2)
2801         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2802           // If any of Add's ops are Adds or Muls with a constant,
2803           // apply this transformation as well.
2804           if (Add->getNumOperands() == 2)
2805             // TODO: There are some cases where this transformation is not
2806             // profitable, for example:
2807             // Add = (C0 + X) * Y + Z.
2808             // Maybe the scope of this transformation should be narrowed down.
2809             if (containsConstantInAddMulChain(Add))
2810               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2811                                            SCEV::FlagAnyWrap, Depth + 1),
2812                                 getMulExpr(LHSC, Add->getOperand(1),
2813                                            SCEV::FlagAnyWrap, Depth + 1),
2814                                 SCEV::FlagAnyWrap, Depth + 1);
2815 
2816     ++Idx;
2817     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2818       // We found two constants, fold them together!
2819       ConstantInt *Fold =
2820           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2821       Ops[0] = getConstant(Fold);
2822       Ops.erase(Ops.begin()+1);  // Erase the folded element
2823       if (Ops.size() == 1) return Ops[0];
2824       LHSC = cast<SCEVConstant>(Ops[0]);
2825     }
2826 
2827     // If we are left with a constant one being multiplied, strip it off.
2828     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2829       Ops.erase(Ops.begin());
2830       --Idx;
2831     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2832       // If we have a multiply of zero, it will always be zero.
2833       return Ops[0];
2834     } else if (Ops[0]->isAllOnesValue()) {
2835       // If we have a mul by -1 of an add, try distributing the -1 among the
2836       // add operands.
2837       if (Ops.size() == 2) {
2838         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2839           SmallVector<const SCEV *, 4> NewOps;
2840           bool AnyFolded = false;
2841           for (const SCEV *AddOp : Add->operands()) {
2842             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2843                                          Depth + 1);
2844             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2845             NewOps.push_back(Mul);
2846           }
2847           if (AnyFolded)
2848             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2849         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2850           // Negation preserves a recurrence's no self-wrap property.
2851           SmallVector<const SCEV *, 4> Operands;
2852           for (const SCEV *AddRecOp : AddRec->operands())
2853             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2854                                           Depth + 1));
2855 
2856           return getAddRecExpr(Operands, AddRec->getLoop(),
2857                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2858         }
2859       }
2860     }
2861 
2862     if (Ops.size() == 1)
2863       return Ops[0];
2864   }
2865 
2866   // Skip over the add expression until we get to a multiply.
2867   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2868     ++Idx;
2869 
2870   // If there are mul operands inline them all into this expression.
2871   if (Idx < Ops.size()) {
2872     bool DeletedMul = false;
2873     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2874       if (Ops.size() > MulOpsInlineThreshold)
2875         break;
2876       // If we have an mul, expand the mul operands onto the end of the
2877       // operands list.
2878       Ops.erase(Ops.begin()+Idx);
2879       Ops.append(Mul->op_begin(), Mul->op_end());
2880       DeletedMul = true;
2881     }
2882 
2883     // If we deleted at least one mul, we added operands to the end of the
2884     // list, and they are not necessarily sorted.  Recurse to resort and
2885     // resimplify any operands we just acquired.
2886     if (DeletedMul)
2887       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2888   }
2889 
2890   // If there are any add recurrences in the operands list, see if any other
2891   // added values are loop invariant.  If so, we can fold them into the
2892   // recurrence.
2893   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2894     ++Idx;
2895 
2896   // Scan over all recurrences, trying to fold loop invariants into them.
2897   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2898     // Scan all of the other operands to this mul and add them to the vector
2899     // if they are loop invariant w.r.t. the recurrence.
2900     SmallVector<const SCEV *, 8> LIOps;
2901     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2902     const Loop *AddRecLoop = AddRec->getLoop();
2903     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2904       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2905         LIOps.push_back(Ops[i]);
2906         Ops.erase(Ops.begin()+i);
2907         --i; --e;
2908       }
2909 
2910     // If we found some loop invariants, fold them into the recurrence.
2911     if (!LIOps.empty()) {
2912       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2913       SmallVector<const SCEV *, 4> NewOps;
2914       NewOps.reserve(AddRec->getNumOperands());
2915       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2916       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2917         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2918                                     SCEV::FlagAnyWrap, Depth + 1));
2919 
2920       // Build the new addrec. Propagate the NUW and NSW flags if both the
2921       // outer mul and the inner addrec are guaranteed to have no overflow.
2922       //
2923       // No self-wrap cannot be guaranteed after changing the step size, but
2924       // will be inferred if either NUW or NSW is true.
2925       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2926       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2927 
2928       // If all of the other operands were loop invariant, we are done.
2929       if (Ops.size() == 1) return NewRec;
2930 
2931       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2932       for (unsigned i = 0;; ++i)
2933         if (Ops[i] == AddRec) {
2934           Ops[i] = NewRec;
2935           break;
2936         }
2937       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2938     }
2939 
2940     // Okay, if there weren't any loop invariants to be folded, check to see
2941     // if there are multiple AddRec's with the same loop induction variable
2942     // being multiplied together.  If so, we can fold them.
2943 
2944     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2945     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2946     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2947     //   ]]],+,...up to x=2n}.
2948     // Note that the arguments to choose() are always integers with values
2949     // known at compile time, never SCEV objects.
2950     //
2951     // The implementation avoids pointless extra computations when the two
2952     // addrec's are of different length (mathematically, it's equivalent to
2953     // an infinite stream of zeros on the right).
2954     bool OpsModified = false;
2955     for (unsigned OtherIdx = Idx+1;
2956          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2957          ++OtherIdx) {
2958       const SCEVAddRecExpr *OtherAddRec =
2959         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2960       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2961         continue;
2962 
2963       // Limit max number of arguments to avoid creation of unreasonably big
2964       // SCEVAddRecs with very complex operands.
2965       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2966           MaxAddRecSize)
2967         continue;
2968 
2969       bool Overflow = false;
2970       Type *Ty = AddRec->getType();
2971       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2972       SmallVector<const SCEV*, 7> AddRecOps;
2973       for (int x = 0, xe = AddRec->getNumOperands() +
2974              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2975         const SCEV *Term = getZero(Ty);
2976         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2977           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2978           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2979                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2980                z < ze && !Overflow; ++z) {
2981             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2982             uint64_t Coeff;
2983             if (LargerThan64Bits)
2984               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2985             else
2986               Coeff = Coeff1*Coeff2;
2987             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2988             const SCEV *Term1 = AddRec->getOperand(y-z);
2989             const SCEV *Term2 = OtherAddRec->getOperand(z);
2990             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2991                                                SCEV::FlagAnyWrap, Depth + 1),
2992                               SCEV::FlagAnyWrap, Depth + 1);
2993           }
2994         }
2995         AddRecOps.push_back(Term);
2996       }
2997       if (!Overflow) {
2998         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2999                                               SCEV::FlagAnyWrap);
3000         if (Ops.size() == 2) return NewAddRec;
3001         Ops[Idx] = NewAddRec;
3002         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3003         OpsModified = true;
3004         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3005         if (!AddRec)
3006           break;
3007       }
3008     }
3009     if (OpsModified)
3010       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3011 
3012     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3013     // next one.
3014   }
3015 
3016   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3017   // already have one, otherwise create a new one.
3018   return getOrCreateMulExpr(Ops, Flags);
3019 }
3020 
3021 /// Represents an unsigned remainder expression based on unsigned division.
3022 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3023                                          const SCEV *RHS) {
3024   assert(getEffectiveSCEVType(LHS->getType()) ==
3025          getEffectiveSCEVType(RHS->getType()) &&
3026          "SCEVURemExpr operand types don't match!");
3027 
3028   // Short-circuit easy cases
3029   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3030     // If constant is one, the result is trivial
3031     if (RHSC->getValue()->isOne())
3032       return getZero(LHS->getType()); // X urem 1 --> 0
3033 
3034     // If constant is a power of two, fold into a zext(trunc(LHS)).
3035     if (RHSC->getAPInt().isPowerOf2()) {
3036       Type *FullTy = LHS->getType();
3037       Type *TruncTy =
3038           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3039       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3040     }
3041   }
3042 
3043   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3044   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3045   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3046   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3047 }
3048 
3049 /// Get a canonical unsigned division expression, or something simpler if
3050 /// possible.
3051 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3052                                          const SCEV *RHS) {
3053   assert(getEffectiveSCEVType(LHS->getType()) ==
3054          getEffectiveSCEVType(RHS->getType()) &&
3055          "SCEVUDivExpr operand types don't match!");
3056 
3057   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3058     if (RHSC->getValue()->isOne())
3059       return LHS;                               // X udiv 1 --> x
3060     // If the denominator is zero, the result of the udiv is undefined. Don't
3061     // try to analyze it, because the resolution chosen here may differ from
3062     // the resolution chosen in other parts of the compiler.
3063     if (!RHSC->getValue()->isZero()) {
3064       // Determine if the division can be folded into the operands of
3065       // its operands.
3066       // TODO: Generalize this to non-constants by using known-bits information.
3067       Type *Ty = LHS->getType();
3068       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3069       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3070       // For non-power-of-two values, effectively round the value up to the
3071       // nearest power of two.
3072       if (!RHSC->getAPInt().isPowerOf2())
3073         ++MaxShiftAmt;
3074       IntegerType *ExtTy =
3075         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3076       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3077         if (const SCEVConstant *Step =
3078             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3079           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3080           const APInt &StepInt = Step->getAPInt();
3081           const APInt &DivInt = RHSC->getAPInt();
3082           if (!StepInt.urem(DivInt) &&
3083               getZeroExtendExpr(AR, ExtTy) ==
3084               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3085                             getZeroExtendExpr(Step, ExtTy),
3086                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3087             SmallVector<const SCEV *, 4> Operands;
3088             for (const SCEV *Op : AR->operands())
3089               Operands.push_back(getUDivExpr(Op, RHS));
3090             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3091           }
3092           /// Get a canonical UDivExpr for a recurrence.
3093           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3094           // We can currently only fold X%N if X is constant.
3095           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3096           if (StartC && !DivInt.urem(StepInt) &&
3097               getZeroExtendExpr(AR, ExtTy) ==
3098               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3099                             getZeroExtendExpr(Step, ExtTy),
3100                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3101             const APInt &StartInt = StartC->getAPInt();
3102             const APInt &StartRem = StartInt.urem(StepInt);
3103             if (StartRem != 0)
3104               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3105                                   AR->getLoop(), SCEV::FlagNW);
3106           }
3107         }
3108       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3109       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3110         SmallVector<const SCEV *, 4> Operands;
3111         for (const SCEV *Op : M->operands())
3112           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3113         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3114           // Find an operand that's safely divisible.
3115           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3116             const SCEV *Op = M->getOperand(i);
3117             const SCEV *Div = getUDivExpr(Op, RHSC);
3118             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3119               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3120                                                       M->op_end());
3121               Operands[i] = Div;
3122               return getMulExpr(Operands);
3123             }
3124           }
3125       }
3126       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3127       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3128         SmallVector<const SCEV *, 4> Operands;
3129         for (const SCEV *Op : A->operands())
3130           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3131         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3132           Operands.clear();
3133           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3134             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3135             if (isa<SCEVUDivExpr>(Op) ||
3136                 getMulExpr(Op, RHS) != A->getOperand(i))
3137               break;
3138             Operands.push_back(Op);
3139           }
3140           if (Operands.size() == A->getNumOperands())
3141             return getAddExpr(Operands);
3142         }
3143       }
3144 
3145       // Fold if both operands are constant.
3146       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3147         Constant *LHSCV = LHSC->getValue();
3148         Constant *RHSCV = RHSC->getValue();
3149         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3150                                                                    RHSCV)));
3151       }
3152     }
3153   }
3154 
3155   FoldingSetNodeID ID;
3156   ID.AddInteger(scUDivExpr);
3157   ID.AddPointer(LHS);
3158   ID.AddPointer(RHS);
3159   void *IP = nullptr;
3160   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3161   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3162                                              LHS, RHS);
3163   UniqueSCEVs.InsertNode(S, IP);
3164   addToLoopUseLists(S);
3165   return S;
3166 }
3167 
3168 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3169   APInt A = C1->getAPInt().abs();
3170   APInt B = C2->getAPInt().abs();
3171   uint32_t ABW = A.getBitWidth();
3172   uint32_t BBW = B.getBitWidth();
3173 
3174   if (ABW > BBW)
3175     B = B.zext(ABW);
3176   else if (ABW < BBW)
3177     A = A.zext(BBW);
3178 
3179   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3180 }
3181 
3182 /// Get a canonical unsigned division expression, or something simpler if
3183 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3184 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3185 /// it's not exact because the udiv may be clearing bits.
3186 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3187                                               const SCEV *RHS) {
3188   // TODO: we could try to find factors in all sorts of things, but for now we
3189   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3190   // end of this file for inspiration.
3191 
3192   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3193   if (!Mul || !Mul->hasNoUnsignedWrap())
3194     return getUDivExpr(LHS, RHS);
3195 
3196   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3197     // If the mulexpr multiplies by a constant, then that constant must be the
3198     // first element of the mulexpr.
3199     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3200       if (LHSCst == RHSCst) {
3201         SmallVector<const SCEV *, 2> Operands;
3202         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3203         return getMulExpr(Operands);
3204       }
3205 
3206       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3207       // that there's a factor provided by one of the other terms. We need to
3208       // check.
3209       APInt Factor = gcd(LHSCst, RHSCst);
3210       if (!Factor.isIntN(1)) {
3211         LHSCst =
3212             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3213         RHSCst =
3214             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3215         SmallVector<const SCEV *, 2> Operands;
3216         Operands.push_back(LHSCst);
3217         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3218         LHS = getMulExpr(Operands);
3219         RHS = RHSCst;
3220         Mul = dyn_cast<SCEVMulExpr>(LHS);
3221         if (!Mul)
3222           return getUDivExactExpr(LHS, RHS);
3223       }
3224     }
3225   }
3226 
3227   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3228     if (Mul->getOperand(i) == RHS) {
3229       SmallVector<const SCEV *, 2> Operands;
3230       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3231       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3232       return getMulExpr(Operands);
3233     }
3234   }
3235 
3236   return getUDivExpr(LHS, RHS);
3237 }
3238 
3239 /// Get an add recurrence expression for the specified loop.  Simplify the
3240 /// expression as much as possible.
3241 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3242                                            const Loop *L,
3243                                            SCEV::NoWrapFlags Flags) {
3244   SmallVector<const SCEV *, 4> Operands;
3245   Operands.push_back(Start);
3246   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3247     if (StepChrec->getLoop() == L) {
3248       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3249       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3250     }
3251 
3252   Operands.push_back(Step);
3253   return getAddRecExpr(Operands, L, Flags);
3254 }
3255 
3256 /// Get an add recurrence expression for the specified loop.  Simplify the
3257 /// expression as much as possible.
3258 const SCEV *
3259 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3260                                const Loop *L, SCEV::NoWrapFlags Flags) {
3261   if (Operands.size() == 1) return Operands[0];
3262 #ifndef NDEBUG
3263   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3264   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3265     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3266            "SCEVAddRecExpr operand types don't match!");
3267   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3268     assert(isLoopInvariant(Operands[i], L) &&
3269            "SCEVAddRecExpr operand is not loop-invariant!");
3270 #endif
3271 
3272   if (Operands.back()->isZero()) {
3273     Operands.pop_back();
3274     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3275   }
3276 
3277   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3278   // use that information to infer NUW and NSW flags. However, computing a
3279   // BE count requires calling getAddRecExpr, so we may not yet have a
3280   // meaningful BE count at this point (and if we don't, we'd be stuck
3281   // with a SCEVCouldNotCompute as the cached BE count).
3282 
3283   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3284 
3285   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3286   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3287     const Loop *NestedLoop = NestedAR->getLoop();
3288     if (L->contains(NestedLoop)
3289             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3290             : (!NestedLoop->contains(L) &&
3291                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3292       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3293                                                   NestedAR->op_end());
3294       Operands[0] = NestedAR->getStart();
3295       // AddRecs require their operands be loop-invariant with respect to their
3296       // loops. Don't perform this transformation if it would break this
3297       // requirement.
3298       bool AllInvariant = all_of(
3299           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3300 
3301       if (AllInvariant) {
3302         // Create a recurrence for the outer loop with the same step size.
3303         //
3304         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3305         // inner recurrence has the same property.
3306         SCEV::NoWrapFlags OuterFlags =
3307           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3308 
3309         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3310         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3311           return isLoopInvariant(Op, NestedLoop);
3312         });
3313 
3314         if (AllInvariant) {
3315           // Ok, both add recurrences are valid after the transformation.
3316           //
3317           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3318           // the outer recurrence has the same property.
3319           SCEV::NoWrapFlags InnerFlags =
3320             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3321           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3322         }
3323       }
3324       // Reset Operands to its original state.
3325       Operands[0] = NestedAR;
3326     }
3327   }
3328 
3329   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3330   // already have one, otherwise create a new one.
3331   FoldingSetNodeID ID;
3332   ID.AddInteger(scAddRecExpr);
3333   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3334     ID.AddPointer(Operands[i]);
3335   ID.AddPointer(L);
3336   void *IP = nullptr;
3337   SCEVAddRecExpr *S =
3338     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3339   if (!S) {
3340     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3341     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3342     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3343                                            O, Operands.size(), L);
3344     UniqueSCEVs.InsertNode(S, IP);
3345     addToLoopUseLists(S);
3346   }
3347   S->setNoWrapFlags(Flags);
3348   return S;
3349 }
3350 
3351 const SCEV *
3352 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3353                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3354   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3355   // getSCEV(Base)->getType() has the same address space as Base->getType()
3356   // because SCEV::getType() preserves the address space.
3357   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3358   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3359   // instruction to its SCEV, because the Instruction may be guarded by control
3360   // flow and the no-overflow bits may not be valid for the expression in any
3361   // context. This can be fixed similarly to how these flags are handled for
3362   // adds.
3363   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3364                                              : SCEV::FlagAnyWrap;
3365 
3366   const SCEV *TotalOffset = getZero(IntPtrTy);
3367   // The array size is unimportant. The first thing we do on CurTy is getting
3368   // its element type.
3369   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3370   for (const SCEV *IndexExpr : IndexExprs) {
3371     // Compute the (potentially symbolic) offset in bytes for this index.
3372     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3373       // For a struct, add the member offset.
3374       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3375       unsigned FieldNo = Index->getZExtValue();
3376       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3377 
3378       // Add the field offset to the running total offset.
3379       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3380 
3381       // Update CurTy to the type of the field at Index.
3382       CurTy = STy->getTypeAtIndex(Index);
3383     } else {
3384       // Update CurTy to its element type.
3385       CurTy = cast<SequentialType>(CurTy)->getElementType();
3386       // For an array, add the element offset, explicitly scaled.
3387       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3388       // Getelementptr indices are signed.
3389       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3390 
3391       // Multiply the index by the element size to compute the element offset.
3392       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3393 
3394       // Add the element offset to the running total offset.
3395       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3396     }
3397   }
3398 
3399   // Add the total offset from all the GEP indices to the base.
3400   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3401 }
3402 
3403 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3404                                          const SCEV *RHS) {
3405   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3406   return getSMaxExpr(Ops);
3407 }
3408 
3409 const SCEV *
3410 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3411   assert(!Ops.empty() && "Cannot get empty smax!");
3412   if (Ops.size() == 1) return Ops[0];
3413 #ifndef NDEBUG
3414   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3415   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3416     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3417            "SCEVSMaxExpr operand types don't match!");
3418 #endif
3419 
3420   // Sort by complexity, this groups all similar expression types together.
3421   GroupByComplexity(Ops, &LI, DT);
3422 
3423   // If there are any constants, fold them together.
3424   unsigned Idx = 0;
3425   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3426     ++Idx;
3427     assert(Idx < Ops.size());
3428     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3429       // We found two constants, fold them together!
3430       ConstantInt *Fold = ConstantInt::get(
3431           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3432       Ops[0] = getConstant(Fold);
3433       Ops.erase(Ops.begin()+1);  // Erase the folded element
3434       if (Ops.size() == 1) return Ops[0];
3435       LHSC = cast<SCEVConstant>(Ops[0]);
3436     }
3437 
3438     // If we are left with a constant minimum-int, strip it off.
3439     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3440       Ops.erase(Ops.begin());
3441       --Idx;
3442     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3443       // If we have an smax with a constant maximum-int, it will always be
3444       // maximum-int.
3445       return Ops[0];
3446     }
3447 
3448     if (Ops.size() == 1) return Ops[0];
3449   }
3450 
3451   // Find the first SMax
3452   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3453     ++Idx;
3454 
3455   // Check to see if one of the operands is an SMax. If so, expand its operands
3456   // onto our operand list, and recurse to simplify.
3457   if (Idx < Ops.size()) {
3458     bool DeletedSMax = false;
3459     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3460       Ops.erase(Ops.begin()+Idx);
3461       Ops.append(SMax->op_begin(), SMax->op_end());
3462       DeletedSMax = true;
3463     }
3464 
3465     if (DeletedSMax)
3466       return getSMaxExpr(Ops);
3467   }
3468 
3469   // Okay, check to see if the same value occurs in the operand list twice.  If
3470   // so, delete one.  Since we sorted the list, these values are required to
3471   // be adjacent.
3472   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3473     //  X smax Y smax Y  -->  X smax Y
3474     //  X smax Y         -->  X, if X is always greater than Y
3475     if (Ops[i] == Ops[i+1] ||
3476         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3477       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3478       --i; --e;
3479     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3480       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3481       --i; --e;
3482     }
3483 
3484   if (Ops.size() == 1) return Ops[0];
3485 
3486   assert(!Ops.empty() && "Reduced smax down to nothing!");
3487 
3488   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3489   // already have one, otherwise create a new one.
3490   FoldingSetNodeID ID;
3491   ID.AddInteger(scSMaxExpr);
3492   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3493     ID.AddPointer(Ops[i]);
3494   void *IP = nullptr;
3495   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3496   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3497   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3498   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3499                                              O, Ops.size());
3500   UniqueSCEVs.InsertNode(S, IP);
3501   addToLoopUseLists(S);
3502   return S;
3503 }
3504 
3505 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3506                                          const SCEV *RHS) {
3507   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3508   return getUMaxExpr(Ops);
3509 }
3510 
3511 const SCEV *
3512 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3513   assert(!Ops.empty() && "Cannot get empty umax!");
3514   if (Ops.size() == 1) return Ops[0];
3515 #ifndef NDEBUG
3516   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3517   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3518     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3519            "SCEVUMaxExpr operand types don't match!");
3520 #endif
3521 
3522   // Sort by complexity, this groups all similar expression types together.
3523   GroupByComplexity(Ops, &LI, DT);
3524 
3525   // If there are any constants, fold them together.
3526   unsigned Idx = 0;
3527   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3528     ++Idx;
3529     assert(Idx < Ops.size());
3530     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3531       // We found two constants, fold them together!
3532       ConstantInt *Fold = ConstantInt::get(
3533           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3534       Ops[0] = getConstant(Fold);
3535       Ops.erase(Ops.begin()+1);  // Erase the folded element
3536       if (Ops.size() == 1) return Ops[0];
3537       LHSC = cast<SCEVConstant>(Ops[0]);
3538     }
3539 
3540     // If we are left with a constant minimum-int, strip it off.
3541     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3542       Ops.erase(Ops.begin());
3543       --Idx;
3544     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3545       // If we have an umax with a constant maximum-int, it will always be
3546       // maximum-int.
3547       return Ops[0];
3548     }
3549 
3550     if (Ops.size() == 1) return Ops[0];
3551   }
3552 
3553   // Find the first UMax
3554   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3555     ++Idx;
3556 
3557   // Check to see if one of the operands is a UMax. If so, expand its operands
3558   // onto our operand list, and recurse to simplify.
3559   if (Idx < Ops.size()) {
3560     bool DeletedUMax = false;
3561     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3562       Ops.erase(Ops.begin()+Idx);
3563       Ops.append(UMax->op_begin(), UMax->op_end());
3564       DeletedUMax = true;
3565     }
3566 
3567     if (DeletedUMax)
3568       return getUMaxExpr(Ops);
3569   }
3570 
3571   // Okay, check to see if the same value occurs in the operand list twice.  If
3572   // so, delete one.  Since we sorted the list, these values are required to
3573   // be adjacent.
3574   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3575     //  X umax Y umax Y  -->  X umax Y
3576     //  X umax Y         -->  X, if X is always greater than Y
3577     if (Ops[i] == Ops[i+1] ||
3578         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3579       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3580       --i; --e;
3581     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3582       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3583       --i; --e;
3584     }
3585 
3586   if (Ops.size() == 1) return Ops[0];
3587 
3588   assert(!Ops.empty() && "Reduced umax down to nothing!");
3589 
3590   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3591   // already have one, otherwise create a new one.
3592   FoldingSetNodeID ID;
3593   ID.AddInteger(scUMaxExpr);
3594   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3595     ID.AddPointer(Ops[i]);
3596   void *IP = nullptr;
3597   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3598   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3599   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3600   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3601                                              O, Ops.size());
3602   UniqueSCEVs.InsertNode(S, IP);
3603   addToLoopUseLists(S);
3604   return S;
3605 }
3606 
3607 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3608                                          const SCEV *RHS) {
3609   // ~smax(~x, ~y) == smin(x, y).
3610   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3611 }
3612 
3613 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3614                                          const SCEV *RHS) {
3615   // ~umax(~x, ~y) == umin(x, y)
3616   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3617 }
3618 
3619 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3620   // We can bypass creating a target-independent
3621   // constant expression and then folding it back into a ConstantInt.
3622   // This is just a compile-time optimization.
3623   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3624 }
3625 
3626 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3627                                              StructType *STy,
3628                                              unsigned FieldNo) {
3629   // We can bypass creating a target-independent
3630   // constant expression and then folding it back into a ConstantInt.
3631   // This is just a compile-time optimization.
3632   return getConstant(
3633       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3634 }
3635 
3636 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3637   // Don't attempt to do anything other than create a SCEVUnknown object
3638   // here.  createSCEV only calls getUnknown after checking for all other
3639   // interesting possibilities, and any other code that calls getUnknown
3640   // is doing so in order to hide a value from SCEV canonicalization.
3641 
3642   FoldingSetNodeID ID;
3643   ID.AddInteger(scUnknown);
3644   ID.AddPointer(V);
3645   void *IP = nullptr;
3646   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3647     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3648            "Stale SCEVUnknown in uniquing map!");
3649     return S;
3650   }
3651   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3652                                             FirstUnknown);
3653   FirstUnknown = cast<SCEVUnknown>(S);
3654   UniqueSCEVs.InsertNode(S, IP);
3655   return S;
3656 }
3657 
3658 //===----------------------------------------------------------------------===//
3659 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3660 //
3661 
3662 /// Test if values of the given type are analyzable within the SCEV
3663 /// framework. This primarily includes integer types, and it can optionally
3664 /// include pointer types if the ScalarEvolution class has access to
3665 /// target-specific information.
3666 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3667   // Integers and pointers are always SCEVable.
3668   return Ty->isIntegerTy() || Ty->isPointerTy();
3669 }
3670 
3671 /// Return the size in bits of the specified type, for which isSCEVable must
3672 /// return true.
3673 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3674   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3675   if (Ty->isPointerTy())
3676     return getDataLayout().getIndexTypeSizeInBits(Ty);
3677   return getDataLayout().getTypeSizeInBits(Ty);
3678 }
3679 
3680 /// Return a type with the same bitwidth as the given type and which represents
3681 /// how SCEV will treat the given type, for which isSCEVable must return
3682 /// true. For pointer types, this is the pointer-sized integer type.
3683 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3684   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3685 
3686   if (Ty->isIntegerTy())
3687     return Ty;
3688 
3689   // The only other support type is pointer.
3690   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3691   return getDataLayout().getIntPtrType(Ty);
3692 }
3693 
3694 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3695   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3696 }
3697 
3698 const SCEV *ScalarEvolution::getCouldNotCompute() {
3699   return CouldNotCompute.get();
3700 }
3701 
3702 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3703   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3704     auto *SU = dyn_cast<SCEVUnknown>(S);
3705     return SU && SU->getValue() == nullptr;
3706   });
3707 
3708   return !ContainsNulls;
3709 }
3710 
3711 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3712   HasRecMapType::iterator I = HasRecMap.find(S);
3713   if (I != HasRecMap.end())
3714     return I->second;
3715 
3716   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3717   HasRecMap.insert({S, FoundAddRec});
3718   return FoundAddRec;
3719 }
3720 
3721 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3722 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3723 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3724 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3725   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3726   if (!Add)
3727     return {S, nullptr};
3728 
3729   if (Add->getNumOperands() != 2)
3730     return {S, nullptr};
3731 
3732   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3733   if (!ConstOp)
3734     return {S, nullptr};
3735 
3736   return {Add->getOperand(1), ConstOp->getValue()};
3737 }
3738 
3739 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3740 /// by the value and offset from any ValueOffsetPair in the set.
3741 SetVector<ScalarEvolution::ValueOffsetPair> *
3742 ScalarEvolution::getSCEVValues(const SCEV *S) {
3743   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3744   if (SI == ExprValueMap.end())
3745     return nullptr;
3746 #ifndef NDEBUG
3747   if (VerifySCEVMap) {
3748     // Check there is no dangling Value in the set returned.
3749     for (const auto &VE : SI->second)
3750       assert(ValueExprMap.count(VE.first));
3751   }
3752 #endif
3753   return &SI->second;
3754 }
3755 
3756 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3757 /// cannot be used separately. eraseValueFromMap should be used to remove
3758 /// V from ValueExprMap and ExprValueMap at the same time.
3759 void ScalarEvolution::eraseValueFromMap(Value *V) {
3760   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3761   if (I != ValueExprMap.end()) {
3762     const SCEV *S = I->second;
3763     // Remove {V, 0} from the set of ExprValueMap[S]
3764     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3765       SV->remove({V, nullptr});
3766 
3767     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3768     const SCEV *Stripped;
3769     ConstantInt *Offset;
3770     std::tie(Stripped, Offset) = splitAddExpr(S);
3771     if (Offset != nullptr) {
3772       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3773         SV->remove({V, Offset});
3774     }
3775     ValueExprMap.erase(V);
3776   }
3777 }
3778 
3779 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3780 /// TODO: In reality it is better to check the poison recursevely
3781 /// but this is better than nothing.
3782 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3783   if (auto *I = dyn_cast<Instruction>(V)) {
3784     if (isa<OverflowingBinaryOperator>(I)) {
3785       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3786         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3787           return true;
3788         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3789           return true;
3790       }
3791     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3792       return true;
3793   }
3794   return false;
3795 }
3796 
3797 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3798 /// create a new one.
3799 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3800   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3801 
3802   const SCEV *S = getExistingSCEV(V);
3803   if (S == nullptr) {
3804     S = createSCEV(V);
3805     // During PHI resolution, it is possible to create two SCEVs for the same
3806     // V, so it is needed to double check whether V->S is inserted into
3807     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3808     std::pair<ValueExprMapType::iterator, bool> Pair =
3809         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3810     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3811       ExprValueMap[S].insert({V, nullptr});
3812 
3813       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3814       // ExprValueMap.
3815       const SCEV *Stripped = S;
3816       ConstantInt *Offset = nullptr;
3817       std::tie(Stripped, Offset) = splitAddExpr(S);
3818       // If stripped is SCEVUnknown, don't bother to save
3819       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3820       // increase the complexity of the expansion code.
3821       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3822       // because it may generate add/sub instead of GEP in SCEV expansion.
3823       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3824           !isa<GetElementPtrInst>(V))
3825         ExprValueMap[Stripped].insert({V, Offset});
3826     }
3827   }
3828   return S;
3829 }
3830 
3831 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3832   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3833 
3834   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3835   if (I != ValueExprMap.end()) {
3836     const SCEV *S = I->second;
3837     if (checkValidity(S))
3838       return S;
3839     eraseValueFromMap(V);
3840     forgetMemoizedResults(S);
3841   }
3842   return nullptr;
3843 }
3844 
3845 /// Return a SCEV corresponding to -V = -1*V
3846 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3847                                              SCEV::NoWrapFlags Flags) {
3848   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3849     return getConstant(
3850                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3851 
3852   Type *Ty = V->getType();
3853   Ty = getEffectiveSCEVType(Ty);
3854   return getMulExpr(
3855       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3856 }
3857 
3858 /// Return a SCEV corresponding to ~V = -1-V
3859 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3860   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3861     return getConstant(
3862                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3863 
3864   Type *Ty = V->getType();
3865   Ty = getEffectiveSCEVType(Ty);
3866   const SCEV *AllOnes =
3867                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3868   return getMinusSCEV(AllOnes, V);
3869 }
3870 
3871 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3872                                           SCEV::NoWrapFlags Flags,
3873                                           unsigned Depth) {
3874   // Fast path: X - X --> 0.
3875   if (LHS == RHS)
3876     return getZero(LHS->getType());
3877 
3878   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3879   // makes it so that we cannot make much use of NUW.
3880   auto AddFlags = SCEV::FlagAnyWrap;
3881   const bool RHSIsNotMinSigned =
3882       !getSignedRangeMin(RHS).isMinSignedValue();
3883   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3884     // Let M be the minimum representable signed value. Then (-1)*RHS
3885     // signed-wraps if and only if RHS is M. That can happen even for
3886     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3887     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3888     // (-1)*RHS, we need to prove that RHS != M.
3889     //
3890     // If LHS is non-negative and we know that LHS - RHS does not
3891     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3892     // either by proving that RHS > M or that LHS >= 0.
3893     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3894       AddFlags = SCEV::FlagNSW;
3895     }
3896   }
3897 
3898   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3899   // RHS is NSW and LHS >= 0.
3900   //
3901   // The difficulty here is that the NSW flag may have been proven
3902   // relative to a loop that is to be found in a recurrence in LHS and
3903   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3904   // larger scope than intended.
3905   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3906 
3907   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3908 }
3909 
3910 const SCEV *
3911 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3912   Type *SrcTy = V->getType();
3913   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3914          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3915          "Cannot truncate or zero extend with non-integer arguments!");
3916   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3917     return V;  // No conversion
3918   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3919     return getTruncateExpr(V, Ty);
3920   return getZeroExtendExpr(V, Ty);
3921 }
3922 
3923 const SCEV *
3924 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3925                                          Type *Ty) {
3926   Type *SrcTy = V->getType();
3927   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3928          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3929          "Cannot truncate or zero extend with non-integer arguments!");
3930   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3931     return V;  // No conversion
3932   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3933     return getTruncateExpr(V, Ty);
3934   return getSignExtendExpr(V, Ty);
3935 }
3936 
3937 const SCEV *
3938 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3939   Type *SrcTy = V->getType();
3940   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3941          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3942          "Cannot noop or zero extend with non-integer arguments!");
3943   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3944          "getNoopOrZeroExtend cannot truncate!");
3945   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3946     return V;  // No conversion
3947   return getZeroExtendExpr(V, Ty);
3948 }
3949 
3950 const SCEV *
3951 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3952   Type *SrcTy = V->getType();
3953   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3954          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3955          "Cannot noop or sign extend with non-integer arguments!");
3956   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3957          "getNoopOrSignExtend cannot truncate!");
3958   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3959     return V;  // No conversion
3960   return getSignExtendExpr(V, Ty);
3961 }
3962 
3963 const SCEV *
3964 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3965   Type *SrcTy = V->getType();
3966   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3967          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3968          "Cannot noop or any extend with non-integer arguments!");
3969   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3970          "getNoopOrAnyExtend cannot truncate!");
3971   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3972     return V;  // No conversion
3973   return getAnyExtendExpr(V, Ty);
3974 }
3975 
3976 const SCEV *
3977 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3978   Type *SrcTy = V->getType();
3979   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3980          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3981          "Cannot truncate or noop with non-integer arguments!");
3982   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3983          "getTruncateOrNoop cannot extend!");
3984   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3985     return V;  // No conversion
3986   return getTruncateExpr(V, Ty);
3987 }
3988 
3989 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3990                                                         const SCEV *RHS) {
3991   const SCEV *PromotedLHS = LHS;
3992   const SCEV *PromotedRHS = RHS;
3993 
3994   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3995     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3996   else
3997     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3998 
3999   return getUMaxExpr(PromotedLHS, PromotedRHS);
4000 }
4001 
4002 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4003                                                         const SCEV *RHS) {
4004   const SCEV *PromotedLHS = LHS;
4005   const SCEV *PromotedRHS = RHS;
4006 
4007   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4008     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4009   else
4010     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4011 
4012   return getUMinExpr(PromotedLHS, PromotedRHS);
4013 }
4014 
4015 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4016   // A pointer operand may evaluate to a nonpointer expression, such as null.
4017   if (!V->getType()->isPointerTy())
4018     return V;
4019 
4020   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4021     return getPointerBase(Cast->getOperand());
4022   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4023     const SCEV *PtrOp = nullptr;
4024     for (const SCEV *NAryOp : NAry->operands()) {
4025       if (NAryOp->getType()->isPointerTy()) {
4026         // Cannot find the base of an expression with multiple pointer operands.
4027         if (PtrOp)
4028           return V;
4029         PtrOp = NAryOp;
4030       }
4031     }
4032     if (!PtrOp)
4033       return V;
4034     return getPointerBase(PtrOp);
4035   }
4036   return V;
4037 }
4038 
4039 /// Push users of the given Instruction onto the given Worklist.
4040 static void
4041 PushDefUseChildren(Instruction *I,
4042                    SmallVectorImpl<Instruction *> &Worklist) {
4043   // Push the def-use children onto the Worklist stack.
4044   for (User *U : I->users())
4045     Worklist.push_back(cast<Instruction>(U));
4046 }
4047 
4048 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4049   SmallVector<Instruction *, 16> Worklist;
4050   PushDefUseChildren(PN, Worklist);
4051 
4052   SmallPtrSet<Instruction *, 8> Visited;
4053   Visited.insert(PN);
4054   while (!Worklist.empty()) {
4055     Instruction *I = Worklist.pop_back_val();
4056     if (!Visited.insert(I).second)
4057       continue;
4058 
4059     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4060     if (It != ValueExprMap.end()) {
4061       const SCEV *Old = It->second;
4062 
4063       // Short-circuit the def-use traversal if the symbolic name
4064       // ceases to appear in expressions.
4065       if (Old != SymName && !hasOperand(Old, SymName))
4066         continue;
4067 
4068       // SCEVUnknown for a PHI either means that it has an unrecognized
4069       // structure, it's a PHI that's in the progress of being computed
4070       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4071       // additional loop trip count information isn't going to change anything.
4072       // In the second case, createNodeForPHI will perform the necessary
4073       // updates on its own when it gets to that point. In the third, we do
4074       // want to forget the SCEVUnknown.
4075       if (!isa<PHINode>(I) ||
4076           !isa<SCEVUnknown>(Old) ||
4077           (I != PN && Old == SymName)) {
4078         eraseValueFromMap(It->first);
4079         forgetMemoizedResults(Old);
4080       }
4081     }
4082 
4083     PushDefUseChildren(I, Worklist);
4084   }
4085 }
4086 
4087 namespace {
4088 
4089 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4090 public:
4091   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4092                              ScalarEvolution &SE) {
4093     SCEVInitRewriter Rewriter(L, SE);
4094     const SCEV *Result = Rewriter.visit(S);
4095     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4096   }
4097 
4098   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4099     if (!SE.isLoopInvariant(Expr, L))
4100       Valid = false;
4101     return Expr;
4102   }
4103 
4104   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4105     // Only allow AddRecExprs for this loop.
4106     if (Expr->getLoop() == L)
4107       return Expr->getStart();
4108     Valid = false;
4109     return Expr;
4110   }
4111 
4112   bool isValid() { return Valid; }
4113 
4114 private:
4115   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4116       : SCEVRewriteVisitor(SE), L(L) {}
4117 
4118   const Loop *L;
4119   bool Valid = true;
4120 };
4121 
4122 /// This class evaluates the compare condition by matching it against the
4123 /// condition of loop latch. If there is a match we assume a true value
4124 /// for the condition while building SCEV nodes.
4125 class SCEVBackedgeConditionFolder
4126     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4127 public:
4128   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4129                              ScalarEvolution &SE) {
4130     bool IsPosBECond = false;
4131     Value *BECond = nullptr;
4132     if (BasicBlock *Latch = L->getLoopLatch()) {
4133       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4134       if (BI && BI->isConditional()) {
4135         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4136                "Both outgoing branches should not target same header!");
4137         BECond = BI->getCondition();
4138         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4139       } else {
4140         return S;
4141       }
4142     }
4143     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4144     return Rewriter.visit(S);
4145   }
4146 
4147   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4148     const SCEV *Result = Expr;
4149     bool InvariantF = SE.isLoopInvariant(Expr, L);
4150 
4151     if (!InvariantF) {
4152       Instruction *I = cast<Instruction>(Expr->getValue());
4153       switch (I->getOpcode()) {
4154       case Instruction::Select: {
4155         SelectInst *SI = cast<SelectInst>(I);
4156         Optional<const SCEV *> Res =
4157             compareWithBackedgeCondition(SI->getCondition());
4158         if (Res.hasValue()) {
4159           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4160           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4161         }
4162         break;
4163       }
4164       default: {
4165         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4166         if (Res.hasValue())
4167           Result = Res.getValue();
4168         break;
4169       }
4170       }
4171     }
4172     return Result;
4173   }
4174 
4175 private:
4176   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4177                                        bool IsPosBECond, ScalarEvolution &SE)
4178       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4179         IsPositiveBECond(IsPosBECond) {}
4180 
4181   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4182 
4183   const Loop *L;
4184   /// Loop back condition.
4185   Value *BackedgeCond = nullptr;
4186   /// Set to true if loop back is on positive branch condition.
4187   bool IsPositiveBECond;
4188 };
4189 
4190 Optional<const SCEV *>
4191 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4192 
4193   // If value matches the backedge condition for loop latch,
4194   // then return a constant evolution node based on loopback
4195   // branch taken.
4196   if (BackedgeCond == IC)
4197     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4198                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4199   return None;
4200 }
4201 
4202 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4203 public:
4204   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4205                              ScalarEvolution &SE) {
4206     SCEVShiftRewriter Rewriter(L, SE);
4207     const SCEV *Result = Rewriter.visit(S);
4208     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4209   }
4210 
4211   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4212     // Only allow AddRecExprs for this loop.
4213     if (!SE.isLoopInvariant(Expr, L))
4214       Valid = false;
4215     return Expr;
4216   }
4217 
4218   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4219     if (Expr->getLoop() == L && Expr->isAffine())
4220       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4221     Valid = false;
4222     return Expr;
4223   }
4224 
4225   bool isValid() { return Valid; }
4226 
4227 private:
4228   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4229       : SCEVRewriteVisitor(SE), L(L) {}
4230 
4231   const Loop *L;
4232   bool Valid = true;
4233 };
4234 
4235 } // end anonymous namespace
4236 
4237 SCEV::NoWrapFlags
4238 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4239   if (!AR->isAffine())
4240     return SCEV::FlagAnyWrap;
4241 
4242   using OBO = OverflowingBinaryOperator;
4243 
4244   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4245 
4246   if (!AR->hasNoSignedWrap()) {
4247     ConstantRange AddRecRange = getSignedRange(AR);
4248     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4249 
4250     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4251         Instruction::Add, IncRange, OBO::NoSignedWrap);
4252     if (NSWRegion.contains(AddRecRange))
4253       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4254   }
4255 
4256   if (!AR->hasNoUnsignedWrap()) {
4257     ConstantRange AddRecRange = getUnsignedRange(AR);
4258     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4259 
4260     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4261         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4262     if (NUWRegion.contains(AddRecRange))
4263       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4264   }
4265 
4266   return Result;
4267 }
4268 
4269 namespace {
4270 
4271 /// Represents an abstract binary operation.  This may exist as a
4272 /// normal instruction or constant expression, or may have been
4273 /// derived from an expression tree.
4274 struct BinaryOp {
4275   unsigned Opcode;
4276   Value *LHS;
4277   Value *RHS;
4278   bool IsNSW = false;
4279   bool IsNUW = false;
4280 
4281   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4282   /// constant expression.
4283   Operator *Op = nullptr;
4284 
4285   explicit BinaryOp(Operator *Op)
4286       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4287         Op(Op) {
4288     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4289       IsNSW = OBO->hasNoSignedWrap();
4290       IsNUW = OBO->hasNoUnsignedWrap();
4291     }
4292   }
4293 
4294   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4295                     bool IsNUW = false)
4296       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4297 };
4298 
4299 } // end anonymous namespace
4300 
4301 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4302 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4303   auto *Op = dyn_cast<Operator>(V);
4304   if (!Op)
4305     return None;
4306 
4307   // Implementation detail: all the cleverness here should happen without
4308   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4309   // SCEV expressions when possible, and we should not break that.
4310 
4311   switch (Op->getOpcode()) {
4312   case Instruction::Add:
4313   case Instruction::Sub:
4314   case Instruction::Mul:
4315   case Instruction::UDiv:
4316   case Instruction::URem:
4317   case Instruction::And:
4318   case Instruction::Or:
4319   case Instruction::AShr:
4320   case Instruction::Shl:
4321     return BinaryOp(Op);
4322 
4323   case Instruction::Xor:
4324     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4325       // If the RHS of the xor is a signmask, then this is just an add.
4326       // Instcombine turns add of signmask into xor as a strength reduction step.
4327       if (RHSC->getValue().isSignMask())
4328         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4329     return BinaryOp(Op);
4330 
4331   case Instruction::LShr:
4332     // Turn logical shift right of a constant into a unsigned divide.
4333     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4334       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4335 
4336       // If the shift count is not less than the bitwidth, the result of
4337       // the shift is undefined. Don't try to analyze it, because the
4338       // resolution chosen here may differ from the resolution chosen in
4339       // other parts of the compiler.
4340       if (SA->getValue().ult(BitWidth)) {
4341         Constant *X =
4342             ConstantInt::get(SA->getContext(),
4343                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4344         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4345       }
4346     }
4347     return BinaryOp(Op);
4348 
4349   case Instruction::ExtractValue: {
4350     auto *EVI = cast<ExtractValueInst>(Op);
4351     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4352       break;
4353 
4354     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4355     if (!CI)
4356       break;
4357 
4358     if (auto *F = CI->getCalledFunction())
4359       switch (F->getIntrinsicID()) {
4360       case Intrinsic::sadd_with_overflow:
4361       case Intrinsic::uadd_with_overflow:
4362         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4363           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4364                           CI->getArgOperand(1));
4365 
4366         // Now that we know that all uses of the arithmetic-result component of
4367         // CI are guarded by the overflow check, we can go ahead and pretend
4368         // that the arithmetic is non-overflowing.
4369         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4370           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4371                           CI->getArgOperand(1), /* IsNSW = */ true,
4372                           /* IsNUW = */ false);
4373         else
4374           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4375                           CI->getArgOperand(1), /* IsNSW = */ false,
4376                           /* IsNUW*/ true);
4377       case Intrinsic::ssub_with_overflow:
4378       case Intrinsic::usub_with_overflow:
4379         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4380           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4381                           CI->getArgOperand(1));
4382 
4383         // The same reasoning as sadd/uadd above.
4384         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4385           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4386                           CI->getArgOperand(1), /* IsNSW = */ true,
4387                           /* IsNUW = */ false);
4388         else
4389           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4390                           CI->getArgOperand(1), /* IsNSW = */ false,
4391                           /* IsNUW = */ true);
4392       case Intrinsic::smul_with_overflow:
4393       case Intrinsic::umul_with_overflow:
4394         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4395                         CI->getArgOperand(1));
4396       default:
4397         break;
4398       }
4399     break;
4400   }
4401 
4402   default:
4403     break;
4404   }
4405 
4406   return None;
4407 }
4408 
4409 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4410 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4411 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4412 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4413 /// follows one of the following patterns:
4414 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4415 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4416 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4417 /// we return the type of the truncation operation, and indicate whether the
4418 /// truncated type should be treated as signed/unsigned by setting
4419 /// \p Signed to true/false, respectively.
4420 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4421                                bool &Signed, ScalarEvolution &SE) {
4422   // The case where Op == SymbolicPHI (that is, with no type conversions on
4423   // the way) is handled by the regular add recurrence creating logic and
4424   // would have already been triggered in createAddRecForPHI. Reaching it here
4425   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4426   // because one of the other operands of the SCEVAddExpr updating this PHI is
4427   // not invariant).
4428   //
4429   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4430   // this case predicates that allow us to prove that Op == SymbolicPHI will
4431   // be added.
4432   if (Op == SymbolicPHI)
4433     return nullptr;
4434 
4435   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4436   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4437   if (SourceBits != NewBits)
4438     return nullptr;
4439 
4440   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4441   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4442   if (!SExt && !ZExt)
4443     return nullptr;
4444   const SCEVTruncateExpr *Trunc =
4445       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4446            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4447   if (!Trunc)
4448     return nullptr;
4449   const SCEV *X = Trunc->getOperand();
4450   if (X != SymbolicPHI)
4451     return nullptr;
4452   Signed = SExt != nullptr;
4453   return Trunc->getType();
4454 }
4455 
4456 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4457   if (!PN->getType()->isIntegerTy())
4458     return nullptr;
4459   const Loop *L = LI.getLoopFor(PN->getParent());
4460   if (!L || L->getHeader() != PN->getParent())
4461     return nullptr;
4462   return L;
4463 }
4464 
4465 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4466 // computation that updates the phi follows the following pattern:
4467 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4468 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4469 // If so, try to see if it can be rewritten as an AddRecExpr under some
4470 // Predicates. If successful, return them as a pair. Also cache the results
4471 // of the analysis.
4472 //
4473 // Example usage scenario:
4474 //    Say the Rewriter is called for the following SCEV:
4475 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4476 //    where:
4477 //         %X = phi i64 (%Start, %BEValue)
4478 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4479 //    and call this function with %SymbolicPHI = %X.
4480 //
4481 //    The analysis will find that the value coming around the backedge has
4482 //    the following SCEV:
4483 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4484 //    Upon concluding that this matches the desired pattern, the function
4485 //    will return the pair {NewAddRec, SmallPredsVec} where:
4486 //         NewAddRec = {%Start,+,%Step}
4487 //         SmallPredsVec = {P1, P2, P3} as follows:
4488 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4489 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4490 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4491 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4492 //    under the predicates {P1,P2,P3}.
4493 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4494 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4495 //
4496 // TODO's:
4497 //
4498 // 1) Extend the Induction descriptor to also support inductions that involve
4499 //    casts: When needed (namely, when we are called in the context of the
4500 //    vectorizer induction analysis), a Set of cast instructions will be
4501 //    populated by this method, and provided back to isInductionPHI. This is
4502 //    needed to allow the vectorizer to properly record them to be ignored by
4503 //    the cost model and to avoid vectorizing them (otherwise these casts,
4504 //    which are redundant under the runtime overflow checks, will be
4505 //    vectorized, which can be costly).
4506 //
4507 // 2) Support additional induction/PHISCEV patterns: We also want to support
4508 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4509 //    after the induction update operation (the induction increment):
4510 //
4511 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4512 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4513 //
4514 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4515 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4516 //
4517 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4518 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4519 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4520   SmallVector<const SCEVPredicate *, 3> Predicates;
4521 
4522   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4523   // return an AddRec expression under some predicate.
4524 
4525   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4526   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4527   assert(L && "Expecting an integer loop header phi");
4528 
4529   // The loop may have multiple entrances or multiple exits; we can analyze
4530   // this phi as an addrec if it has a unique entry value and a unique
4531   // backedge value.
4532   Value *BEValueV = nullptr, *StartValueV = nullptr;
4533   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4534     Value *V = PN->getIncomingValue(i);
4535     if (L->contains(PN->getIncomingBlock(i))) {
4536       if (!BEValueV) {
4537         BEValueV = V;
4538       } else if (BEValueV != V) {
4539         BEValueV = nullptr;
4540         break;
4541       }
4542     } else if (!StartValueV) {
4543       StartValueV = V;
4544     } else if (StartValueV != V) {
4545       StartValueV = nullptr;
4546       break;
4547     }
4548   }
4549   if (!BEValueV || !StartValueV)
4550     return None;
4551 
4552   const SCEV *BEValue = getSCEV(BEValueV);
4553 
4554   // If the value coming around the backedge is an add with the symbolic
4555   // value we just inserted, possibly with casts that we can ignore under
4556   // an appropriate runtime guard, then we found a simple induction variable!
4557   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4558   if (!Add)
4559     return None;
4560 
4561   // If there is a single occurrence of the symbolic value, possibly
4562   // casted, replace it with a recurrence.
4563   unsigned FoundIndex = Add->getNumOperands();
4564   Type *TruncTy = nullptr;
4565   bool Signed;
4566   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4567     if ((TruncTy =
4568              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4569       if (FoundIndex == e) {
4570         FoundIndex = i;
4571         break;
4572       }
4573 
4574   if (FoundIndex == Add->getNumOperands())
4575     return None;
4576 
4577   // Create an add with everything but the specified operand.
4578   SmallVector<const SCEV *, 8> Ops;
4579   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4580     if (i != FoundIndex)
4581       Ops.push_back(Add->getOperand(i));
4582   const SCEV *Accum = getAddExpr(Ops);
4583 
4584   // The runtime checks will not be valid if the step amount is
4585   // varying inside the loop.
4586   if (!isLoopInvariant(Accum, L))
4587     return None;
4588 
4589   // *** Part2: Create the predicates
4590 
4591   // Analysis was successful: we have a phi-with-cast pattern for which we
4592   // can return an AddRec expression under the following predicates:
4593   //
4594   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4595   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4596   // P2: An Equal predicate that guarantees that
4597   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4598   // P3: An Equal predicate that guarantees that
4599   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4600   //
4601   // As we next prove, the above predicates guarantee that:
4602   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4603   //
4604   //
4605   // More formally, we want to prove that:
4606   //     Expr(i+1) = Start + (i+1) * Accum
4607   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4608   //
4609   // Given that:
4610   // 1) Expr(0) = Start
4611   // 2) Expr(1) = Start + Accum
4612   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4613   // 3) Induction hypothesis (step i):
4614   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4615   //
4616   // Proof:
4617   //  Expr(i+1) =
4618   //   = Start + (i+1)*Accum
4619   //   = (Start + i*Accum) + Accum
4620   //   = Expr(i) + Accum
4621   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4622   //                                                             :: from step i
4623   //
4624   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4625   //
4626   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4627   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4628   //     + Accum                                                     :: from P3
4629   //
4630   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4631   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4632   //
4633   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4634   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4635   //
4636   // By induction, the same applies to all iterations 1<=i<n:
4637   //
4638 
4639   // Create a truncated addrec for which we will add a no overflow check (P1).
4640   const SCEV *StartVal = getSCEV(StartValueV);
4641   const SCEV *PHISCEV =
4642       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4643                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4644 
4645   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4646   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4647   // will be constant.
4648   //
4649   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4650   // add P1.
4651   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4652     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4653         Signed ? SCEVWrapPredicate::IncrementNSSW
4654                : SCEVWrapPredicate::IncrementNUSW;
4655     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4656     Predicates.push_back(AddRecPred);
4657   }
4658 
4659   // Create the Equal Predicates P2,P3:
4660 
4661   // It is possible that the predicates P2 and/or P3 are computable at
4662   // compile time due to StartVal and/or Accum being constants.
4663   // If either one is, then we can check that now and escape if either P2
4664   // or P3 is false.
4665 
4666   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4667   // for each of StartVal and Accum
4668   auto getExtendedExpr = [&](const SCEV *Expr,
4669                              bool CreateSignExtend) -> const SCEV * {
4670     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4671     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4672     const SCEV *ExtendedExpr =
4673         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4674                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4675     return ExtendedExpr;
4676   };
4677 
4678   // Given:
4679   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4680   //               = getExtendedExpr(Expr)
4681   // Determine whether the predicate P: Expr == ExtendedExpr
4682   // is known to be false at compile time
4683   auto PredIsKnownFalse = [&](const SCEV *Expr,
4684                               const SCEV *ExtendedExpr) -> bool {
4685     return Expr != ExtendedExpr &&
4686            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4687   };
4688 
4689   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4690   if (PredIsKnownFalse(StartVal, StartExtended)) {
4691     DEBUG(dbgs() << "P2 is compile-time false\n";);
4692     return None;
4693   }
4694 
4695   // The Step is always Signed (because the overflow checks are either
4696   // NSSW or NUSW)
4697   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4698   if (PredIsKnownFalse(Accum, AccumExtended)) {
4699     DEBUG(dbgs() << "P3 is compile-time false\n";);
4700     return None;
4701   }
4702 
4703   auto AppendPredicate = [&](const SCEV *Expr,
4704                              const SCEV *ExtendedExpr) -> void {
4705     if (Expr != ExtendedExpr &&
4706         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4707       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4708       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4709       Predicates.push_back(Pred);
4710     }
4711   };
4712 
4713   AppendPredicate(StartVal, StartExtended);
4714   AppendPredicate(Accum, AccumExtended);
4715 
4716   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4717   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4718   // into NewAR if it will also add the runtime overflow checks specified in
4719   // Predicates.
4720   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4721 
4722   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4723       std::make_pair(NewAR, Predicates);
4724   // Remember the result of the analysis for this SCEV at this locayyytion.
4725   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4726   return PredRewrite;
4727 }
4728 
4729 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4730 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4731   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4732   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4733   if (!L)
4734     return None;
4735 
4736   // Check to see if we already analyzed this PHI.
4737   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4738   if (I != PredicatedSCEVRewrites.end()) {
4739     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4740         I->second;
4741     // Analysis was done before and failed to create an AddRec:
4742     if (Rewrite.first == SymbolicPHI)
4743       return None;
4744     // Analysis was done before and succeeded to create an AddRec under
4745     // a predicate:
4746     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4747     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4748     return Rewrite;
4749   }
4750 
4751   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4752     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4753 
4754   // Record in the cache that the analysis failed
4755   if (!Rewrite) {
4756     SmallVector<const SCEVPredicate *, 3> Predicates;
4757     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4758     return None;
4759   }
4760 
4761   return Rewrite;
4762 }
4763 
4764 // FIXME: This utility is currently required because the Rewriter currently
4765 // does not rewrite this expression:
4766 // {0, +, (sext ix (trunc iy to ix) to iy)}
4767 // into {0, +, %step},
4768 // even when the following Equal predicate exists:
4769 // "%step == (sext ix (trunc iy to ix) to iy)".
4770 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4771     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4772   if (AR1 == AR2)
4773     return true;
4774 
4775   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4776     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4777         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4778       return false;
4779     return true;
4780   };
4781 
4782   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4783       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4784     return false;
4785   return true;
4786 }
4787 
4788 /// A helper function for createAddRecFromPHI to handle simple cases.
4789 ///
4790 /// This function tries to find an AddRec expression for the simplest (yet most
4791 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4792 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4793 /// technique for finding the AddRec expression.
4794 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4795                                                       Value *BEValueV,
4796                                                       Value *StartValueV) {
4797   const Loop *L = LI.getLoopFor(PN->getParent());
4798   assert(L && L->getHeader() == PN->getParent());
4799   assert(BEValueV && StartValueV);
4800 
4801   auto BO = MatchBinaryOp(BEValueV, DT);
4802   if (!BO)
4803     return nullptr;
4804 
4805   if (BO->Opcode != Instruction::Add)
4806     return nullptr;
4807 
4808   const SCEV *Accum = nullptr;
4809   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4810     Accum = getSCEV(BO->RHS);
4811   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4812     Accum = getSCEV(BO->LHS);
4813 
4814   if (!Accum)
4815     return nullptr;
4816 
4817   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4818   if (BO->IsNUW)
4819     Flags = setFlags(Flags, SCEV::FlagNUW);
4820   if (BO->IsNSW)
4821     Flags = setFlags(Flags, SCEV::FlagNSW);
4822 
4823   const SCEV *StartVal = getSCEV(StartValueV);
4824   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4825 
4826   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4827 
4828   // We can add Flags to the post-inc expression only if we
4829   // know that it is *undefined behavior* for BEValueV to
4830   // overflow.
4831   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4832     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4833       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4834 
4835   return PHISCEV;
4836 }
4837 
4838 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4839   const Loop *L = LI.getLoopFor(PN->getParent());
4840   if (!L || L->getHeader() != PN->getParent())
4841     return nullptr;
4842 
4843   // The loop may have multiple entrances or multiple exits; we can analyze
4844   // this phi as an addrec if it has a unique entry value and a unique
4845   // backedge value.
4846   Value *BEValueV = nullptr, *StartValueV = nullptr;
4847   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4848     Value *V = PN->getIncomingValue(i);
4849     if (L->contains(PN->getIncomingBlock(i))) {
4850       if (!BEValueV) {
4851         BEValueV = V;
4852       } else if (BEValueV != V) {
4853         BEValueV = nullptr;
4854         break;
4855       }
4856     } else if (!StartValueV) {
4857       StartValueV = V;
4858     } else if (StartValueV != V) {
4859       StartValueV = nullptr;
4860       break;
4861     }
4862   }
4863   if (!BEValueV || !StartValueV)
4864     return nullptr;
4865 
4866   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4867          "PHI node already processed?");
4868 
4869   // First, try to find AddRec expression without creating a fictituos symbolic
4870   // value for PN.
4871   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4872     return S;
4873 
4874   // Handle PHI node value symbolically.
4875   const SCEV *SymbolicName = getUnknown(PN);
4876   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4877 
4878   // Using this symbolic name for the PHI, analyze the value coming around
4879   // the back-edge.
4880   const SCEV *BEValue = getSCEV(BEValueV);
4881 
4882   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4883   // has a special value for the first iteration of the loop.
4884 
4885   // If the value coming around the backedge is an add with the symbolic
4886   // value we just inserted, then we found a simple induction variable!
4887   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4888     // If there is a single occurrence of the symbolic value, replace it
4889     // with a recurrence.
4890     unsigned FoundIndex = Add->getNumOperands();
4891     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4892       if (Add->getOperand(i) == SymbolicName)
4893         if (FoundIndex == e) {
4894           FoundIndex = i;
4895           break;
4896         }
4897 
4898     if (FoundIndex != Add->getNumOperands()) {
4899       // Create an add with everything but the specified operand.
4900       SmallVector<const SCEV *, 8> Ops;
4901       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4902         if (i != FoundIndex)
4903           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4904                                                              L, *this));
4905       const SCEV *Accum = getAddExpr(Ops);
4906 
4907       // This is not a valid addrec if the step amount is varying each
4908       // loop iteration, but is not itself an addrec in this loop.
4909       if (isLoopInvariant(Accum, L) ||
4910           (isa<SCEVAddRecExpr>(Accum) &&
4911            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4912         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4913 
4914         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4915           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4916             if (BO->IsNUW)
4917               Flags = setFlags(Flags, SCEV::FlagNUW);
4918             if (BO->IsNSW)
4919               Flags = setFlags(Flags, SCEV::FlagNSW);
4920           }
4921         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4922           // If the increment is an inbounds GEP, then we know the address
4923           // space cannot be wrapped around. We cannot make any guarantee
4924           // about signed or unsigned overflow because pointers are
4925           // unsigned but we may have a negative index from the base
4926           // pointer. We can guarantee that no unsigned wrap occurs if the
4927           // indices form a positive value.
4928           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4929             Flags = setFlags(Flags, SCEV::FlagNW);
4930 
4931             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4932             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4933               Flags = setFlags(Flags, SCEV::FlagNUW);
4934           }
4935 
4936           // We cannot transfer nuw and nsw flags from subtraction
4937           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4938           // for instance.
4939         }
4940 
4941         const SCEV *StartVal = getSCEV(StartValueV);
4942         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4943 
4944         // Okay, for the entire analysis of this edge we assumed the PHI
4945         // to be symbolic.  We now need to go back and purge all of the
4946         // entries for the scalars that use the symbolic expression.
4947         forgetSymbolicName(PN, SymbolicName);
4948         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4949 
4950         // We can add Flags to the post-inc expression only if we
4951         // know that it is *undefined behavior* for BEValueV to
4952         // overflow.
4953         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4954           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4955             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4956 
4957         return PHISCEV;
4958       }
4959     }
4960   } else {
4961     // Otherwise, this could be a loop like this:
4962     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4963     // In this case, j = {1,+,1}  and BEValue is j.
4964     // Because the other in-value of i (0) fits the evolution of BEValue
4965     // i really is an addrec evolution.
4966     //
4967     // We can generalize this saying that i is the shifted value of BEValue
4968     // by one iteration:
4969     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4970     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4971     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4972     if (Shifted != getCouldNotCompute() &&
4973         Start != getCouldNotCompute()) {
4974       const SCEV *StartVal = getSCEV(StartValueV);
4975       if (Start == StartVal) {
4976         // Okay, for the entire analysis of this edge we assumed the PHI
4977         // to be symbolic.  We now need to go back and purge all of the
4978         // entries for the scalars that use the symbolic expression.
4979         forgetSymbolicName(PN, SymbolicName);
4980         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4981         return Shifted;
4982       }
4983     }
4984   }
4985 
4986   // Remove the temporary PHI node SCEV that has been inserted while intending
4987   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4988   // as it will prevent later (possibly simpler) SCEV expressions to be added
4989   // to the ValueExprMap.
4990   eraseValueFromMap(PN);
4991 
4992   return nullptr;
4993 }
4994 
4995 // Checks if the SCEV S is available at BB.  S is considered available at BB
4996 // if S can be materialized at BB without introducing a fault.
4997 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4998                                BasicBlock *BB) {
4999   struct CheckAvailable {
5000     bool TraversalDone = false;
5001     bool Available = true;
5002 
5003     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5004     BasicBlock *BB = nullptr;
5005     DominatorTree &DT;
5006 
5007     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5008       : L(L), BB(BB), DT(DT) {}
5009 
5010     bool setUnavailable() {
5011       TraversalDone = true;
5012       Available = false;
5013       return false;
5014     }
5015 
5016     bool follow(const SCEV *S) {
5017       switch (S->getSCEVType()) {
5018       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5019       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5020         // These expressions are available if their operand(s) is/are.
5021         return true;
5022 
5023       case scAddRecExpr: {
5024         // We allow add recurrences that are on the loop BB is in, or some
5025         // outer loop.  This guarantees availability because the value of the
5026         // add recurrence at BB is simply the "current" value of the induction
5027         // variable.  We can relax this in the future; for instance an add
5028         // recurrence on a sibling dominating loop is also available at BB.
5029         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5030         if (L && (ARLoop == L || ARLoop->contains(L)))
5031           return true;
5032 
5033         return setUnavailable();
5034       }
5035 
5036       case scUnknown: {
5037         // For SCEVUnknown, we check for simple dominance.
5038         const auto *SU = cast<SCEVUnknown>(S);
5039         Value *V = SU->getValue();
5040 
5041         if (isa<Argument>(V))
5042           return false;
5043 
5044         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5045           return false;
5046 
5047         return setUnavailable();
5048       }
5049 
5050       case scUDivExpr:
5051       case scCouldNotCompute:
5052         // We do not try to smart about these at all.
5053         return setUnavailable();
5054       }
5055       llvm_unreachable("switch should be fully covered!");
5056     }
5057 
5058     bool isDone() { return TraversalDone; }
5059   };
5060 
5061   CheckAvailable CA(L, BB, DT);
5062   SCEVTraversal<CheckAvailable> ST(CA);
5063 
5064   ST.visitAll(S);
5065   return CA.Available;
5066 }
5067 
5068 // Try to match a control flow sequence that branches out at BI and merges back
5069 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5070 // match.
5071 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5072                           Value *&C, Value *&LHS, Value *&RHS) {
5073   C = BI->getCondition();
5074 
5075   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5076   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5077 
5078   if (!LeftEdge.isSingleEdge())
5079     return false;
5080 
5081   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5082 
5083   Use &LeftUse = Merge->getOperandUse(0);
5084   Use &RightUse = Merge->getOperandUse(1);
5085 
5086   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5087     LHS = LeftUse;
5088     RHS = RightUse;
5089     return true;
5090   }
5091 
5092   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5093     LHS = RightUse;
5094     RHS = LeftUse;
5095     return true;
5096   }
5097 
5098   return false;
5099 }
5100 
5101 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5102   auto IsReachable =
5103       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5104   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5105     const Loop *L = LI.getLoopFor(PN->getParent());
5106 
5107     // We don't want to break LCSSA, even in a SCEV expression tree.
5108     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5109       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5110         return nullptr;
5111 
5112     // Try to match
5113     //
5114     //  br %cond, label %left, label %right
5115     // left:
5116     //  br label %merge
5117     // right:
5118     //  br label %merge
5119     // merge:
5120     //  V = phi [ %x, %left ], [ %y, %right ]
5121     //
5122     // as "select %cond, %x, %y"
5123 
5124     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5125     assert(IDom && "At least the entry block should dominate PN");
5126 
5127     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5128     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5129 
5130     if (BI && BI->isConditional() &&
5131         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5132         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5133         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5134       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5135   }
5136 
5137   return nullptr;
5138 }
5139 
5140 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5141   if (const SCEV *S = createAddRecFromPHI(PN))
5142     return S;
5143 
5144   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5145     return S;
5146 
5147   // If the PHI has a single incoming value, follow that value, unless the
5148   // PHI's incoming blocks are in a different loop, in which case doing so
5149   // risks breaking LCSSA form. Instcombine would normally zap these, but
5150   // it doesn't have DominatorTree information, so it may miss cases.
5151   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5152     if (LI.replacementPreservesLCSSAForm(PN, V))
5153       return getSCEV(V);
5154 
5155   // If it's not a loop phi, we can't handle it yet.
5156   return getUnknown(PN);
5157 }
5158 
5159 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5160                                                       Value *Cond,
5161                                                       Value *TrueVal,
5162                                                       Value *FalseVal) {
5163   // Handle "constant" branch or select. This can occur for instance when a
5164   // loop pass transforms an inner loop and moves on to process the outer loop.
5165   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5166     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5167 
5168   // Try to match some simple smax or umax patterns.
5169   auto *ICI = dyn_cast<ICmpInst>(Cond);
5170   if (!ICI)
5171     return getUnknown(I);
5172 
5173   Value *LHS = ICI->getOperand(0);
5174   Value *RHS = ICI->getOperand(1);
5175 
5176   switch (ICI->getPredicate()) {
5177   case ICmpInst::ICMP_SLT:
5178   case ICmpInst::ICMP_SLE:
5179     std::swap(LHS, RHS);
5180     LLVM_FALLTHROUGH;
5181   case ICmpInst::ICMP_SGT:
5182   case ICmpInst::ICMP_SGE:
5183     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5184     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5185     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5186       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5187       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5188       const SCEV *LA = getSCEV(TrueVal);
5189       const SCEV *RA = getSCEV(FalseVal);
5190       const SCEV *LDiff = getMinusSCEV(LA, LS);
5191       const SCEV *RDiff = getMinusSCEV(RA, RS);
5192       if (LDiff == RDiff)
5193         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5194       LDiff = getMinusSCEV(LA, RS);
5195       RDiff = getMinusSCEV(RA, LS);
5196       if (LDiff == RDiff)
5197         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5198     }
5199     break;
5200   case ICmpInst::ICMP_ULT:
5201   case ICmpInst::ICMP_ULE:
5202     std::swap(LHS, RHS);
5203     LLVM_FALLTHROUGH;
5204   case ICmpInst::ICMP_UGT:
5205   case ICmpInst::ICMP_UGE:
5206     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5207     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5208     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5209       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5210       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5211       const SCEV *LA = getSCEV(TrueVal);
5212       const SCEV *RA = getSCEV(FalseVal);
5213       const SCEV *LDiff = getMinusSCEV(LA, LS);
5214       const SCEV *RDiff = getMinusSCEV(RA, RS);
5215       if (LDiff == RDiff)
5216         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5217       LDiff = getMinusSCEV(LA, RS);
5218       RDiff = getMinusSCEV(RA, LS);
5219       if (LDiff == RDiff)
5220         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5221     }
5222     break;
5223   case ICmpInst::ICMP_NE:
5224     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5225     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5226         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5227       const SCEV *One = getOne(I->getType());
5228       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5229       const SCEV *LA = getSCEV(TrueVal);
5230       const SCEV *RA = getSCEV(FalseVal);
5231       const SCEV *LDiff = getMinusSCEV(LA, LS);
5232       const SCEV *RDiff = getMinusSCEV(RA, One);
5233       if (LDiff == RDiff)
5234         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5235     }
5236     break;
5237   case ICmpInst::ICMP_EQ:
5238     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5239     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5240         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5241       const SCEV *One = getOne(I->getType());
5242       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5243       const SCEV *LA = getSCEV(TrueVal);
5244       const SCEV *RA = getSCEV(FalseVal);
5245       const SCEV *LDiff = getMinusSCEV(LA, One);
5246       const SCEV *RDiff = getMinusSCEV(RA, LS);
5247       if (LDiff == RDiff)
5248         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5249     }
5250     break;
5251   default:
5252     break;
5253   }
5254 
5255   return getUnknown(I);
5256 }
5257 
5258 /// Expand GEP instructions into add and multiply operations. This allows them
5259 /// to be analyzed by regular SCEV code.
5260 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5261   // Don't attempt to analyze GEPs over unsized objects.
5262   if (!GEP->getSourceElementType()->isSized())
5263     return getUnknown(GEP);
5264 
5265   SmallVector<const SCEV *, 4> IndexExprs;
5266   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5267     IndexExprs.push_back(getSCEV(*Index));
5268   return getGEPExpr(GEP, IndexExprs);
5269 }
5270 
5271 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5272   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5273     return C->getAPInt().countTrailingZeros();
5274 
5275   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5276     return std::min(GetMinTrailingZeros(T->getOperand()),
5277                     (uint32_t)getTypeSizeInBits(T->getType()));
5278 
5279   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5280     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5281     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5282                ? getTypeSizeInBits(E->getType())
5283                : OpRes;
5284   }
5285 
5286   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5287     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5288     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5289                ? getTypeSizeInBits(E->getType())
5290                : OpRes;
5291   }
5292 
5293   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5294     // The result is the min of all operands results.
5295     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5296     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5297       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5298     return MinOpRes;
5299   }
5300 
5301   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5302     // The result is the sum of all operands results.
5303     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5304     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5305     for (unsigned i = 1, e = M->getNumOperands();
5306          SumOpRes != BitWidth && i != e; ++i)
5307       SumOpRes =
5308           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5309     return SumOpRes;
5310   }
5311 
5312   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5313     // The result is the min of all operands results.
5314     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5315     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5316       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5317     return MinOpRes;
5318   }
5319 
5320   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5321     // The result is the min of all operands results.
5322     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5323     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5324       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5325     return MinOpRes;
5326   }
5327 
5328   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5329     // The result is the min of all operands results.
5330     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5331     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5332       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5333     return MinOpRes;
5334   }
5335 
5336   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5337     // For a SCEVUnknown, ask ValueTracking.
5338     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5339     return Known.countMinTrailingZeros();
5340   }
5341 
5342   // SCEVUDivExpr
5343   return 0;
5344 }
5345 
5346 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5347   auto I = MinTrailingZerosCache.find(S);
5348   if (I != MinTrailingZerosCache.end())
5349     return I->second;
5350 
5351   uint32_t Result = GetMinTrailingZerosImpl(S);
5352   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5353   assert(InsertPair.second && "Should insert a new key");
5354   return InsertPair.first->second;
5355 }
5356 
5357 /// Helper method to assign a range to V from metadata present in the IR.
5358 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5359   if (Instruction *I = dyn_cast<Instruction>(V))
5360     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5361       return getConstantRangeFromMetadata(*MD);
5362 
5363   return None;
5364 }
5365 
5366 /// Determine the range for a particular SCEV.  If SignHint is
5367 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5368 /// with a "cleaner" unsigned (resp. signed) representation.
5369 const ConstantRange &
5370 ScalarEvolution::getRangeRef(const SCEV *S,
5371                              ScalarEvolution::RangeSignHint SignHint) {
5372   DenseMap<const SCEV *, ConstantRange> &Cache =
5373       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5374                                                        : SignedRanges;
5375 
5376   // See if we've computed this range already.
5377   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5378   if (I != Cache.end())
5379     return I->second;
5380 
5381   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5382     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5383 
5384   unsigned BitWidth = getTypeSizeInBits(S->getType());
5385   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5386 
5387   // If the value has known zeros, the maximum value will have those known zeros
5388   // as well.
5389   uint32_t TZ = GetMinTrailingZeros(S);
5390   if (TZ != 0) {
5391     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5392       ConservativeResult =
5393           ConstantRange(APInt::getMinValue(BitWidth),
5394                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5395     else
5396       ConservativeResult = ConstantRange(
5397           APInt::getSignedMinValue(BitWidth),
5398           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5399   }
5400 
5401   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5402     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5403     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5404       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5405     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5406   }
5407 
5408   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5409     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5410     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5411       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5412     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5413   }
5414 
5415   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5416     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5417     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5418       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5419     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5420   }
5421 
5422   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5423     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5424     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5425       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5426     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5427   }
5428 
5429   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5430     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5431     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5432     return setRange(UDiv, SignHint,
5433                     ConservativeResult.intersectWith(X.udiv(Y)));
5434   }
5435 
5436   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5437     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5438     return setRange(ZExt, SignHint,
5439                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5440   }
5441 
5442   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5443     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5444     return setRange(SExt, SignHint,
5445                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5446   }
5447 
5448   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5449     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5450     return setRange(Trunc, SignHint,
5451                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5452   }
5453 
5454   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5455     // If there's no unsigned wrap, the value will never be less than its
5456     // initial value.
5457     if (AddRec->hasNoUnsignedWrap())
5458       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5459         if (!C->getValue()->isZero())
5460           ConservativeResult = ConservativeResult.intersectWith(
5461               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5462 
5463     // If there's no signed wrap, and all the operands have the same sign or
5464     // zero, the value won't ever change sign.
5465     if (AddRec->hasNoSignedWrap()) {
5466       bool AllNonNeg = true;
5467       bool AllNonPos = true;
5468       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5469         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5470         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5471       }
5472       if (AllNonNeg)
5473         ConservativeResult = ConservativeResult.intersectWith(
5474           ConstantRange(APInt(BitWidth, 0),
5475                         APInt::getSignedMinValue(BitWidth)));
5476       else if (AllNonPos)
5477         ConservativeResult = ConservativeResult.intersectWith(
5478           ConstantRange(APInt::getSignedMinValue(BitWidth),
5479                         APInt(BitWidth, 1)));
5480     }
5481 
5482     // TODO: non-affine addrec
5483     if (AddRec->isAffine()) {
5484       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5485       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5486           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5487         auto RangeFromAffine = getRangeForAffineAR(
5488             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5489             BitWidth);
5490         if (!RangeFromAffine.isFullSet())
5491           ConservativeResult =
5492               ConservativeResult.intersectWith(RangeFromAffine);
5493 
5494         auto RangeFromFactoring = getRangeViaFactoring(
5495             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5496             BitWidth);
5497         if (!RangeFromFactoring.isFullSet())
5498           ConservativeResult =
5499               ConservativeResult.intersectWith(RangeFromFactoring);
5500       }
5501     }
5502 
5503     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5504   }
5505 
5506   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5507     // Check if the IR explicitly contains !range metadata.
5508     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5509     if (MDRange.hasValue())
5510       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5511 
5512     // Split here to avoid paying the compile-time cost of calling both
5513     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5514     // if needed.
5515     const DataLayout &DL = getDataLayout();
5516     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5517       // For a SCEVUnknown, ask ValueTracking.
5518       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5519       if (Known.One != ~Known.Zero + 1)
5520         ConservativeResult =
5521             ConservativeResult.intersectWith(ConstantRange(Known.One,
5522                                                            ~Known.Zero + 1));
5523     } else {
5524       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5525              "generalize as needed!");
5526       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5527       if (NS > 1)
5528         ConservativeResult = ConservativeResult.intersectWith(
5529             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5530                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5531     }
5532 
5533     return setRange(U, SignHint, std::move(ConservativeResult));
5534   }
5535 
5536   return setRange(S, SignHint, std::move(ConservativeResult));
5537 }
5538 
5539 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5540 // values that the expression can take. Initially, the expression has a value
5541 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5542 // argument defines if we treat Step as signed or unsigned.
5543 static ConstantRange getRangeForAffineARHelper(APInt Step,
5544                                                const ConstantRange &StartRange,
5545                                                const APInt &MaxBECount,
5546                                                unsigned BitWidth, bool Signed) {
5547   // If either Step or MaxBECount is 0, then the expression won't change, and we
5548   // just need to return the initial range.
5549   if (Step == 0 || MaxBECount == 0)
5550     return StartRange;
5551 
5552   // If we don't know anything about the initial value (i.e. StartRange is
5553   // FullRange), then we don't know anything about the final range either.
5554   // Return FullRange.
5555   if (StartRange.isFullSet())
5556     return ConstantRange(BitWidth, /* isFullSet = */ true);
5557 
5558   // If Step is signed and negative, then we use its absolute value, but we also
5559   // note that we're moving in the opposite direction.
5560   bool Descending = Signed && Step.isNegative();
5561 
5562   if (Signed)
5563     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5564     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5565     // This equations hold true due to the well-defined wrap-around behavior of
5566     // APInt.
5567     Step = Step.abs();
5568 
5569   // Check if Offset is more than full span of BitWidth. If it is, the
5570   // expression is guaranteed to overflow.
5571   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5572     return ConstantRange(BitWidth, /* isFullSet = */ true);
5573 
5574   // Offset is by how much the expression can change. Checks above guarantee no
5575   // overflow here.
5576   APInt Offset = Step * MaxBECount;
5577 
5578   // Minimum value of the final range will match the minimal value of StartRange
5579   // if the expression is increasing and will be decreased by Offset otherwise.
5580   // Maximum value of the final range will match the maximal value of StartRange
5581   // if the expression is decreasing and will be increased by Offset otherwise.
5582   APInt StartLower = StartRange.getLower();
5583   APInt StartUpper = StartRange.getUpper() - 1;
5584   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5585                                    : (StartUpper + std::move(Offset));
5586 
5587   // It's possible that the new minimum/maximum value will fall into the initial
5588   // range (due to wrap around). This means that the expression can take any
5589   // value in this bitwidth, and we have to return full range.
5590   if (StartRange.contains(MovedBoundary))
5591     return ConstantRange(BitWidth, /* isFullSet = */ true);
5592 
5593   APInt NewLower =
5594       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5595   APInt NewUpper =
5596       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5597   NewUpper += 1;
5598 
5599   // If we end up with full range, return a proper full range.
5600   if (NewLower == NewUpper)
5601     return ConstantRange(BitWidth, /* isFullSet = */ true);
5602 
5603   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5604   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5605 }
5606 
5607 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5608                                                    const SCEV *Step,
5609                                                    const SCEV *MaxBECount,
5610                                                    unsigned BitWidth) {
5611   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5612          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5613          "Precondition!");
5614 
5615   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5616   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5617 
5618   // First, consider step signed.
5619   ConstantRange StartSRange = getSignedRange(Start);
5620   ConstantRange StepSRange = getSignedRange(Step);
5621 
5622   // If Step can be both positive and negative, we need to find ranges for the
5623   // maximum absolute step values in both directions and union them.
5624   ConstantRange SR =
5625       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5626                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5627   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5628                                               StartSRange, MaxBECountValue,
5629                                               BitWidth, /* Signed = */ true));
5630 
5631   // Next, consider step unsigned.
5632   ConstantRange UR = getRangeForAffineARHelper(
5633       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5634       MaxBECountValue, BitWidth, /* Signed = */ false);
5635 
5636   // Finally, intersect signed and unsigned ranges.
5637   return SR.intersectWith(UR);
5638 }
5639 
5640 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5641                                                     const SCEV *Step,
5642                                                     const SCEV *MaxBECount,
5643                                                     unsigned BitWidth) {
5644   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5645   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5646 
5647   struct SelectPattern {
5648     Value *Condition = nullptr;
5649     APInt TrueValue;
5650     APInt FalseValue;
5651 
5652     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5653                            const SCEV *S) {
5654       Optional<unsigned> CastOp;
5655       APInt Offset(BitWidth, 0);
5656 
5657       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5658              "Should be!");
5659 
5660       // Peel off a constant offset:
5661       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5662         // In the future we could consider being smarter here and handle
5663         // {Start+Step,+,Step} too.
5664         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5665           return;
5666 
5667         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5668         S = SA->getOperand(1);
5669       }
5670 
5671       // Peel off a cast operation
5672       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5673         CastOp = SCast->getSCEVType();
5674         S = SCast->getOperand();
5675       }
5676 
5677       using namespace llvm::PatternMatch;
5678 
5679       auto *SU = dyn_cast<SCEVUnknown>(S);
5680       const APInt *TrueVal, *FalseVal;
5681       if (!SU ||
5682           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5683                                           m_APInt(FalseVal)))) {
5684         Condition = nullptr;
5685         return;
5686       }
5687 
5688       TrueValue = *TrueVal;
5689       FalseValue = *FalseVal;
5690 
5691       // Re-apply the cast we peeled off earlier
5692       if (CastOp.hasValue())
5693         switch (*CastOp) {
5694         default:
5695           llvm_unreachable("Unknown SCEV cast type!");
5696 
5697         case scTruncate:
5698           TrueValue = TrueValue.trunc(BitWidth);
5699           FalseValue = FalseValue.trunc(BitWidth);
5700           break;
5701         case scZeroExtend:
5702           TrueValue = TrueValue.zext(BitWidth);
5703           FalseValue = FalseValue.zext(BitWidth);
5704           break;
5705         case scSignExtend:
5706           TrueValue = TrueValue.sext(BitWidth);
5707           FalseValue = FalseValue.sext(BitWidth);
5708           break;
5709         }
5710 
5711       // Re-apply the constant offset we peeled off earlier
5712       TrueValue += Offset;
5713       FalseValue += Offset;
5714     }
5715 
5716     bool isRecognized() { return Condition != nullptr; }
5717   };
5718 
5719   SelectPattern StartPattern(*this, BitWidth, Start);
5720   if (!StartPattern.isRecognized())
5721     return ConstantRange(BitWidth, /* isFullSet = */ true);
5722 
5723   SelectPattern StepPattern(*this, BitWidth, Step);
5724   if (!StepPattern.isRecognized())
5725     return ConstantRange(BitWidth, /* isFullSet = */ true);
5726 
5727   if (StartPattern.Condition != StepPattern.Condition) {
5728     // We don't handle this case today; but we could, by considering four
5729     // possibilities below instead of two. I'm not sure if there are cases where
5730     // that will help over what getRange already does, though.
5731     return ConstantRange(BitWidth, /* isFullSet = */ true);
5732   }
5733 
5734   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5735   // construct arbitrary general SCEV expressions here.  This function is called
5736   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5737   // say) can end up caching a suboptimal value.
5738 
5739   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5740   // C2352 and C2512 (otherwise it isn't needed).
5741 
5742   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5743   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5744   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5745   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5746 
5747   ConstantRange TrueRange =
5748       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5749   ConstantRange FalseRange =
5750       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5751 
5752   return TrueRange.unionWith(FalseRange);
5753 }
5754 
5755 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5756   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5757   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5758 
5759   // Return early if there are no flags to propagate to the SCEV.
5760   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5761   if (BinOp->hasNoUnsignedWrap())
5762     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5763   if (BinOp->hasNoSignedWrap())
5764     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5765   if (Flags == SCEV::FlagAnyWrap)
5766     return SCEV::FlagAnyWrap;
5767 
5768   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5769 }
5770 
5771 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5772   // Here we check that I is in the header of the innermost loop containing I,
5773   // since we only deal with instructions in the loop header. The actual loop we
5774   // need to check later will come from an add recurrence, but getting that
5775   // requires computing the SCEV of the operands, which can be expensive. This
5776   // check we can do cheaply to rule out some cases early.
5777   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5778   if (InnermostContainingLoop == nullptr ||
5779       InnermostContainingLoop->getHeader() != I->getParent())
5780     return false;
5781 
5782   // Only proceed if we can prove that I does not yield poison.
5783   if (!programUndefinedIfFullPoison(I))
5784     return false;
5785 
5786   // At this point we know that if I is executed, then it does not wrap
5787   // according to at least one of NSW or NUW. If I is not executed, then we do
5788   // not know if the calculation that I represents would wrap. Multiple
5789   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5790   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5791   // derived from other instructions that map to the same SCEV. We cannot make
5792   // that guarantee for cases where I is not executed. So we need to find the
5793   // loop that I is considered in relation to and prove that I is executed for
5794   // every iteration of that loop. That implies that the value that I
5795   // calculates does not wrap anywhere in the loop, so then we can apply the
5796   // flags to the SCEV.
5797   //
5798   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5799   // from different loops, so that we know which loop to prove that I is
5800   // executed in.
5801   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5802     // I could be an extractvalue from a call to an overflow intrinsic.
5803     // TODO: We can do better here in some cases.
5804     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5805       return false;
5806     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5807     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5808       bool AllOtherOpsLoopInvariant = true;
5809       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5810            ++OtherOpIndex) {
5811         if (OtherOpIndex != OpIndex) {
5812           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5813           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5814             AllOtherOpsLoopInvariant = false;
5815             break;
5816           }
5817         }
5818       }
5819       if (AllOtherOpsLoopInvariant &&
5820           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5821         return true;
5822     }
5823   }
5824   return false;
5825 }
5826 
5827 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5828   // If we know that \c I can never be poison period, then that's enough.
5829   if (isSCEVExprNeverPoison(I))
5830     return true;
5831 
5832   // For an add recurrence specifically, we assume that infinite loops without
5833   // side effects are undefined behavior, and then reason as follows:
5834   //
5835   // If the add recurrence is poison in any iteration, it is poison on all
5836   // future iterations (since incrementing poison yields poison). If the result
5837   // of the add recurrence is fed into the loop latch condition and the loop
5838   // does not contain any throws or exiting blocks other than the latch, we now
5839   // have the ability to "choose" whether the backedge is taken or not (by
5840   // choosing a sufficiently evil value for the poison feeding into the branch)
5841   // for every iteration including and after the one in which \p I first became
5842   // poison.  There are two possibilities (let's call the iteration in which \p
5843   // I first became poison as K):
5844   //
5845   //  1. In the set of iterations including and after K, the loop body executes
5846   //     no side effects.  In this case executing the backege an infinte number
5847   //     of times will yield undefined behavior.
5848   //
5849   //  2. In the set of iterations including and after K, the loop body executes
5850   //     at least one side effect.  In this case, that specific instance of side
5851   //     effect is control dependent on poison, which also yields undefined
5852   //     behavior.
5853 
5854   auto *ExitingBB = L->getExitingBlock();
5855   auto *LatchBB = L->getLoopLatch();
5856   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5857     return false;
5858 
5859   SmallPtrSet<const Instruction *, 16> Pushed;
5860   SmallVector<const Instruction *, 8> PoisonStack;
5861 
5862   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5863   // things that are known to be fully poison under that assumption go on the
5864   // PoisonStack.
5865   Pushed.insert(I);
5866   PoisonStack.push_back(I);
5867 
5868   bool LatchControlDependentOnPoison = false;
5869   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5870     const Instruction *Poison = PoisonStack.pop_back_val();
5871 
5872     for (auto *PoisonUser : Poison->users()) {
5873       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5874         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5875           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5876       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5877         assert(BI->isConditional() && "Only possibility!");
5878         if (BI->getParent() == LatchBB) {
5879           LatchControlDependentOnPoison = true;
5880           break;
5881         }
5882       }
5883     }
5884   }
5885 
5886   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5887 }
5888 
5889 ScalarEvolution::LoopProperties
5890 ScalarEvolution::getLoopProperties(const Loop *L) {
5891   using LoopProperties = ScalarEvolution::LoopProperties;
5892 
5893   auto Itr = LoopPropertiesCache.find(L);
5894   if (Itr == LoopPropertiesCache.end()) {
5895     auto HasSideEffects = [](Instruction *I) {
5896       if (auto *SI = dyn_cast<StoreInst>(I))
5897         return !SI->isSimple();
5898 
5899       return I->mayHaveSideEffects();
5900     };
5901 
5902     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5903                          /*HasNoSideEffects*/ true};
5904 
5905     for (auto *BB : L->getBlocks())
5906       for (auto &I : *BB) {
5907         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5908           LP.HasNoAbnormalExits = false;
5909         if (HasSideEffects(&I))
5910           LP.HasNoSideEffects = false;
5911         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5912           break; // We're already as pessimistic as we can get.
5913       }
5914 
5915     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5916     assert(InsertPair.second && "We just checked!");
5917     Itr = InsertPair.first;
5918   }
5919 
5920   return Itr->second;
5921 }
5922 
5923 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5924   if (!isSCEVable(V->getType()))
5925     return getUnknown(V);
5926 
5927   if (Instruction *I = dyn_cast<Instruction>(V)) {
5928     // Don't attempt to analyze instructions in blocks that aren't
5929     // reachable. Such instructions don't matter, and they aren't required
5930     // to obey basic rules for definitions dominating uses which this
5931     // analysis depends on.
5932     if (!DT.isReachableFromEntry(I->getParent()))
5933       return getUnknown(V);
5934   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5935     return getConstant(CI);
5936   else if (isa<ConstantPointerNull>(V))
5937     return getZero(V->getType());
5938   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5939     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5940   else if (!isa<ConstantExpr>(V))
5941     return getUnknown(V);
5942 
5943   Operator *U = cast<Operator>(V);
5944   if (auto BO = MatchBinaryOp(U, DT)) {
5945     switch (BO->Opcode) {
5946     case Instruction::Add: {
5947       // The simple thing to do would be to just call getSCEV on both operands
5948       // and call getAddExpr with the result. However if we're looking at a
5949       // bunch of things all added together, this can be quite inefficient,
5950       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5951       // Instead, gather up all the operands and make a single getAddExpr call.
5952       // LLVM IR canonical form means we need only traverse the left operands.
5953       SmallVector<const SCEV *, 4> AddOps;
5954       do {
5955         if (BO->Op) {
5956           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5957             AddOps.push_back(OpSCEV);
5958             break;
5959           }
5960 
5961           // If a NUW or NSW flag can be applied to the SCEV for this
5962           // addition, then compute the SCEV for this addition by itself
5963           // with a separate call to getAddExpr. We need to do that
5964           // instead of pushing the operands of the addition onto AddOps,
5965           // since the flags are only known to apply to this particular
5966           // addition - they may not apply to other additions that can be
5967           // formed with operands from AddOps.
5968           const SCEV *RHS = getSCEV(BO->RHS);
5969           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5970           if (Flags != SCEV::FlagAnyWrap) {
5971             const SCEV *LHS = getSCEV(BO->LHS);
5972             if (BO->Opcode == Instruction::Sub)
5973               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5974             else
5975               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5976             break;
5977           }
5978         }
5979 
5980         if (BO->Opcode == Instruction::Sub)
5981           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5982         else
5983           AddOps.push_back(getSCEV(BO->RHS));
5984 
5985         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5986         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5987                        NewBO->Opcode != Instruction::Sub)) {
5988           AddOps.push_back(getSCEV(BO->LHS));
5989           break;
5990         }
5991         BO = NewBO;
5992       } while (true);
5993 
5994       return getAddExpr(AddOps);
5995     }
5996 
5997     case Instruction::Mul: {
5998       SmallVector<const SCEV *, 4> MulOps;
5999       do {
6000         if (BO->Op) {
6001           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6002             MulOps.push_back(OpSCEV);
6003             break;
6004           }
6005 
6006           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6007           if (Flags != SCEV::FlagAnyWrap) {
6008             MulOps.push_back(
6009                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6010             break;
6011           }
6012         }
6013 
6014         MulOps.push_back(getSCEV(BO->RHS));
6015         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6016         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6017           MulOps.push_back(getSCEV(BO->LHS));
6018           break;
6019         }
6020         BO = NewBO;
6021       } while (true);
6022 
6023       return getMulExpr(MulOps);
6024     }
6025     case Instruction::UDiv:
6026       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6027     case Instruction::URem:
6028       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6029     case Instruction::Sub: {
6030       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6031       if (BO->Op)
6032         Flags = getNoWrapFlagsFromUB(BO->Op);
6033       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6034     }
6035     case Instruction::And:
6036       // For an expression like x&255 that merely masks off the high bits,
6037       // use zext(trunc(x)) as the SCEV expression.
6038       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6039         if (CI->isZero())
6040           return getSCEV(BO->RHS);
6041         if (CI->isMinusOne())
6042           return getSCEV(BO->LHS);
6043         const APInt &A = CI->getValue();
6044 
6045         // Instcombine's ShrinkDemandedConstant may strip bits out of
6046         // constants, obscuring what would otherwise be a low-bits mask.
6047         // Use computeKnownBits to compute what ShrinkDemandedConstant
6048         // knew about to reconstruct a low-bits mask value.
6049         unsigned LZ = A.countLeadingZeros();
6050         unsigned TZ = A.countTrailingZeros();
6051         unsigned BitWidth = A.getBitWidth();
6052         KnownBits Known(BitWidth);
6053         computeKnownBits(BO->LHS, Known, getDataLayout(),
6054                          0, &AC, nullptr, &DT);
6055 
6056         APInt EffectiveMask =
6057             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6058         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6059           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6060           const SCEV *LHS = getSCEV(BO->LHS);
6061           const SCEV *ShiftedLHS = nullptr;
6062           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6063             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6064               // For an expression like (x * 8) & 8, simplify the multiply.
6065               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6066               unsigned GCD = std::min(MulZeros, TZ);
6067               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6068               SmallVector<const SCEV*, 4> MulOps;
6069               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6070               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6071               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6072               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6073             }
6074           }
6075           if (!ShiftedLHS)
6076             ShiftedLHS = getUDivExpr(LHS, MulCount);
6077           return getMulExpr(
6078               getZeroExtendExpr(
6079                   getTruncateExpr(ShiftedLHS,
6080                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6081                   BO->LHS->getType()),
6082               MulCount);
6083         }
6084       }
6085       break;
6086 
6087     case Instruction::Or:
6088       // If the RHS of the Or is a constant, we may have something like:
6089       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6090       // optimizations will transparently handle this case.
6091       //
6092       // In order for this transformation to be safe, the LHS must be of the
6093       // form X*(2^n) and the Or constant must be less than 2^n.
6094       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6095         const SCEV *LHS = getSCEV(BO->LHS);
6096         const APInt &CIVal = CI->getValue();
6097         if (GetMinTrailingZeros(LHS) >=
6098             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6099           // Build a plain add SCEV.
6100           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6101           // If the LHS of the add was an addrec and it has no-wrap flags,
6102           // transfer the no-wrap flags, since an or won't introduce a wrap.
6103           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6104             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6105             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6106                 OldAR->getNoWrapFlags());
6107           }
6108           return S;
6109         }
6110       }
6111       break;
6112 
6113     case Instruction::Xor:
6114       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6115         // If the RHS of xor is -1, then this is a not operation.
6116         if (CI->isMinusOne())
6117           return getNotSCEV(getSCEV(BO->LHS));
6118 
6119         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6120         // This is a variant of the check for xor with -1, and it handles
6121         // the case where instcombine has trimmed non-demanded bits out
6122         // of an xor with -1.
6123         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6124           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6125             if (LBO->getOpcode() == Instruction::And &&
6126                 LCI->getValue() == CI->getValue())
6127               if (const SCEVZeroExtendExpr *Z =
6128                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6129                 Type *UTy = BO->LHS->getType();
6130                 const SCEV *Z0 = Z->getOperand();
6131                 Type *Z0Ty = Z0->getType();
6132                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6133 
6134                 // If C is a low-bits mask, the zero extend is serving to
6135                 // mask off the high bits. Complement the operand and
6136                 // re-apply the zext.
6137                 if (CI->getValue().isMask(Z0TySize))
6138                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6139 
6140                 // If C is a single bit, it may be in the sign-bit position
6141                 // before the zero-extend. In this case, represent the xor
6142                 // using an add, which is equivalent, and re-apply the zext.
6143                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6144                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6145                     Trunc.isSignMask())
6146                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6147                                            UTy);
6148               }
6149       }
6150       break;
6151 
6152   case Instruction::Shl:
6153     // Turn shift left of a constant amount into a multiply.
6154     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6155       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6156 
6157       // If the shift count is not less than the bitwidth, the result of
6158       // the shift is undefined. Don't try to analyze it, because the
6159       // resolution chosen here may differ from the resolution chosen in
6160       // other parts of the compiler.
6161       if (SA->getValue().uge(BitWidth))
6162         break;
6163 
6164       // It is currently not resolved how to interpret NSW for left
6165       // shift by BitWidth - 1, so we avoid applying flags in that
6166       // case. Remove this check (or this comment) once the situation
6167       // is resolved. See
6168       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6169       // and http://reviews.llvm.org/D8890 .
6170       auto Flags = SCEV::FlagAnyWrap;
6171       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6172         Flags = getNoWrapFlagsFromUB(BO->Op);
6173 
6174       Constant *X = ConstantInt::get(getContext(),
6175         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6176       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6177     }
6178     break;
6179 
6180     case Instruction::AShr: {
6181       // AShr X, C, where C is a constant.
6182       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6183       if (!CI)
6184         break;
6185 
6186       Type *OuterTy = BO->LHS->getType();
6187       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6188       // If the shift count is not less than the bitwidth, the result of
6189       // the shift is undefined. Don't try to analyze it, because the
6190       // resolution chosen here may differ from the resolution chosen in
6191       // other parts of the compiler.
6192       if (CI->getValue().uge(BitWidth))
6193         break;
6194 
6195       if (CI->isZero())
6196         return getSCEV(BO->LHS); // shift by zero --> noop
6197 
6198       uint64_t AShrAmt = CI->getZExtValue();
6199       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6200 
6201       Operator *L = dyn_cast<Operator>(BO->LHS);
6202       if (L && L->getOpcode() == Instruction::Shl) {
6203         // X = Shl A, n
6204         // Y = AShr X, m
6205         // Both n and m are constant.
6206 
6207         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6208         if (L->getOperand(1) == BO->RHS)
6209           // For a two-shift sext-inreg, i.e. n = m,
6210           // use sext(trunc(x)) as the SCEV expression.
6211           return getSignExtendExpr(
6212               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6213 
6214         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6215         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6216           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6217           if (ShlAmt > AShrAmt) {
6218             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6219             // expression. We already checked that ShlAmt < BitWidth, so
6220             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6221             // ShlAmt - AShrAmt < Amt.
6222             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6223                                             ShlAmt - AShrAmt);
6224             return getSignExtendExpr(
6225                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6226                 getConstant(Mul)), OuterTy);
6227           }
6228         }
6229       }
6230       break;
6231     }
6232     }
6233   }
6234 
6235   switch (U->getOpcode()) {
6236   case Instruction::Trunc:
6237     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6238 
6239   case Instruction::ZExt:
6240     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6241 
6242   case Instruction::SExt:
6243     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6244       // The NSW flag of a subtract does not always survive the conversion to
6245       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6246       // more likely to preserve NSW and allow later AddRec optimisations.
6247       //
6248       // NOTE: This is effectively duplicating this logic from getSignExtend:
6249       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6250       // but by that point the NSW information has potentially been lost.
6251       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6252         Type *Ty = U->getType();
6253         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6254         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6255         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6256       }
6257     }
6258     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6259 
6260   case Instruction::BitCast:
6261     // BitCasts are no-op casts so we just eliminate the cast.
6262     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6263       return getSCEV(U->getOperand(0));
6264     break;
6265 
6266   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6267   // lead to pointer expressions which cannot safely be expanded to GEPs,
6268   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6269   // simplifying integer expressions.
6270 
6271   case Instruction::GetElementPtr:
6272     return createNodeForGEP(cast<GEPOperator>(U));
6273 
6274   case Instruction::PHI:
6275     return createNodeForPHI(cast<PHINode>(U));
6276 
6277   case Instruction::Select:
6278     // U can also be a select constant expr, which let fall through.  Since
6279     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6280     // constant expressions cannot have instructions as operands, we'd have
6281     // returned getUnknown for a select constant expressions anyway.
6282     if (isa<Instruction>(U))
6283       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6284                                       U->getOperand(1), U->getOperand(2));
6285     break;
6286 
6287   case Instruction::Call:
6288   case Instruction::Invoke:
6289     if (Value *RV = CallSite(U).getReturnedArgOperand())
6290       return getSCEV(RV);
6291     break;
6292   }
6293 
6294   return getUnknown(V);
6295 }
6296 
6297 //===----------------------------------------------------------------------===//
6298 //                   Iteration Count Computation Code
6299 //
6300 
6301 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6302   if (!ExitCount)
6303     return 0;
6304 
6305   ConstantInt *ExitConst = ExitCount->getValue();
6306 
6307   // Guard against huge trip counts.
6308   if (ExitConst->getValue().getActiveBits() > 32)
6309     return 0;
6310 
6311   // In case of integer overflow, this returns 0, which is correct.
6312   return ((unsigned)ExitConst->getZExtValue()) + 1;
6313 }
6314 
6315 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6316   if (BasicBlock *ExitingBB = L->getExitingBlock())
6317     return getSmallConstantTripCount(L, ExitingBB);
6318 
6319   // No trip count information for multiple exits.
6320   return 0;
6321 }
6322 
6323 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6324                                                     BasicBlock *ExitingBlock) {
6325   assert(ExitingBlock && "Must pass a non-null exiting block!");
6326   assert(L->isLoopExiting(ExitingBlock) &&
6327          "Exiting block must actually branch out of the loop!");
6328   const SCEVConstant *ExitCount =
6329       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6330   return getConstantTripCount(ExitCount);
6331 }
6332 
6333 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6334   const auto *MaxExitCount =
6335       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6336   return getConstantTripCount(MaxExitCount);
6337 }
6338 
6339 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6340   if (BasicBlock *ExitingBB = L->getExitingBlock())
6341     return getSmallConstantTripMultiple(L, ExitingBB);
6342 
6343   // No trip multiple information for multiple exits.
6344   return 0;
6345 }
6346 
6347 /// Returns the largest constant divisor of the trip count of this loop as a
6348 /// normal unsigned value, if possible. This means that the actual trip count is
6349 /// always a multiple of the returned value (don't forget the trip count could
6350 /// very well be zero as well!).
6351 ///
6352 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6353 /// multiple of a constant (which is also the case if the trip count is simply
6354 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6355 /// if the trip count is very large (>= 2^32).
6356 ///
6357 /// As explained in the comments for getSmallConstantTripCount, this assumes
6358 /// that control exits the loop via ExitingBlock.
6359 unsigned
6360 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6361                                               BasicBlock *ExitingBlock) {
6362   assert(ExitingBlock && "Must pass a non-null exiting block!");
6363   assert(L->isLoopExiting(ExitingBlock) &&
6364          "Exiting block must actually branch out of the loop!");
6365   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6366   if (ExitCount == getCouldNotCompute())
6367     return 1;
6368 
6369   // Get the trip count from the BE count by adding 1.
6370   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6371 
6372   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6373   if (!TC)
6374     // Attempt to factor more general cases. Returns the greatest power of
6375     // two divisor. If overflow happens, the trip count expression is still
6376     // divisible by the greatest power of 2 divisor returned.
6377     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6378 
6379   ConstantInt *Result = TC->getValue();
6380 
6381   // Guard against huge trip counts (this requires checking
6382   // for zero to handle the case where the trip count == -1 and the
6383   // addition wraps).
6384   if (!Result || Result->getValue().getActiveBits() > 32 ||
6385       Result->getValue().getActiveBits() == 0)
6386     return 1;
6387 
6388   return (unsigned)Result->getZExtValue();
6389 }
6390 
6391 /// Get the expression for the number of loop iterations for which this loop is
6392 /// guaranteed not to exit via ExitingBlock. Otherwise return
6393 /// SCEVCouldNotCompute.
6394 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6395                                           BasicBlock *ExitingBlock) {
6396   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6397 }
6398 
6399 const SCEV *
6400 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6401                                                  SCEVUnionPredicate &Preds) {
6402   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6403 }
6404 
6405 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6406   return getBackedgeTakenInfo(L).getExact(this);
6407 }
6408 
6409 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6410 /// known never to be less than the actual backedge taken count.
6411 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6412   return getBackedgeTakenInfo(L).getMax(this);
6413 }
6414 
6415 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6416   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6417 }
6418 
6419 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6420 static void
6421 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6422   BasicBlock *Header = L->getHeader();
6423 
6424   // Push all Loop-header PHIs onto the Worklist stack.
6425   for (PHINode &PN : Header->phis())
6426     Worklist.push_back(&PN);
6427 }
6428 
6429 const ScalarEvolution::BackedgeTakenInfo &
6430 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6431   auto &BTI = getBackedgeTakenInfo(L);
6432   if (BTI.hasFullInfo())
6433     return BTI;
6434 
6435   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6436 
6437   if (!Pair.second)
6438     return Pair.first->second;
6439 
6440   BackedgeTakenInfo Result =
6441       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6442 
6443   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6444 }
6445 
6446 const ScalarEvolution::BackedgeTakenInfo &
6447 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6448   // Initially insert an invalid entry for this loop. If the insertion
6449   // succeeds, proceed to actually compute a backedge-taken count and
6450   // update the value. The temporary CouldNotCompute value tells SCEV
6451   // code elsewhere that it shouldn't attempt to request a new
6452   // backedge-taken count, which could result in infinite recursion.
6453   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6454       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6455   if (!Pair.second)
6456     return Pair.first->second;
6457 
6458   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6459   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6460   // must be cleared in this scope.
6461   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6462 
6463   if (Result.getExact(this) != getCouldNotCompute()) {
6464     assert(isLoopInvariant(Result.getExact(this), L) &&
6465            isLoopInvariant(Result.getMax(this), L) &&
6466            "Computed backedge-taken count isn't loop invariant for loop!");
6467     ++NumTripCountsComputed;
6468   }
6469   else if (Result.getMax(this) == getCouldNotCompute() &&
6470            isa<PHINode>(L->getHeader()->begin())) {
6471     // Only count loops that have phi nodes as not being computable.
6472     ++NumTripCountsNotComputed;
6473   }
6474 
6475   // Now that we know more about the trip count for this loop, forget any
6476   // existing SCEV values for PHI nodes in this loop since they are only
6477   // conservative estimates made without the benefit of trip count
6478   // information. This is similar to the code in forgetLoop, except that
6479   // it handles SCEVUnknown PHI nodes specially.
6480   if (Result.hasAnyInfo()) {
6481     SmallVector<Instruction *, 16> Worklist;
6482     PushLoopPHIs(L, Worklist);
6483 
6484     SmallPtrSet<Instruction *, 8> Discovered;
6485     while (!Worklist.empty()) {
6486       Instruction *I = Worklist.pop_back_val();
6487 
6488       ValueExprMapType::iterator It =
6489         ValueExprMap.find_as(static_cast<Value *>(I));
6490       if (It != ValueExprMap.end()) {
6491         const SCEV *Old = It->second;
6492 
6493         // SCEVUnknown for a PHI either means that it has an unrecognized
6494         // structure, or it's a PHI that's in the progress of being computed
6495         // by createNodeForPHI.  In the former case, additional loop trip
6496         // count information isn't going to change anything. In the later
6497         // case, createNodeForPHI will perform the necessary updates on its
6498         // own when it gets to that point.
6499         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6500           eraseValueFromMap(It->first);
6501           forgetMemoizedResults(Old);
6502         }
6503         if (PHINode *PN = dyn_cast<PHINode>(I))
6504           ConstantEvolutionLoopExitValue.erase(PN);
6505       }
6506 
6507       // Since we don't need to invalidate anything for correctness and we're
6508       // only invalidating to make SCEV's results more precise, we get to stop
6509       // early to avoid invalidating too much.  This is especially important in
6510       // cases like:
6511       //
6512       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6513       // loop0:
6514       //   %pn0 = phi
6515       //   ...
6516       // loop1:
6517       //   %pn1 = phi
6518       //   ...
6519       //
6520       // where both loop0 and loop1's backedge taken count uses the SCEV
6521       // expression for %v.  If we don't have the early stop below then in cases
6522       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6523       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6524       // count for loop1, effectively nullifying SCEV's trip count cache.
6525       for (auto *U : I->users())
6526         if (auto *I = dyn_cast<Instruction>(U)) {
6527           auto *LoopForUser = LI.getLoopFor(I->getParent());
6528           if (LoopForUser && L->contains(LoopForUser) &&
6529               Discovered.insert(I).second)
6530             Worklist.push_back(I);
6531         }
6532     }
6533   }
6534 
6535   // Re-lookup the insert position, since the call to
6536   // computeBackedgeTakenCount above could result in a
6537   // recusive call to getBackedgeTakenInfo (on a different
6538   // loop), which would invalidate the iterator computed
6539   // earlier.
6540   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6541 }
6542 
6543 void ScalarEvolution::forgetLoop(const Loop *L) {
6544   // Drop any stored trip count value.
6545   auto RemoveLoopFromBackedgeMap =
6546       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6547         auto BTCPos = Map.find(L);
6548         if (BTCPos != Map.end()) {
6549           BTCPos->second.clear();
6550           Map.erase(BTCPos);
6551         }
6552       };
6553 
6554   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6555   SmallVector<Instruction *, 32> Worklist;
6556   SmallPtrSet<Instruction *, 16> Visited;
6557 
6558   // Iterate over all the loops and sub-loops to drop SCEV information.
6559   while (!LoopWorklist.empty()) {
6560     auto *CurrL = LoopWorklist.pop_back_val();
6561 
6562     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6563     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6564 
6565     // Drop information about predicated SCEV rewrites for this loop.
6566     for (auto I = PredicatedSCEVRewrites.begin();
6567          I != PredicatedSCEVRewrites.end();) {
6568       std::pair<const SCEV *, const Loop *> Entry = I->first;
6569       if (Entry.second == CurrL)
6570         PredicatedSCEVRewrites.erase(I++);
6571       else
6572         ++I;
6573     }
6574 
6575     auto LoopUsersItr = LoopUsers.find(CurrL);
6576     if (LoopUsersItr != LoopUsers.end()) {
6577       for (auto *S : LoopUsersItr->second)
6578         forgetMemoizedResults(S);
6579       LoopUsers.erase(LoopUsersItr);
6580     }
6581 
6582     // Drop information about expressions based on loop-header PHIs.
6583     PushLoopPHIs(CurrL, Worklist);
6584 
6585     while (!Worklist.empty()) {
6586       Instruction *I = Worklist.pop_back_val();
6587       if (!Visited.insert(I).second)
6588         continue;
6589 
6590       ValueExprMapType::iterator It =
6591           ValueExprMap.find_as(static_cast<Value *>(I));
6592       if (It != ValueExprMap.end()) {
6593         eraseValueFromMap(It->first);
6594         forgetMemoizedResults(It->second);
6595         if (PHINode *PN = dyn_cast<PHINode>(I))
6596           ConstantEvolutionLoopExitValue.erase(PN);
6597       }
6598 
6599       PushDefUseChildren(I, Worklist);
6600     }
6601 
6602     LoopPropertiesCache.erase(CurrL);
6603     // Forget all contained loops too, to avoid dangling entries in the
6604     // ValuesAtScopes map.
6605     LoopWorklist.append(CurrL->begin(), CurrL->end());
6606   }
6607 }
6608 
6609 void ScalarEvolution::forgetValue(Value *V) {
6610   Instruction *I = dyn_cast<Instruction>(V);
6611   if (!I) return;
6612 
6613   // Drop information about expressions based on loop-header PHIs.
6614   SmallVector<Instruction *, 16> Worklist;
6615   Worklist.push_back(I);
6616 
6617   SmallPtrSet<Instruction *, 8> Visited;
6618   while (!Worklist.empty()) {
6619     I = Worklist.pop_back_val();
6620     if (!Visited.insert(I).second)
6621       continue;
6622 
6623     ValueExprMapType::iterator It =
6624       ValueExprMap.find_as(static_cast<Value *>(I));
6625     if (It != ValueExprMap.end()) {
6626       eraseValueFromMap(It->first);
6627       forgetMemoizedResults(It->second);
6628       if (PHINode *PN = dyn_cast<PHINode>(I))
6629         ConstantEvolutionLoopExitValue.erase(PN);
6630     }
6631 
6632     PushDefUseChildren(I, Worklist);
6633   }
6634 }
6635 
6636 /// Get the exact loop backedge taken count considering all loop exits. A
6637 /// computable result can only be returned for loops with a single exit.
6638 /// Returning the minimum taken count among all exits is incorrect because one
6639 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6640 /// the limit of each loop test is never skipped. This is a valid assumption as
6641 /// long as the loop exits via that test. For precise results, it is the
6642 /// caller's responsibility to specify the relevant loop exit using
6643 /// getExact(ExitingBlock, SE).
6644 const SCEV *
6645 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6646                                              SCEVUnionPredicate *Preds) const {
6647   // If any exits were not computable, the loop is not computable.
6648   if (!isComplete() || ExitNotTaken.empty())
6649     return SE->getCouldNotCompute();
6650 
6651   const SCEV *BECount = nullptr;
6652   for (auto &ENT : ExitNotTaken) {
6653     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6654 
6655     if (!BECount)
6656       BECount = ENT.ExactNotTaken;
6657     else if (BECount != ENT.ExactNotTaken)
6658       return SE->getCouldNotCompute();
6659     if (Preds && !ENT.hasAlwaysTruePredicate())
6660       Preds->add(ENT.Predicate.get());
6661 
6662     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6663            "Predicate should be always true!");
6664   }
6665 
6666   assert(BECount && "Invalid not taken count for loop exit");
6667   return BECount;
6668 }
6669 
6670 /// Get the exact not taken count for this loop exit.
6671 const SCEV *
6672 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6673                                              ScalarEvolution *SE) const {
6674   for (auto &ENT : ExitNotTaken)
6675     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6676       return ENT.ExactNotTaken;
6677 
6678   return SE->getCouldNotCompute();
6679 }
6680 
6681 /// getMax - Get the max backedge taken count for the loop.
6682 const SCEV *
6683 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6684   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6685     return !ENT.hasAlwaysTruePredicate();
6686   };
6687 
6688   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6689     return SE->getCouldNotCompute();
6690 
6691   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6692          "No point in having a non-constant max backedge taken count!");
6693   return getMax();
6694 }
6695 
6696 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6697   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6698     return !ENT.hasAlwaysTruePredicate();
6699   };
6700   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6701 }
6702 
6703 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6704                                                     ScalarEvolution *SE) const {
6705   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6706       SE->hasOperand(getMax(), S))
6707     return true;
6708 
6709   for (auto &ENT : ExitNotTaken)
6710     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6711         SE->hasOperand(ENT.ExactNotTaken, S))
6712       return true;
6713 
6714   return false;
6715 }
6716 
6717 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6718     : ExactNotTaken(E), MaxNotTaken(E) {
6719   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6720           isa<SCEVConstant>(MaxNotTaken)) &&
6721          "No point in having a non-constant max backedge taken count!");
6722 }
6723 
6724 ScalarEvolution::ExitLimit::ExitLimit(
6725     const SCEV *E, const SCEV *M, bool MaxOrZero,
6726     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6727     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6728   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6729           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6730          "Exact is not allowed to be less precise than Max");
6731   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6732           isa<SCEVConstant>(MaxNotTaken)) &&
6733          "No point in having a non-constant max backedge taken count!");
6734   for (auto *PredSet : PredSetList)
6735     for (auto *P : *PredSet)
6736       addPredicate(P);
6737 }
6738 
6739 ScalarEvolution::ExitLimit::ExitLimit(
6740     const SCEV *E, const SCEV *M, bool MaxOrZero,
6741     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6742     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6743   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6744           isa<SCEVConstant>(MaxNotTaken)) &&
6745          "No point in having a non-constant max backedge taken count!");
6746 }
6747 
6748 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6749                                       bool MaxOrZero)
6750     : ExitLimit(E, M, MaxOrZero, None) {
6751   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6752           isa<SCEVConstant>(MaxNotTaken)) &&
6753          "No point in having a non-constant max backedge taken count!");
6754 }
6755 
6756 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6757 /// computable exit into a persistent ExitNotTakenInfo array.
6758 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6759     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6760         &&ExitCounts,
6761     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6762     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6763   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6764 
6765   ExitNotTaken.reserve(ExitCounts.size());
6766   std::transform(
6767       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6768       [&](const EdgeExitInfo &EEI) {
6769         BasicBlock *ExitBB = EEI.first;
6770         const ExitLimit &EL = EEI.second;
6771         if (EL.Predicates.empty())
6772           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6773 
6774         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6775         for (auto *Pred : EL.Predicates)
6776           Predicate->add(Pred);
6777 
6778         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6779       });
6780   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6781          "No point in having a non-constant max backedge taken count!");
6782 }
6783 
6784 /// Invalidate this result and free the ExitNotTakenInfo array.
6785 void ScalarEvolution::BackedgeTakenInfo::clear() {
6786   ExitNotTaken.clear();
6787 }
6788 
6789 /// Compute the number of times the backedge of the specified loop will execute.
6790 ScalarEvolution::BackedgeTakenInfo
6791 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6792                                            bool AllowPredicates) {
6793   SmallVector<BasicBlock *, 8> ExitingBlocks;
6794   L->getExitingBlocks(ExitingBlocks);
6795 
6796   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6797 
6798   SmallVector<EdgeExitInfo, 4> ExitCounts;
6799   bool CouldComputeBECount = true;
6800   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6801   const SCEV *MustExitMaxBECount = nullptr;
6802   const SCEV *MayExitMaxBECount = nullptr;
6803   bool MustExitMaxOrZero = false;
6804 
6805   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6806   // and compute maxBECount.
6807   // Do a union of all the predicates here.
6808   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6809     BasicBlock *ExitBB = ExitingBlocks[i];
6810     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6811 
6812     assert((AllowPredicates || EL.Predicates.empty()) &&
6813            "Predicated exit limit when predicates are not allowed!");
6814 
6815     // 1. For each exit that can be computed, add an entry to ExitCounts.
6816     // CouldComputeBECount is true only if all exits can be computed.
6817     if (EL.ExactNotTaken == getCouldNotCompute())
6818       // We couldn't compute an exact value for this exit, so
6819       // we won't be able to compute an exact value for the loop.
6820       CouldComputeBECount = false;
6821     else
6822       ExitCounts.emplace_back(ExitBB, EL);
6823 
6824     // 2. Derive the loop's MaxBECount from each exit's max number of
6825     // non-exiting iterations. Partition the loop exits into two kinds:
6826     // LoopMustExits and LoopMayExits.
6827     //
6828     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6829     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6830     // MaxBECount is the minimum EL.MaxNotTaken of computable
6831     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6832     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6833     // computable EL.MaxNotTaken.
6834     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6835         DT.dominates(ExitBB, Latch)) {
6836       if (!MustExitMaxBECount) {
6837         MustExitMaxBECount = EL.MaxNotTaken;
6838         MustExitMaxOrZero = EL.MaxOrZero;
6839       } else {
6840         MustExitMaxBECount =
6841             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6842       }
6843     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6844       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6845         MayExitMaxBECount = EL.MaxNotTaken;
6846       else {
6847         MayExitMaxBECount =
6848             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6849       }
6850     }
6851   }
6852   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6853     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6854   // The loop backedge will be taken the maximum or zero times if there's
6855   // a single exit that must be taken the maximum or zero times.
6856   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6857   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6858                            MaxBECount, MaxOrZero);
6859 }
6860 
6861 ScalarEvolution::ExitLimit
6862 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6863                                       bool AllowPredicates) {
6864   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6865   // at this block and remember the exit block and whether all other targets
6866   // lead to the loop header.
6867   bool MustExecuteLoopHeader = true;
6868   BasicBlock *Exit = nullptr;
6869   for (auto *SBB : successors(ExitingBlock))
6870     if (!L->contains(SBB)) {
6871       if (Exit) // Multiple exit successors.
6872         return getCouldNotCompute();
6873       Exit = SBB;
6874     } else if (SBB != L->getHeader()) {
6875       MustExecuteLoopHeader = false;
6876     }
6877 
6878   // At this point, we know we have a conditional branch that determines whether
6879   // the loop is exited.  However, we don't know if the branch is executed each
6880   // time through the loop.  If not, then the execution count of the branch will
6881   // not be equal to the trip count of the loop.
6882   //
6883   // Currently we check for this by checking to see if the Exit branch goes to
6884   // the loop header.  If so, we know it will always execute the same number of
6885   // times as the loop.  We also handle the case where the exit block *is* the
6886   // loop header.  This is common for un-rotated loops.
6887   //
6888   // If both of those tests fail, walk up the unique predecessor chain to the
6889   // header, stopping if there is an edge that doesn't exit the loop. If the
6890   // header is reached, the execution count of the branch will be equal to the
6891   // trip count of the loop.
6892   //
6893   //  More extensive analysis could be done to handle more cases here.
6894   //
6895   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6896     // The simple checks failed, try climbing the unique predecessor chain
6897     // up to the header.
6898     bool Ok = false;
6899     for (BasicBlock *BB = ExitingBlock; BB; ) {
6900       BasicBlock *Pred = BB->getUniquePredecessor();
6901       if (!Pred)
6902         return getCouldNotCompute();
6903       TerminatorInst *PredTerm = Pred->getTerminator();
6904       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6905         if (PredSucc == BB)
6906           continue;
6907         // If the predecessor has a successor that isn't BB and isn't
6908         // outside the loop, assume the worst.
6909         if (L->contains(PredSucc))
6910           return getCouldNotCompute();
6911       }
6912       if (Pred == L->getHeader()) {
6913         Ok = true;
6914         break;
6915       }
6916       BB = Pred;
6917     }
6918     if (!Ok)
6919       return getCouldNotCompute();
6920   }
6921 
6922   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6923   TerminatorInst *Term = ExitingBlock->getTerminator();
6924   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6925     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6926     // Proceed to the next level to examine the exit condition expression.
6927     return computeExitLimitFromCond(
6928         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6929         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6930   }
6931 
6932   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6933     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6934                                                 /*ControlsExit=*/IsOnlyExit);
6935 
6936   return getCouldNotCompute();
6937 }
6938 
6939 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6940     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6941     bool ControlsExit, bool AllowPredicates) {
6942   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6943   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6944                                         ControlsExit, AllowPredicates);
6945 }
6946 
6947 Optional<ScalarEvolution::ExitLimit>
6948 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6949                                       BasicBlock *TBB, BasicBlock *FBB,
6950                                       bool ControlsExit, bool AllowPredicates) {
6951   (void)this->L;
6952   (void)this->TBB;
6953   (void)this->FBB;
6954   (void)this->AllowPredicates;
6955 
6956   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6957          this->AllowPredicates == AllowPredicates &&
6958          "Variance in assumed invariant key components!");
6959   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6960   if (Itr == TripCountMap.end())
6961     return None;
6962   return Itr->second;
6963 }
6964 
6965 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6966                                              BasicBlock *TBB, BasicBlock *FBB,
6967                                              bool ControlsExit,
6968                                              bool AllowPredicates,
6969                                              const ExitLimit &EL) {
6970   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6971          this->AllowPredicates == AllowPredicates &&
6972          "Variance in assumed invariant key components!");
6973 
6974   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6975   assert(InsertResult.second && "Expected successful insertion!");
6976   (void)InsertResult;
6977 }
6978 
6979 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6980     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6981     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6982 
6983   if (auto MaybeEL =
6984           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6985     return *MaybeEL;
6986 
6987   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6988                                               ControlsExit, AllowPredicates);
6989   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6990   return EL;
6991 }
6992 
6993 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6994     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6995     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6996   // Check if the controlling expression for this loop is an And or Or.
6997   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6998     if (BO->getOpcode() == Instruction::And) {
6999       // Recurse on the operands of the and.
7000       bool EitherMayExit = L->contains(TBB);
7001       ExitLimit EL0 = computeExitLimitFromCondCached(
7002           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
7003           AllowPredicates);
7004       ExitLimit EL1 = computeExitLimitFromCondCached(
7005           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7006           AllowPredicates);
7007       const SCEV *BECount = getCouldNotCompute();
7008       const SCEV *MaxBECount = getCouldNotCompute();
7009       if (EitherMayExit) {
7010         // Both conditions must be true for the loop to continue executing.
7011         // Choose the less conservative count.
7012         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7013             EL1.ExactNotTaken == getCouldNotCompute())
7014           BECount = getCouldNotCompute();
7015         else
7016           BECount =
7017               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7018         if (EL0.MaxNotTaken == getCouldNotCompute())
7019           MaxBECount = EL1.MaxNotTaken;
7020         else if (EL1.MaxNotTaken == getCouldNotCompute())
7021           MaxBECount = EL0.MaxNotTaken;
7022         else
7023           MaxBECount =
7024               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7025       } else {
7026         // Both conditions must be true at the same time for the loop to exit.
7027         // For now, be conservative.
7028         assert(L->contains(FBB) && "Loop block has no successor in loop!");
7029         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7030           MaxBECount = EL0.MaxNotTaken;
7031         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7032           BECount = EL0.ExactNotTaken;
7033       }
7034 
7035       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7036       // to be more aggressive when computing BECount than when computing
7037       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7038       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7039       // to not.
7040       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7041           !isa<SCEVCouldNotCompute>(BECount))
7042         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7043 
7044       return ExitLimit(BECount, MaxBECount, false,
7045                        {&EL0.Predicates, &EL1.Predicates});
7046     }
7047     if (BO->getOpcode() == Instruction::Or) {
7048       // Recurse on the operands of the or.
7049       bool EitherMayExit = L->contains(FBB);
7050       ExitLimit EL0 = computeExitLimitFromCondCached(
7051           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
7052           AllowPredicates);
7053       ExitLimit EL1 = computeExitLimitFromCondCached(
7054           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
7055           AllowPredicates);
7056       const SCEV *BECount = getCouldNotCompute();
7057       const SCEV *MaxBECount = getCouldNotCompute();
7058       if (EitherMayExit) {
7059         // Both conditions must be false for the loop to continue executing.
7060         // Choose the less conservative count.
7061         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7062             EL1.ExactNotTaken == getCouldNotCompute())
7063           BECount = getCouldNotCompute();
7064         else
7065           BECount =
7066               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7067         if (EL0.MaxNotTaken == getCouldNotCompute())
7068           MaxBECount = EL1.MaxNotTaken;
7069         else if (EL1.MaxNotTaken == getCouldNotCompute())
7070           MaxBECount = EL0.MaxNotTaken;
7071         else
7072           MaxBECount =
7073               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7074       } else {
7075         // Both conditions must be false at the same time for the loop to exit.
7076         // For now, be conservative.
7077         assert(L->contains(TBB) && "Loop block has no successor in loop!");
7078         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7079           MaxBECount = EL0.MaxNotTaken;
7080         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7081           BECount = EL0.ExactNotTaken;
7082       }
7083 
7084       return ExitLimit(BECount, MaxBECount, false,
7085                        {&EL0.Predicates, &EL1.Predicates});
7086     }
7087   }
7088 
7089   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7090   // Proceed to the next level to examine the icmp.
7091   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7092     ExitLimit EL =
7093         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
7094     if (EL.hasFullInfo() || !AllowPredicates)
7095       return EL;
7096 
7097     // Try again, but use SCEV predicates this time.
7098     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
7099                                     /*AllowPredicates=*/true);
7100   }
7101 
7102   // Check for a constant condition. These are normally stripped out by
7103   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7104   // preserve the CFG and is temporarily leaving constant conditions
7105   // in place.
7106   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7107     if (L->contains(FBB) == !CI->getZExtValue())
7108       // The backedge is always taken.
7109       return getCouldNotCompute();
7110     else
7111       // The backedge is never taken.
7112       return getZero(CI->getType());
7113   }
7114 
7115   // If it's not an integer or pointer comparison then compute it the hard way.
7116   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7117 }
7118 
7119 ScalarEvolution::ExitLimit
7120 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7121                                           ICmpInst *ExitCond,
7122                                           BasicBlock *TBB,
7123                                           BasicBlock *FBB,
7124                                           bool ControlsExit,
7125                                           bool AllowPredicates) {
7126   // If the condition was exit on true, convert the condition to exit on false
7127   ICmpInst::Predicate Pred;
7128   if (!L->contains(FBB))
7129     Pred = ExitCond->getPredicate();
7130   else
7131     Pred = ExitCond->getInversePredicate();
7132   const ICmpInst::Predicate OriginalPred = Pred;
7133 
7134   // Handle common loops like: for (X = "string"; *X; ++X)
7135   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7136     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7137       ExitLimit ItCnt =
7138         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7139       if (ItCnt.hasAnyInfo())
7140         return ItCnt;
7141     }
7142 
7143   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7144   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7145 
7146   // Try to evaluate any dependencies out of the loop.
7147   LHS = getSCEVAtScope(LHS, L);
7148   RHS = getSCEVAtScope(RHS, L);
7149 
7150   // At this point, we would like to compute how many iterations of the
7151   // loop the predicate will return true for these inputs.
7152   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7153     // If there is a loop-invariant, force it into the RHS.
7154     std::swap(LHS, RHS);
7155     Pred = ICmpInst::getSwappedPredicate(Pred);
7156   }
7157 
7158   // Simplify the operands before analyzing them.
7159   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7160 
7161   // If we have a comparison of a chrec against a constant, try to use value
7162   // ranges to answer this query.
7163   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7164     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7165       if (AddRec->getLoop() == L) {
7166         // Form the constant range.
7167         ConstantRange CompRange =
7168             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7169 
7170         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7171         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7172       }
7173 
7174   switch (Pred) {
7175   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7176     // Convert to: while (X-Y != 0)
7177     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7178                                 AllowPredicates);
7179     if (EL.hasAnyInfo()) return EL;
7180     break;
7181   }
7182   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7183     // Convert to: while (X-Y == 0)
7184     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7185     if (EL.hasAnyInfo()) return EL;
7186     break;
7187   }
7188   case ICmpInst::ICMP_SLT:
7189   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7190     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7191     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7192                                     AllowPredicates);
7193     if (EL.hasAnyInfo()) return EL;
7194     break;
7195   }
7196   case ICmpInst::ICMP_SGT:
7197   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7198     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7199     ExitLimit EL =
7200         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7201                             AllowPredicates);
7202     if (EL.hasAnyInfo()) return EL;
7203     break;
7204   }
7205   default:
7206     break;
7207   }
7208 
7209   auto *ExhaustiveCount =
7210       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
7211 
7212   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7213     return ExhaustiveCount;
7214 
7215   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7216                                       ExitCond->getOperand(1), L, OriginalPred);
7217 }
7218 
7219 ScalarEvolution::ExitLimit
7220 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7221                                                       SwitchInst *Switch,
7222                                                       BasicBlock *ExitingBlock,
7223                                                       bool ControlsExit) {
7224   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7225 
7226   // Give up if the exit is the default dest of a switch.
7227   if (Switch->getDefaultDest() == ExitingBlock)
7228     return getCouldNotCompute();
7229 
7230   assert(L->contains(Switch->getDefaultDest()) &&
7231          "Default case must not exit the loop!");
7232   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7233   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7234 
7235   // while (X != Y) --> while (X-Y != 0)
7236   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7237   if (EL.hasAnyInfo())
7238     return EL;
7239 
7240   return getCouldNotCompute();
7241 }
7242 
7243 static ConstantInt *
7244 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7245                                 ScalarEvolution &SE) {
7246   const SCEV *InVal = SE.getConstant(C);
7247   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7248   assert(isa<SCEVConstant>(Val) &&
7249          "Evaluation of SCEV at constant didn't fold correctly?");
7250   return cast<SCEVConstant>(Val)->getValue();
7251 }
7252 
7253 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7254 /// compute the backedge execution count.
7255 ScalarEvolution::ExitLimit
7256 ScalarEvolution::computeLoadConstantCompareExitLimit(
7257   LoadInst *LI,
7258   Constant *RHS,
7259   const Loop *L,
7260   ICmpInst::Predicate predicate) {
7261   if (LI->isVolatile()) return getCouldNotCompute();
7262 
7263   // Check to see if the loaded pointer is a getelementptr of a global.
7264   // TODO: Use SCEV instead of manually grubbing with GEPs.
7265   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7266   if (!GEP) return getCouldNotCompute();
7267 
7268   // Make sure that it is really a constant global we are gepping, with an
7269   // initializer, and make sure the first IDX is really 0.
7270   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7271   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7272       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7273       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7274     return getCouldNotCompute();
7275 
7276   // Okay, we allow one non-constant index into the GEP instruction.
7277   Value *VarIdx = nullptr;
7278   std::vector<Constant*> Indexes;
7279   unsigned VarIdxNum = 0;
7280   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7281     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7282       Indexes.push_back(CI);
7283     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7284       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7285       VarIdx = GEP->getOperand(i);
7286       VarIdxNum = i-2;
7287       Indexes.push_back(nullptr);
7288     }
7289 
7290   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7291   if (!VarIdx)
7292     return getCouldNotCompute();
7293 
7294   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7295   // Check to see if X is a loop variant variable value now.
7296   const SCEV *Idx = getSCEV(VarIdx);
7297   Idx = getSCEVAtScope(Idx, L);
7298 
7299   // We can only recognize very limited forms of loop index expressions, in
7300   // particular, only affine AddRec's like {C1,+,C2}.
7301   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7302   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7303       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7304       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7305     return getCouldNotCompute();
7306 
7307   unsigned MaxSteps = MaxBruteForceIterations;
7308   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7309     ConstantInt *ItCst = ConstantInt::get(
7310                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7311     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7312 
7313     // Form the GEP offset.
7314     Indexes[VarIdxNum] = Val;
7315 
7316     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7317                                                          Indexes);
7318     if (!Result) break;  // Cannot compute!
7319 
7320     // Evaluate the condition for this iteration.
7321     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7322     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7323     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7324       ++NumArrayLenItCounts;
7325       return getConstant(ItCst);   // Found terminating iteration!
7326     }
7327   }
7328   return getCouldNotCompute();
7329 }
7330 
7331 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7332     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7333   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7334   if (!RHS)
7335     return getCouldNotCompute();
7336 
7337   const BasicBlock *Latch = L->getLoopLatch();
7338   if (!Latch)
7339     return getCouldNotCompute();
7340 
7341   const BasicBlock *Predecessor = L->getLoopPredecessor();
7342   if (!Predecessor)
7343     return getCouldNotCompute();
7344 
7345   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7346   // Return LHS in OutLHS and shift_opt in OutOpCode.
7347   auto MatchPositiveShift =
7348       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7349 
7350     using namespace PatternMatch;
7351 
7352     ConstantInt *ShiftAmt;
7353     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7354       OutOpCode = Instruction::LShr;
7355     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7356       OutOpCode = Instruction::AShr;
7357     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7358       OutOpCode = Instruction::Shl;
7359     else
7360       return false;
7361 
7362     return ShiftAmt->getValue().isStrictlyPositive();
7363   };
7364 
7365   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7366   //
7367   // loop:
7368   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7369   //   %iv.shifted = lshr i32 %iv, <positive constant>
7370   //
7371   // Return true on a successful match.  Return the corresponding PHI node (%iv
7372   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7373   auto MatchShiftRecurrence =
7374       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7375     Optional<Instruction::BinaryOps> PostShiftOpCode;
7376 
7377     {
7378       Instruction::BinaryOps OpC;
7379       Value *V;
7380 
7381       // If we encounter a shift instruction, "peel off" the shift operation,
7382       // and remember that we did so.  Later when we inspect %iv's backedge
7383       // value, we will make sure that the backedge value uses the same
7384       // operation.
7385       //
7386       // Note: the peeled shift operation does not have to be the same
7387       // instruction as the one feeding into the PHI's backedge value.  We only
7388       // really care about it being the same *kind* of shift instruction --
7389       // that's all that is required for our later inferences to hold.
7390       if (MatchPositiveShift(LHS, V, OpC)) {
7391         PostShiftOpCode = OpC;
7392         LHS = V;
7393       }
7394     }
7395 
7396     PNOut = dyn_cast<PHINode>(LHS);
7397     if (!PNOut || PNOut->getParent() != L->getHeader())
7398       return false;
7399 
7400     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7401     Value *OpLHS;
7402 
7403     return
7404         // The backedge value for the PHI node must be a shift by a positive
7405         // amount
7406         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7407 
7408         // of the PHI node itself
7409         OpLHS == PNOut &&
7410 
7411         // and the kind of shift should be match the kind of shift we peeled
7412         // off, if any.
7413         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7414   };
7415 
7416   PHINode *PN;
7417   Instruction::BinaryOps OpCode;
7418   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7419     return getCouldNotCompute();
7420 
7421   const DataLayout &DL = getDataLayout();
7422 
7423   // The key rationale for this optimization is that for some kinds of shift
7424   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7425   // within a finite number of iterations.  If the condition guarding the
7426   // backedge (in the sense that the backedge is taken if the condition is true)
7427   // is false for the value the shift recurrence stabilizes to, then we know
7428   // that the backedge is taken only a finite number of times.
7429 
7430   ConstantInt *StableValue = nullptr;
7431   switch (OpCode) {
7432   default:
7433     llvm_unreachable("Impossible case!");
7434 
7435   case Instruction::AShr: {
7436     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7437     // bitwidth(K) iterations.
7438     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7439     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7440                                        Predecessor->getTerminator(), &DT);
7441     auto *Ty = cast<IntegerType>(RHS->getType());
7442     if (Known.isNonNegative())
7443       StableValue = ConstantInt::get(Ty, 0);
7444     else if (Known.isNegative())
7445       StableValue = ConstantInt::get(Ty, -1, true);
7446     else
7447       return getCouldNotCompute();
7448 
7449     break;
7450   }
7451   case Instruction::LShr:
7452   case Instruction::Shl:
7453     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7454     // stabilize to 0 in at most bitwidth(K) iterations.
7455     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7456     break;
7457   }
7458 
7459   auto *Result =
7460       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7461   assert(Result->getType()->isIntegerTy(1) &&
7462          "Otherwise cannot be an operand to a branch instruction");
7463 
7464   if (Result->isZeroValue()) {
7465     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7466     const SCEV *UpperBound =
7467         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7468     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7469   }
7470 
7471   return getCouldNotCompute();
7472 }
7473 
7474 /// Return true if we can constant fold an instruction of the specified type,
7475 /// assuming that all operands were constants.
7476 static bool CanConstantFold(const Instruction *I) {
7477   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7478       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7479       isa<LoadInst>(I))
7480     return true;
7481 
7482   if (const CallInst *CI = dyn_cast<CallInst>(I))
7483     if (const Function *F = CI->getCalledFunction())
7484       return canConstantFoldCallTo(CI, F);
7485   return false;
7486 }
7487 
7488 /// Determine whether this instruction can constant evolve within this loop
7489 /// assuming its operands can all constant evolve.
7490 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7491   // An instruction outside of the loop can't be derived from a loop PHI.
7492   if (!L->contains(I)) return false;
7493 
7494   if (isa<PHINode>(I)) {
7495     // We don't currently keep track of the control flow needed to evaluate
7496     // PHIs, so we cannot handle PHIs inside of loops.
7497     return L->getHeader() == I->getParent();
7498   }
7499 
7500   // If we won't be able to constant fold this expression even if the operands
7501   // are constants, bail early.
7502   return CanConstantFold(I);
7503 }
7504 
7505 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7506 /// recursing through each instruction operand until reaching a loop header phi.
7507 static PHINode *
7508 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7509                                DenseMap<Instruction *, PHINode *> &PHIMap,
7510                                unsigned Depth) {
7511   if (Depth > MaxConstantEvolvingDepth)
7512     return nullptr;
7513 
7514   // Otherwise, we can evaluate this instruction if all of its operands are
7515   // constant or derived from a PHI node themselves.
7516   PHINode *PHI = nullptr;
7517   for (Value *Op : UseInst->operands()) {
7518     if (isa<Constant>(Op)) continue;
7519 
7520     Instruction *OpInst = dyn_cast<Instruction>(Op);
7521     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7522 
7523     PHINode *P = dyn_cast<PHINode>(OpInst);
7524     if (!P)
7525       // If this operand is already visited, reuse the prior result.
7526       // We may have P != PHI if this is the deepest point at which the
7527       // inconsistent paths meet.
7528       P = PHIMap.lookup(OpInst);
7529     if (!P) {
7530       // Recurse and memoize the results, whether a phi is found or not.
7531       // This recursive call invalidates pointers into PHIMap.
7532       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7533       PHIMap[OpInst] = P;
7534     }
7535     if (!P)
7536       return nullptr;  // Not evolving from PHI
7537     if (PHI && PHI != P)
7538       return nullptr;  // Evolving from multiple different PHIs.
7539     PHI = P;
7540   }
7541   // This is a expression evolving from a constant PHI!
7542   return PHI;
7543 }
7544 
7545 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7546 /// in the loop that V is derived from.  We allow arbitrary operations along the
7547 /// way, but the operands of an operation must either be constants or a value
7548 /// derived from a constant PHI.  If this expression does not fit with these
7549 /// constraints, return null.
7550 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7551   Instruction *I = dyn_cast<Instruction>(V);
7552   if (!I || !canConstantEvolve(I, L)) return nullptr;
7553 
7554   if (PHINode *PN = dyn_cast<PHINode>(I))
7555     return PN;
7556 
7557   // Record non-constant instructions contained by the loop.
7558   DenseMap<Instruction *, PHINode *> PHIMap;
7559   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7560 }
7561 
7562 /// EvaluateExpression - Given an expression that passes the
7563 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7564 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7565 /// reason, return null.
7566 static Constant *EvaluateExpression(Value *V, const Loop *L,
7567                                     DenseMap<Instruction *, Constant *> &Vals,
7568                                     const DataLayout &DL,
7569                                     const TargetLibraryInfo *TLI) {
7570   // Convenient constant check, but redundant for recursive calls.
7571   if (Constant *C = dyn_cast<Constant>(V)) return C;
7572   Instruction *I = dyn_cast<Instruction>(V);
7573   if (!I) return nullptr;
7574 
7575   if (Constant *C = Vals.lookup(I)) return C;
7576 
7577   // An instruction inside the loop depends on a value outside the loop that we
7578   // weren't given a mapping for, or a value such as a call inside the loop.
7579   if (!canConstantEvolve(I, L)) return nullptr;
7580 
7581   // An unmapped PHI can be due to a branch or another loop inside this loop,
7582   // or due to this not being the initial iteration through a loop where we
7583   // couldn't compute the evolution of this particular PHI last time.
7584   if (isa<PHINode>(I)) return nullptr;
7585 
7586   std::vector<Constant*> Operands(I->getNumOperands());
7587 
7588   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7589     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7590     if (!Operand) {
7591       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7592       if (!Operands[i]) return nullptr;
7593       continue;
7594     }
7595     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7596     Vals[Operand] = C;
7597     if (!C) return nullptr;
7598     Operands[i] = C;
7599   }
7600 
7601   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7602     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7603                                            Operands[1], DL, TLI);
7604   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7605     if (!LI->isVolatile())
7606       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7607   }
7608   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7609 }
7610 
7611 
7612 // If every incoming value to PN except the one for BB is a specific Constant,
7613 // return that, else return nullptr.
7614 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7615   Constant *IncomingVal = nullptr;
7616 
7617   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7618     if (PN->getIncomingBlock(i) == BB)
7619       continue;
7620 
7621     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7622     if (!CurrentVal)
7623       return nullptr;
7624 
7625     if (IncomingVal != CurrentVal) {
7626       if (IncomingVal)
7627         return nullptr;
7628       IncomingVal = CurrentVal;
7629     }
7630   }
7631 
7632   return IncomingVal;
7633 }
7634 
7635 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7636 /// in the header of its containing loop, we know the loop executes a
7637 /// constant number of times, and the PHI node is just a recurrence
7638 /// involving constants, fold it.
7639 Constant *
7640 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7641                                                    const APInt &BEs,
7642                                                    const Loop *L) {
7643   auto I = ConstantEvolutionLoopExitValue.find(PN);
7644   if (I != ConstantEvolutionLoopExitValue.end())
7645     return I->second;
7646 
7647   if (BEs.ugt(MaxBruteForceIterations))
7648     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7649 
7650   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7651 
7652   DenseMap<Instruction *, Constant *> CurrentIterVals;
7653   BasicBlock *Header = L->getHeader();
7654   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7655 
7656   BasicBlock *Latch = L->getLoopLatch();
7657   if (!Latch)
7658     return nullptr;
7659 
7660   for (PHINode &PHI : Header->phis()) {
7661     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7662       CurrentIterVals[&PHI] = StartCST;
7663   }
7664   if (!CurrentIterVals.count(PN))
7665     return RetVal = nullptr;
7666 
7667   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7668 
7669   // Execute the loop symbolically to determine the exit value.
7670   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7671          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7672 
7673   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7674   unsigned IterationNum = 0;
7675   const DataLayout &DL = getDataLayout();
7676   for (; ; ++IterationNum) {
7677     if (IterationNum == NumIterations)
7678       return RetVal = CurrentIterVals[PN];  // Got exit value!
7679 
7680     // Compute the value of the PHIs for the next iteration.
7681     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7682     DenseMap<Instruction *, Constant *> NextIterVals;
7683     Constant *NextPHI =
7684         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7685     if (!NextPHI)
7686       return nullptr;        // Couldn't evaluate!
7687     NextIterVals[PN] = NextPHI;
7688 
7689     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7690 
7691     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7692     // cease to be able to evaluate one of them or if they stop evolving,
7693     // because that doesn't necessarily prevent us from computing PN.
7694     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7695     for (const auto &I : CurrentIterVals) {
7696       PHINode *PHI = dyn_cast<PHINode>(I.first);
7697       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7698       PHIsToCompute.emplace_back(PHI, I.second);
7699     }
7700     // We use two distinct loops because EvaluateExpression may invalidate any
7701     // iterators into CurrentIterVals.
7702     for (const auto &I : PHIsToCompute) {
7703       PHINode *PHI = I.first;
7704       Constant *&NextPHI = NextIterVals[PHI];
7705       if (!NextPHI) {   // Not already computed.
7706         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7707         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7708       }
7709       if (NextPHI != I.second)
7710         StoppedEvolving = false;
7711     }
7712 
7713     // If all entries in CurrentIterVals == NextIterVals then we can stop
7714     // iterating, the loop can't continue to change.
7715     if (StoppedEvolving)
7716       return RetVal = CurrentIterVals[PN];
7717 
7718     CurrentIterVals.swap(NextIterVals);
7719   }
7720 }
7721 
7722 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7723                                                           Value *Cond,
7724                                                           bool ExitWhen) {
7725   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7726   if (!PN) return getCouldNotCompute();
7727 
7728   // If the loop is canonicalized, the PHI will have exactly two entries.
7729   // That's the only form we support here.
7730   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7731 
7732   DenseMap<Instruction *, Constant *> CurrentIterVals;
7733   BasicBlock *Header = L->getHeader();
7734   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7735 
7736   BasicBlock *Latch = L->getLoopLatch();
7737   assert(Latch && "Should follow from NumIncomingValues == 2!");
7738 
7739   for (PHINode &PHI : Header->phis()) {
7740     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7741       CurrentIterVals[&PHI] = StartCST;
7742   }
7743   if (!CurrentIterVals.count(PN))
7744     return getCouldNotCompute();
7745 
7746   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7747   // the loop symbolically to determine when the condition gets a value of
7748   // "ExitWhen".
7749   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7750   const DataLayout &DL = getDataLayout();
7751   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7752     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7753         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7754 
7755     // Couldn't symbolically evaluate.
7756     if (!CondVal) return getCouldNotCompute();
7757 
7758     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7759       ++NumBruteForceTripCountsComputed;
7760       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7761     }
7762 
7763     // Update all the PHI nodes for the next iteration.
7764     DenseMap<Instruction *, Constant *> NextIterVals;
7765 
7766     // Create a list of which PHIs we need to compute. We want to do this before
7767     // calling EvaluateExpression on them because that may invalidate iterators
7768     // into CurrentIterVals.
7769     SmallVector<PHINode *, 8> PHIsToCompute;
7770     for (const auto &I : CurrentIterVals) {
7771       PHINode *PHI = dyn_cast<PHINode>(I.first);
7772       if (!PHI || PHI->getParent() != Header) continue;
7773       PHIsToCompute.push_back(PHI);
7774     }
7775     for (PHINode *PHI : PHIsToCompute) {
7776       Constant *&NextPHI = NextIterVals[PHI];
7777       if (NextPHI) continue;    // Already computed!
7778 
7779       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7780       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7781     }
7782     CurrentIterVals.swap(NextIterVals);
7783   }
7784 
7785   // Too many iterations were needed to evaluate.
7786   return getCouldNotCompute();
7787 }
7788 
7789 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7790   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7791       ValuesAtScopes[V];
7792   // Check to see if we've folded this expression at this loop before.
7793   for (auto &LS : Values)
7794     if (LS.first == L)
7795       return LS.second ? LS.second : V;
7796 
7797   Values.emplace_back(L, nullptr);
7798 
7799   // Otherwise compute it.
7800   const SCEV *C = computeSCEVAtScope(V, L);
7801   for (auto &LS : reverse(ValuesAtScopes[V]))
7802     if (LS.first == L) {
7803       LS.second = C;
7804       break;
7805     }
7806   return C;
7807 }
7808 
7809 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7810 /// will return Constants for objects which aren't represented by a
7811 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7812 /// Returns NULL if the SCEV isn't representable as a Constant.
7813 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7814   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7815     case scCouldNotCompute:
7816     case scAddRecExpr:
7817       break;
7818     case scConstant:
7819       return cast<SCEVConstant>(V)->getValue();
7820     case scUnknown:
7821       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7822     case scSignExtend: {
7823       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7824       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7825         return ConstantExpr::getSExt(CastOp, SS->getType());
7826       break;
7827     }
7828     case scZeroExtend: {
7829       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7830       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7831         return ConstantExpr::getZExt(CastOp, SZ->getType());
7832       break;
7833     }
7834     case scTruncate: {
7835       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7836       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7837         return ConstantExpr::getTrunc(CastOp, ST->getType());
7838       break;
7839     }
7840     case scAddExpr: {
7841       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7842       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7843         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7844           unsigned AS = PTy->getAddressSpace();
7845           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7846           C = ConstantExpr::getBitCast(C, DestPtrTy);
7847         }
7848         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7849           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7850           if (!C2) return nullptr;
7851 
7852           // First pointer!
7853           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7854             unsigned AS = C2->getType()->getPointerAddressSpace();
7855             std::swap(C, C2);
7856             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7857             // The offsets have been converted to bytes.  We can add bytes to an
7858             // i8* by GEP with the byte count in the first index.
7859             C = ConstantExpr::getBitCast(C, DestPtrTy);
7860           }
7861 
7862           // Don't bother trying to sum two pointers. We probably can't
7863           // statically compute a load that results from it anyway.
7864           if (C2->getType()->isPointerTy())
7865             return nullptr;
7866 
7867           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7868             if (PTy->getElementType()->isStructTy())
7869               C2 = ConstantExpr::getIntegerCast(
7870                   C2, Type::getInt32Ty(C->getContext()), true);
7871             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7872           } else
7873             C = ConstantExpr::getAdd(C, C2);
7874         }
7875         return C;
7876       }
7877       break;
7878     }
7879     case scMulExpr: {
7880       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7881       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7882         // Don't bother with pointers at all.
7883         if (C->getType()->isPointerTy()) return nullptr;
7884         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7885           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7886           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7887           C = ConstantExpr::getMul(C, C2);
7888         }
7889         return C;
7890       }
7891       break;
7892     }
7893     case scUDivExpr: {
7894       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7895       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7896         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7897           if (LHS->getType() == RHS->getType())
7898             return ConstantExpr::getUDiv(LHS, RHS);
7899       break;
7900     }
7901     case scSMaxExpr:
7902     case scUMaxExpr:
7903       break; // TODO: smax, umax.
7904   }
7905   return nullptr;
7906 }
7907 
7908 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7909   if (isa<SCEVConstant>(V)) return V;
7910 
7911   // If this instruction is evolved from a constant-evolving PHI, compute the
7912   // exit value from the loop without using SCEVs.
7913   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7914     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7915       const Loop *LI = this->LI[I->getParent()];
7916       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7917         if (PHINode *PN = dyn_cast<PHINode>(I))
7918           if (PN->getParent() == LI->getHeader()) {
7919             // Okay, there is no closed form solution for the PHI node.  Check
7920             // to see if the loop that contains it has a known backedge-taken
7921             // count.  If so, we may be able to force computation of the exit
7922             // value.
7923             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7924             if (const SCEVConstant *BTCC =
7925                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7926 
7927               // This trivial case can show up in some degenerate cases where
7928               // the incoming IR has not yet been fully simplified.
7929               if (BTCC->getValue()->isZero()) {
7930                 Value *InitValue = nullptr;
7931                 bool MultipleInitValues = false;
7932                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7933                   if (!LI->contains(PN->getIncomingBlock(i))) {
7934                     if (!InitValue)
7935                       InitValue = PN->getIncomingValue(i);
7936                     else if (InitValue != PN->getIncomingValue(i)) {
7937                       MultipleInitValues = true;
7938                       break;
7939                     }
7940                   }
7941                   if (!MultipleInitValues && InitValue)
7942                     return getSCEV(InitValue);
7943                 }
7944               }
7945               // Okay, we know how many times the containing loop executes.  If
7946               // this is a constant evolving PHI node, get the final value at
7947               // the specified iteration number.
7948               Constant *RV =
7949                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7950               if (RV) return getSCEV(RV);
7951             }
7952           }
7953 
7954       // Okay, this is an expression that we cannot symbolically evaluate
7955       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7956       // the arguments into constants, and if so, try to constant propagate the
7957       // result.  This is particularly useful for computing loop exit values.
7958       if (CanConstantFold(I)) {
7959         SmallVector<Constant *, 4> Operands;
7960         bool MadeImprovement = false;
7961         for (Value *Op : I->operands()) {
7962           if (Constant *C = dyn_cast<Constant>(Op)) {
7963             Operands.push_back(C);
7964             continue;
7965           }
7966 
7967           // If any of the operands is non-constant and if they are
7968           // non-integer and non-pointer, don't even try to analyze them
7969           // with scev techniques.
7970           if (!isSCEVable(Op->getType()))
7971             return V;
7972 
7973           const SCEV *OrigV = getSCEV(Op);
7974           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7975           MadeImprovement |= OrigV != OpV;
7976 
7977           Constant *C = BuildConstantFromSCEV(OpV);
7978           if (!C) return V;
7979           if (C->getType() != Op->getType())
7980             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7981                                                               Op->getType(),
7982                                                               false),
7983                                       C, Op->getType());
7984           Operands.push_back(C);
7985         }
7986 
7987         // Check to see if getSCEVAtScope actually made an improvement.
7988         if (MadeImprovement) {
7989           Constant *C = nullptr;
7990           const DataLayout &DL = getDataLayout();
7991           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7992             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7993                                                 Operands[1], DL, &TLI);
7994           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7995             if (!LI->isVolatile())
7996               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7997           } else
7998             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7999           if (!C) return V;
8000           return getSCEV(C);
8001         }
8002       }
8003     }
8004 
8005     // This is some other type of SCEVUnknown, just return it.
8006     return V;
8007   }
8008 
8009   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8010     // Avoid performing the look-up in the common case where the specified
8011     // expression has no loop-variant portions.
8012     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8013       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8014       if (OpAtScope != Comm->getOperand(i)) {
8015         // Okay, at least one of these operands is loop variant but might be
8016         // foldable.  Build a new instance of the folded commutative expression.
8017         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8018                                             Comm->op_begin()+i);
8019         NewOps.push_back(OpAtScope);
8020 
8021         for (++i; i != e; ++i) {
8022           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8023           NewOps.push_back(OpAtScope);
8024         }
8025         if (isa<SCEVAddExpr>(Comm))
8026           return getAddExpr(NewOps);
8027         if (isa<SCEVMulExpr>(Comm))
8028           return getMulExpr(NewOps);
8029         if (isa<SCEVSMaxExpr>(Comm))
8030           return getSMaxExpr(NewOps);
8031         if (isa<SCEVUMaxExpr>(Comm))
8032           return getUMaxExpr(NewOps);
8033         llvm_unreachable("Unknown commutative SCEV type!");
8034       }
8035     }
8036     // If we got here, all operands are loop invariant.
8037     return Comm;
8038   }
8039 
8040   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8041     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8042     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8043     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8044       return Div;   // must be loop invariant
8045     return getUDivExpr(LHS, RHS);
8046   }
8047 
8048   // If this is a loop recurrence for a loop that does not contain L, then we
8049   // are dealing with the final value computed by the loop.
8050   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8051     // First, attempt to evaluate each operand.
8052     // Avoid performing the look-up in the common case where the specified
8053     // expression has no loop-variant portions.
8054     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8055       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8056       if (OpAtScope == AddRec->getOperand(i))
8057         continue;
8058 
8059       // Okay, at least one of these operands is loop variant but might be
8060       // foldable.  Build a new instance of the folded commutative expression.
8061       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8062                                           AddRec->op_begin()+i);
8063       NewOps.push_back(OpAtScope);
8064       for (++i; i != e; ++i)
8065         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8066 
8067       const SCEV *FoldedRec =
8068         getAddRecExpr(NewOps, AddRec->getLoop(),
8069                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8070       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8071       // The addrec may be folded to a nonrecurrence, for example, if the
8072       // induction variable is multiplied by zero after constant folding. Go
8073       // ahead and return the folded value.
8074       if (!AddRec)
8075         return FoldedRec;
8076       break;
8077     }
8078 
8079     // If the scope is outside the addrec's loop, evaluate it by using the
8080     // loop exit value of the addrec.
8081     if (!AddRec->getLoop()->contains(L)) {
8082       // To evaluate this recurrence, we need to know how many times the AddRec
8083       // loop iterates.  Compute this now.
8084       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8085       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8086 
8087       // Then, evaluate the AddRec.
8088       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8089     }
8090 
8091     return AddRec;
8092   }
8093 
8094   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8095     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8096     if (Op == Cast->getOperand())
8097       return Cast;  // must be loop invariant
8098     return getZeroExtendExpr(Op, Cast->getType());
8099   }
8100 
8101   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8102     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8103     if (Op == Cast->getOperand())
8104       return Cast;  // must be loop invariant
8105     return getSignExtendExpr(Op, Cast->getType());
8106   }
8107 
8108   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8109     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8110     if (Op == Cast->getOperand())
8111       return Cast;  // must be loop invariant
8112     return getTruncateExpr(Op, Cast->getType());
8113   }
8114 
8115   llvm_unreachable("Unknown SCEV type!");
8116 }
8117 
8118 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8119   return getSCEVAtScope(getSCEV(V), L);
8120 }
8121 
8122 /// Finds the minimum unsigned root of the following equation:
8123 ///
8124 ///     A * X = B (mod N)
8125 ///
8126 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8127 /// A and B isn't important.
8128 ///
8129 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8130 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8131                                                ScalarEvolution &SE) {
8132   uint32_t BW = A.getBitWidth();
8133   assert(BW == SE.getTypeSizeInBits(B->getType()));
8134   assert(A != 0 && "A must be non-zero.");
8135 
8136   // 1. D = gcd(A, N)
8137   //
8138   // The gcd of A and N may have only one prime factor: 2. The number of
8139   // trailing zeros in A is its multiplicity
8140   uint32_t Mult2 = A.countTrailingZeros();
8141   // D = 2^Mult2
8142 
8143   // 2. Check if B is divisible by D.
8144   //
8145   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8146   // is not less than multiplicity of this prime factor for D.
8147   if (SE.GetMinTrailingZeros(B) < Mult2)
8148     return SE.getCouldNotCompute();
8149 
8150   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8151   // modulo (N / D).
8152   //
8153   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8154   // (N / D) in general. The inverse itself always fits into BW bits, though,
8155   // so we immediately truncate it.
8156   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8157   APInt Mod(BW + 1, 0);
8158   Mod.setBit(BW - Mult2);  // Mod = N / D
8159   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8160 
8161   // 4. Compute the minimum unsigned root of the equation:
8162   // I * (B / D) mod (N / D)
8163   // To simplify the computation, we factor out the divide by D:
8164   // (I * B mod N) / D
8165   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8166   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8167 }
8168 
8169 /// Find the roots of the quadratic equation for the given quadratic chrec
8170 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8171 /// two SCEVCouldNotCompute objects.
8172 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8173 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8174   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8175   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8176   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8177   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8178 
8179   // We currently can only solve this if the coefficients are constants.
8180   if (!LC || !MC || !NC)
8181     return None;
8182 
8183   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8184   const APInt &L = LC->getAPInt();
8185   const APInt &M = MC->getAPInt();
8186   const APInt &N = NC->getAPInt();
8187   APInt Two(BitWidth, 2);
8188 
8189   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8190 
8191   // The A coefficient is N/2
8192   APInt A = N.sdiv(Two);
8193 
8194   // The B coefficient is M-N/2
8195   APInt B = M;
8196   B -= A; // A is the same as N/2.
8197 
8198   // The C coefficient is L.
8199   const APInt& C = L;
8200 
8201   // Compute the B^2-4ac term.
8202   APInt SqrtTerm = B;
8203   SqrtTerm *= B;
8204   SqrtTerm -= 4 * (A * C);
8205 
8206   if (SqrtTerm.isNegative()) {
8207     // The loop is provably infinite.
8208     return None;
8209   }
8210 
8211   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8212   // integer value or else APInt::sqrt() will assert.
8213   APInt SqrtVal = SqrtTerm.sqrt();
8214 
8215   // Compute the two solutions for the quadratic formula.
8216   // The divisions must be performed as signed divisions.
8217   APInt NegB = -std::move(B);
8218   APInt TwoA = std::move(A);
8219   TwoA <<= 1;
8220   if (TwoA.isNullValue())
8221     return None;
8222 
8223   LLVMContext &Context = SE.getContext();
8224 
8225   ConstantInt *Solution1 =
8226     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8227   ConstantInt *Solution2 =
8228     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8229 
8230   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8231                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8232 }
8233 
8234 ScalarEvolution::ExitLimit
8235 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8236                               bool AllowPredicates) {
8237 
8238   // This is only used for loops with a "x != y" exit test. The exit condition
8239   // is now expressed as a single expression, V = x-y. So the exit test is
8240   // effectively V != 0.  We know and take advantage of the fact that this
8241   // expression only being used in a comparison by zero context.
8242 
8243   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8244   // If the value is a constant
8245   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8246     // If the value is already zero, the branch will execute zero times.
8247     if (C->getValue()->isZero()) return C;
8248     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8249   }
8250 
8251   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8252   if (!AddRec && AllowPredicates)
8253     // Try to make this an AddRec using runtime tests, in the first X
8254     // iterations of this loop, where X is the SCEV expression found by the
8255     // algorithm below.
8256     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8257 
8258   if (!AddRec || AddRec->getLoop() != L)
8259     return getCouldNotCompute();
8260 
8261   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8262   // the quadratic equation to solve it.
8263   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8264     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8265       const SCEVConstant *R1 = Roots->first;
8266       const SCEVConstant *R2 = Roots->second;
8267       // Pick the smallest positive root value.
8268       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8269               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8270         if (!CB->getZExtValue())
8271           std::swap(R1, R2); // R1 is the minimum root now.
8272 
8273         // We can only use this value if the chrec ends up with an exact zero
8274         // value at this index.  When solving for "X*X != 5", for example, we
8275         // should not accept a root of 2.
8276         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8277         if (Val->isZero())
8278           // We found a quadratic root!
8279           return ExitLimit(R1, R1, false, Predicates);
8280       }
8281     }
8282     return getCouldNotCompute();
8283   }
8284 
8285   // Otherwise we can only handle this if it is affine.
8286   if (!AddRec->isAffine())
8287     return getCouldNotCompute();
8288 
8289   // If this is an affine expression, the execution count of this branch is
8290   // the minimum unsigned root of the following equation:
8291   //
8292   //     Start + Step*N = 0 (mod 2^BW)
8293   //
8294   // equivalent to:
8295   //
8296   //             Step*N = -Start (mod 2^BW)
8297   //
8298   // where BW is the common bit width of Start and Step.
8299 
8300   // Get the initial value for the loop.
8301   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8302   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8303 
8304   // For now we handle only constant steps.
8305   //
8306   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8307   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8308   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8309   // We have not yet seen any such cases.
8310   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8311   if (!StepC || StepC->getValue()->isZero())
8312     return getCouldNotCompute();
8313 
8314   // For positive steps (counting up until unsigned overflow):
8315   //   N = -Start/Step (as unsigned)
8316   // For negative steps (counting down to zero):
8317   //   N = Start/-Step
8318   // First compute the unsigned distance from zero in the direction of Step.
8319   bool CountDown = StepC->getAPInt().isNegative();
8320   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8321 
8322   // Handle unitary steps, which cannot wraparound.
8323   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8324   //   N = Distance (as unsigned)
8325   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8326     APInt MaxBECount = getUnsignedRangeMax(Distance);
8327 
8328     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8329     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8330     // case, and see if we can improve the bound.
8331     //
8332     // Explicitly handling this here is necessary because getUnsignedRange
8333     // isn't context-sensitive; it doesn't know that we only care about the
8334     // range inside the loop.
8335     const SCEV *Zero = getZero(Distance->getType());
8336     const SCEV *One = getOne(Distance->getType());
8337     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8338     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8339       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8340       // as "unsigned_max(Distance + 1) - 1".
8341       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8342       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8343     }
8344     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8345   }
8346 
8347   // If the condition controls loop exit (the loop exits only if the expression
8348   // is true) and the addition is no-wrap we can use unsigned divide to
8349   // compute the backedge count.  In this case, the step may not divide the
8350   // distance, but we don't care because if the condition is "missed" the loop
8351   // will have undefined behavior due to wrapping.
8352   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8353       loopHasNoAbnormalExits(AddRec->getLoop())) {
8354     const SCEV *Exact =
8355         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8356     const SCEV *Max =
8357         Exact == getCouldNotCompute()
8358             ? Exact
8359             : getConstant(getUnsignedRangeMax(Exact));
8360     return ExitLimit(Exact, Max, false, Predicates);
8361   }
8362 
8363   // Solve the general equation.
8364   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8365                                                getNegativeSCEV(Start), *this);
8366   const SCEV *M = E == getCouldNotCompute()
8367                       ? E
8368                       : getConstant(getUnsignedRangeMax(E));
8369   return ExitLimit(E, M, false, Predicates);
8370 }
8371 
8372 ScalarEvolution::ExitLimit
8373 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8374   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8375   // handle them yet except for the trivial case.  This could be expanded in the
8376   // future as needed.
8377 
8378   // If the value is a constant, check to see if it is known to be non-zero
8379   // already.  If so, the backedge will execute zero times.
8380   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8381     if (!C->getValue()->isZero())
8382       return getZero(C->getType());
8383     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8384   }
8385 
8386   // We could implement others, but I really doubt anyone writes loops like
8387   // this, and if they did, they would already be constant folded.
8388   return getCouldNotCompute();
8389 }
8390 
8391 std::pair<BasicBlock *, BasicBlock *>
8392 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8393   // If the block has a unique predecessor, then there is no path from the
8394   // predecessor to the block that does not go through the direct edge
8395   // from the predecessor to the block.
8396   if (BasicBlock *Pred = BB->getSinglePredecessor())
8397     return {Pred, BB};
8398 
8399   // A loop's header is defined to be a block that dominates the loop.
8400   // If the header has a unique predecessor outside the loop, it must be
8401   // a block that has exactly one successor that can reach the loop.
8402   if (Loop *L = LI.getLoopFor(BB))
8403     return {L->getLoopPredecessor(), L->getHeader()};
8404 
8405   return {nullptr, nullptr};
8406 }
8407 
8408 /// SCEV structural equivalence is usually sufficient for testing whether two
8409 /// expressions are equal, however for the purposes of looking for a condition
8410 /// guarding a loop, it can be useful to be a little more general, since a
8411 /// front-end may have replicated the controlling expression.
8412 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8413   // Quick check to see if they are the same SCEV.
8414   if (A == B) return true;
8415 
8416   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8417     // Not all instructions that are "identical" compute the same value.  For
8418     // instance, two distinct alloca instructions allocating the same type are
8419     // identical and do not read memory; but compute distinct values.
8420     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8421   };
8422 
8423   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8424   // two different instructions with the same value. Check for this case.
8425   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8426     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8427       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8428         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8429           if (ComputesEqualValues(AI, BI))
8430             return true;
8431 
8432   // Otherwise assume they may have a different value.
8433   return false;
8434 }
8435 
8436 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8437                                            const SCEV *&LHS, const SCEV *&RHS,
8438                                            unsigned Depth) {
8439   bool Changed = false;
8440 
8441   // If we hit the max recursion limit bail out.
8442   if (Depth >= 3)
8443     return false;
8444 
8445   // Canonicalize a constant to the right side.
8446   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8447     // Check for both operands constant.
8448     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8449       if (ConstantExpr::getICmp(Pred,
8450                                 LHSC->getValue(),
8451                                 RHSC->getValue())->isNullValue())
8452         goto trivially_false;
8453       else
8454         goto trivially_true;
8455     }
8456     // Otherwise swap the operands to put the constant on the right.
8457     std::swap(LHS, RHS);
8458     Pred = ICmpInst::getSwappedPredicate(Pred);
8459     Changed = true;
8460   }
8461 
8462   // If we're comparing an addrec with a value which is loop-invariant in the
8463   // addrec's loop, put the addrec on the left. Also make a dominance check,
8464   // as both operands could be addrecs loop-invariant in each other's loop.
8465   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8466     const Loop *L = AR->getLoop();
8467     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8468       std::swap(LHS, RHS);
8469       Pred = ICmpInst::getSwappedPredicate(Pred);
8470       Changed = true;
8471     }
8472   }
8473 
8474   // If there's a constant operand, canonicalize comparisons with boundary
8475   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8476   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8477     const APInt &RA = RC->getAPInt();
8478 
8479     bool SimplifiedByConstantRange = false;
8480 
8481     if (!ICmpInst::isEquality(Pred)) {
8482       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8483       if (ExactCR.isFullSet())
8484         goto trivially_true;
8485       else if (ExactCR.isEmptySet())
8486         goto trivially_false;
8487 
8488       APInt NewRHS;
8489       CmpInst::Predicate NewPred;
8490       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8491           ICmpInst::isEquality(NewPred)) {
8492         // We were able to convert an inequality to an equality.
8493         Pred = NewPred;
8494         RHS = getConstant(NewRHS);
8495         Changed = SimplifiedByConstantRange = true;
8496       }
8497     }
8498 
8499     if (!SimplifiedByConstantRange) {
8500       switch (Pred) {
8501       default:
8502         break;
8503       case ICmpInst::ICMP_EQ:
8504       case ICmpInst::ICMP_NE:
8505         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8506         if (!RA)
8507           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8508             if (const SCEVMulExpr *ME =
8509                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8510               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8511                   ME->getOperand(0)->isAllOnesValue()) {
8512                 RHS = AE->getOperand(1);
8513                 LHS = ME->getOperand(1);
8514                 Changed = true;
8515               }
8516         break;
8517 
8518 
8519         // The "Should have been caught earlier!" messages refer to the fact
8520         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8521         // should have fired on the corresponding cases, and canonicalized the
8522         // check to trivially_true or trivially_false.
8523 
8524       case ICmpInst::ICMP_UGE:
8525         assert(!RA.isMinValue() && "Should have been caught earlier!");
8526         Pred = ICmpInst::ICMP_UGT;
8527         RHS = getConstant(RA - 1);
8528         Changed = true;
8529         break;
8530       case ICmpInst::ICMP_ULE:
8531         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8532         Pred = ICmpInst::ICMP_ULT;
8533         RHS = getConstant(RA + 1);
8534         Changed = true;
8535         break;
8536       case ICmpInst::ICMP_SGE:
8537         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8538         Pred = ICmpInst::ICMP_SGT;
8539         RHS = getConstant(RA - 1);
8540         Changed = true;
8541         break;
8542       case ICmpInst::ICMP_SLE:
8543         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8544         Pred = ICmpInst::ICMP_SLT;
8545         RHS = getConstant(RA + 1);
8546         Changed = true;
8547         break;
8548       }
8549     }
8550   }
8551 
8552   // Check for obvious equality.
8553   if (HasSameValue(LHS, RHS)) {
8554     if (ICmpInst::isTrueWhenEqual(Pred))
8555       goto trivially_true;
8556     if (ICmpInst::isFalseWhenEqual(Pred))
8557       goto trivially_false;
8558   }
8559 
8560   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8561   // adding or subtracting 1 from one of the operands.
8562   switch (Pred) {
8563   case ICmpInst::ICMP_SLE:
8564     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8565       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8566                        SCEV::FlagNSW);
8567       Pred = ICmpInst::ICMP_SLT;
8568       Changed = true;
8569     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8570       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8571                        SCEV::FlagNSW);
8572       Pred = ICmpInst::ICMP_SLT;
8573       Changed = true;
8574     }
8575     break;
8576   case ICmpInst::ICMP_SGE:
8577     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8578       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8579                        SCEV::FlagNSW);
8580       Pred = ICmpInst::ICMP_SGT;
8581       Changed = true;
8582     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8583       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8584                        SCEV::FlagNSW);
8585       Pred = ICmpInst::ICMP_SGT;
8586       Changed = true;
8587     }
8588     break;
8589   case ICmpInst::ICMP_ULE:
8590     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8591       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8592                        SCEV::FlagNUW);
8593       Pred = ICmpInst::ICMP_ULT;
8594       Changed = true;
8595     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8596       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8597       Pred = ICmpInst::ICMP_ULT;
8598       Changed = true;
8599     }
8600     break;
8601   case ICmpInst::ICMP_UGE:
8602     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8603       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8604       Pred = ICmpInst::ICMP_UGT;
8605       Changed = true;
8606     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8607       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8608                        SCEV::FlagNUW);
8609       Pred = ICmpInst::ICMP_UGT;
8610       Changed = true;
8611     }
8612     break;
8613   default:
8614     break;
8615   }
8616 
8617   // TODO: More simplifications are possible here.
8618 
8619   // Recursively simplify until we either hit a recursion limit or nothing
8620   // changes.
8621   if (Changed)
8622     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8623 
8624   return Changed;
8625 
8626 trivially_true:
8627   // Return 0 == 0.
8628   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8629   Pred = ICmpInst::ICMP_EQ;
8630   return true;
8631 
8632 trivially_false:
8633   // Return 0 != 0.
8634   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8635   Pred = ICmpInst::ICMP_NE;
8636   return true;
8637 }
8638 
8639 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8640   return getSignedRangeMax(S).isNegative();
8641 }
8642 
8643 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8644   return getSignedRangeMin(S).isStrictlyPositive();
8645 }
8646 
8647 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8648   return !getSignedRangeMin(S).isNegative();
8649 }
8650 
8651 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8652   return !getSignedRangeMax(S).isStrictlyPositive();
8653 }
8654 
8655 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8656   return isKnownNegative(S) || isKnownPositive(S);
8657 }
8658 
8659 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8660                                        const SCEV *LHS, const SCEV *RHS) {
8661   // Canonicalize the inputs first.
8662   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8663 
8664   // If LHS or RHS is an addrec, check to see if the condition is true in
8665   // every iteration of the loop.
8666   // If LHS and RHS are both addrec, both conditions must be true in
8667   // every iteration of the loop.
8668   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8669   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8670   bool LeftGuarded = false;
8671   bool RightGuarded = false;
8672   if (LAR) {
8673     const Loop *L = LAR->getLoop();
8674     if (isAvailableAtLoopEntry(RHS, L) &&
8675         isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
8676         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8677       if (!RAR) return true;
8678       LeftGuarded = true;
8679     }
8680   }
8681   if (RAR) {
8682     const Loop *L = RAR->getLoop();
8683     if (isAvailableAtLoopEntry(LHS, L) &&
8684         isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8685         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8686       if (!LAR) return true;
8687       RightGuarded = true;
8688     }
8689   }
8690   if (LeftGuarded && RightGuarded)
8691     return true;
8692 
8693   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8694     return true;
8695 
8696   // Otherwise see what can be done with known constant ranges.
8697   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8698 }
8699 
8700 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8701                                            ICmpInst::Predicate Pred,
8702                                            bool &Increasing) {
8703   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8704 
8705 #ifndef NDEBUG
8706   // Verify an invariant: inverting the predicate should turn a monotonically
8707   // increasing change to a monotonically decreasing one, and vice versa.
8708   bool IncreasingSwapped;
8709   bool ResultSwapped = isMonotonicPredicateImpl(
8710       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8711 
8712   assert(Result == ResultSwapped && "should be able to analyze both!");
8713   if (ResultSwapped)
8714     assert(Increasing == !IncreasingSwapped &&
8715            "monotonicity should flip as we flip the predicate");
8716 #endif
8717 
8718   return Result;
8719 }
8720 
8721 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8722                                                ICmpInst::Predicate Pred,
8723                                                bool &Increasing) {
8724 
8725   // A zero step value for LHS means the induction variable is essentially a
8726   // loop invariant value. We don't really depend on the predicate actually
8727   // flipping from false to true (for increasing predicates, and the other way
8728   // around for decreasing predicates), all we care about is that *if* the
8729   // predicate changes then it only changes from false to true.
8730   //
8731   // A zero step value in itself is not very useful, but there may be places
8732   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8733   // as general as possible.
8734 
8735   switch (Pred) {
8736   default:
8737     return false; // Conservative answer
8738 
8739   case ICmpInst::ICMP_UGT:
8740   case ICmpInst::ICMP_UGE:
8741   case ICmpInst::ICMP_ULT:
8742   case ICmpInst::ICMP_ULE:
8743     if (!LHS->hasNoUnsignedWrap())
8744       return false;
8745 
8746     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8747     return true;
8748 
8749   case ICmpInst::ICMP_SGT:
8750   case ICmpInst::ICMP_SGE:
8751   case ICmpInst::ICMP_SLT:
8752   case ICmpInst::ICMP_SLE: {
8753     if (!LHS->hasNoSignedWrap())
8754       return false;
8755 
8756     const SCEV *Step = LHS->getStepRecurrence(*this);
8757 
8758     if (isKnownNonNegative(Step)) {
8759       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8760       return true;
8761     }
8762 
8763     if (isKnownNonPositive(Step)) {
8764       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8765       return true;
8766     }
8767 
8768     return false;
8769   }
8770 
8771   }
8772 
8773   llvm_unreachable("switch has default clause!");
8774 }
8775 
8776 bool ScalarEvolution::isLoopInvariantPredicate(
8777     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8778     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8779     const SCEV *&InvariantRHS) {
8780 
8781   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8782   if (!isLoopInvariant(RHS, L)) {
8783     if (!isLoopInvariant(LHS, L))
8784       return false;
8785 
8786     std::swap(LHS, RHS);
8787     Pred = ICmpInst::getSwappedPredicate(Pred);
8788   }
8789 
8790   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8791   if (!ArLHS || ArLHS->getLoop() != L)
8792     return false;
8793 
8794   bool Increasing;
8795   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8796     return false;
8797 
8798   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8799   // true as the loop iterates, and the backedge is control dependent on
8800   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8801   //
8802   //   * if the predicate was false in the first iteration then the predicate
8803   //     is never evaluated again, since the loop exits without taking the
8804   //     backedge.
8805   //   * if the predicate was true in the first iteration then it will
8806   //     continue to be true for all future iterations since it is
8807   //     monotonically increasing.
8808   //
8809   // For both the above possibilities, we can replace the loop varying
8810   // predicate with its value on the first iteration of the loop (which is
8811   // loop invariant).
8812   //
8813   // A similar reasoning applies for a monotonically decreasing predicate, by
8814   // replacing true with false and false with true in the above two bullets.
8815 
8816   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8817 
8818   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8819     return false;
8820 
8821   InvariantPred = Pred;
8822   InvariantLHS = ArLHS->getStart();
8823   InvariantRHS = RHS;
8824   return true;
8825 }
8826 
8827 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8828     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8829   if (HasSameValue(LHS, RHS))
8830     return ICmpInst::isTrueWhenEqual(Pred);
8831 
8832   // This code is split out from isKnownPredicate because it is called from
8833   // within isLoopEntryGuardedByCond.
8834 
8835   auto CheckRanges =
8836       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8837     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8838         .contains(RangeLHS);
8839   };
8840 
8841   // The check at the top of the function catches the case where the values are
8842   // known to be equal.
8843   if (Pred == CmpInst::ICMP_EQ)
8844     return false;
8845 
8846   if (Pred == CmpInst::ICMP_NE)
8847     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8848            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8849            isKnownNonZero(getMinusSCEV(LHS, RHS));
8850 
8851   if (CmpInst::isSigned(Pred))
8852     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8853 
8854   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8855 }
8856 
8857 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8858                                                     const SCEV *LHS,
8859                                                     const SCEV *RHS) {
8860   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8861   // Return Y via OutY.
8862   auto MatchBinaryAddToConst =
8863       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8864              SCEV::NoWrapFlags ExpectedFlags) {
8865     const SCEV *NonConstOp, *ConstOp;
8866     SCEV::NoWrapFlags FlagsPresent;
8867 
8868     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8869         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8870       return false;
8871 
8872     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8873     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8874   };
8875 
8876   APInt C;
8877 
8878   switch (Pred) {
8879   default:
8880     break;
8881 
8882   case ICmpInst::ICMP_SGE:
8883     std::swap(LHS, RHS);
8884     LLVM_FALLTHROUGH;
8885   case ICmpInst::ICMP_SLE:
8886     // X s<= (X + C)<nsw> if C >= 0
8887     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8888       return true;
8889 
8890     // (X + C)<nsw> s<= X if C <= 0
8891     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8892         !C.isStrictlyPositive())
8893       return true;
8894     break;
8895 
8896   case ICmpInst::ICMP_SGT:
8897     std::swap(LHS, RHS);
8898     LLVM_FALLTHROUGH;
8899   case ICmpInst::ICMP_SLT:
8900     // X s< (X + C)<nsw> if C > 0
8901     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8902         C.isStrictlyPositive())
8903       return true;
8904 
8905     // (X + C)<nsw> s< X if C < 0
8906     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8907       return true;
8908     break;
8909   }
8910 
8911   return false;
8912 }
8913 
8914 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8915                                                    const SCEV *LHS,
8916                                                    const SCEV *RHS) {
8917   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8918     return false;
8919 
8920   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8921   // the stack can result in exponential time complexity.
8922   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8923 
8924   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8925   //
8926   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8927   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8928   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8929   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8930   // use isKnownPredicate later if needed.
8931   return isKnownNonNegative(RHS) &&
8932          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8933          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8934 }
8935 
8936 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8937                                         ICmpInst::Predicate Pred,
8938                                         const SCEV *LHS, const SCEV *RHS) {
8939   // No need to even try if we know the module has no guards.
8940   if (!HasGuards)
8941     return false;
8942 
8943   return any_of(*BB, [&](Instruction &I) {
8944     using namespace llvm::PatternMatch;
8945 
8946     Value *Condition;
8947     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8948                          m_Value(Condition))) &&
8949            isImpliedCond(Pred, LHS, RHS, Condition, false);
8950   });
8951 }
8952 
8953 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8954 /// protected by a conditional between LHS and RHS.  This is used to
8955 /// to eliminate casts.
8956 bool
8957 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8958                                              ICmpInst::Predicate Pred,
8959                                              const SCEV *LHS, const SCEV *RHS) {
8960   // Interpret a null as meaning no loop, where there is obviously no guard
8961   // (interprocedural conditions notwithstanding).
8962   if (!L) return true;
8963 
8964   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8965     return true;
8966 
8967   BasicBlock *Latch = L->getLoopLatch();
8968   if (!Latch)
8969     return false;
8970 
8971   BranchInst *LoopContinuePredicate =
8972     dyn_cast<BranchInst>(Latch->getTerminator());
8973   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8974       isImpliedCond(Pred, LHS, RHS,
8975                     LoopContinuePredicate->getCondition(),
8976                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8977     return true;
8978 
8979   // We don't want more than one activation of the following loops on the stack
8980   // -- that can lead to O(n!) time complexity.
8981   if (WalkingBEDominatingConds)
8982     return false;
8983 
8984   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8985 
8986   // See if we can exploit a trip count to prove the predicate.
8987   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8988   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8989   if (LatchBECount != getCouldNotCompute()) {
8990     // We know that Latch branches back to the loop header exactly
8991     // LatchBECount times.  This means the backdege condition at Latch is
8992     // equivalent to  "{0,+,1} u< LatchBECount".
8993     Type *Ty = LatchBECount->getType();
8994     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8995     const SCEV *LoopCounter =
8996       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8997     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8998                       LatchBECount))
8999       return true;
9000   }
9001 
9002   // Check conditions due to any @llvm.assume intrinsics.
9003   for (auto &AssumeVH : AC.assumptions()) {
9004     if (!AssumeVH)
9005       continue;
9006     auto *CI = cast<CallInst>(AssumeVH);
9007     if (!DT.dominates(CI, Latch->getTerminator()))
9008       continue;
9009 
9010     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9011       return true;
9012   }
9013 
9014   // If the loop is not reachable from the entry block, we risk running into an
9015   // infinite loop as we walk up into the dom tree.  These loops do not matter
9016   // anyway, so we just return a conservative answer when we see them.
9017   if (!DT.isReachableFromEntry(L->getHeader()))
9018     return false;
9019 
9020   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9021     return true;
9022 
9023   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9024        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9025     assert(DTN && "should reach the loop header before reaching the root!");
9026 
9027     BasicBlock *BB = DTN->getBlock();
9028     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9029       return true;
9030 
9031     BasicBlock *PBB = BB->getSinglePredecessor();
9032     if (!PBB)
9033       continue;
9034 
9035     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9036     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9037       continue;
9038 
9039     Value *Condition = ContinuePredicate->getCondition();
9040 
9041     // If we have an edge `E` within the loop body that dominates the only
9042     // latch, the condition guarding `E` also guards the backedge.  This
9043     // reasoning works only for loops with a single latch.
9044 
9045     BasicBlockEdge DominatingEdge(PBB, BB);
9046     if (DominatingEdge.isSingleEdge()) {
9047       // We're constructively (and conservatively) enumerating edges within the
9048       // loop body that dominate the latch.  The dominator tree better agree
9049       // with us on this:
9050       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9051 
9052       if (isImpliedCond(Pred, LHS, RHS, Condition,
9053                         BB != ContinuePredicate->getSuccessor(0)))
9054         return true;
9055     }
9056   }
9057 
9058   return false;
9059 }
9060 
9061 bool
9062 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9063                                           ICmpInst::Predicate Pred,
9064                                           const SCEV *LHS, const SCEV *RHS) {
9065   // Interpret a null as meaning no loop, where there is obviously no guard
9066   // (interprocedural conditions notwithstanding).
9067   if (!L) return false;
9068 
9069   // Both LHS and RHS must be available at loop entry.
9070   assert(isAvailableAtLoopEntry(LHS, L) &&
9071          "LHS is not available at Loop Entry");
9072   assert(isAvailableAtLoopEntry(RHS, L) &&
9073          "RHS is not available at Loop Entry");
9074 
9075   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
9076     return true;
9077 
9078   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9079   // the facts (a >= b && a != b) separately. A typical situation is when the
9080   // non-strict comparison is known from ranges and non-equality is known from
9081   // dominating predicates. If we are proving strict comparison, we always try
9082   // to prove non-equality and non-strict comparison separately.
9083   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9084   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9085   bool ProvedNonStrictComparison = false;
9086   bool ProvedNonEquality = false;
9087 
9088   if (ProvingStrictComparison) {
9089     ProvedNonStrictComparison =
9090         isKnownPredicateViaConstantRanges(NonStrictPredicate, LHS, RHS);
9091     ProvedNonEquality =
9092         isKnownPredicateViaConstantRanges(ICmpInst::ICMP_NE, LHS, RHS);
9093     if (ProvedNonStrictComparison && ProvedNonEquality)
9094       return true;
9095   }
9096 
9097   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9098   auto ProveViaGuard = [&](BasicBlock *Block) {
9099     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9100       return true;
9101     if (ProvingStrictComparison) {
9102       if (!ProvedNonStrictComparison)
9103         ProvedNonStrictComparison =
9104             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9105       if (!ProvedNonEquality)
9106         ProvedNonEquality =
9107             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9108       if (ProvedNonStrictComparison && ProvedNonEquality)
9109         return true;
9110     }
9111     return false;
9112   };
9113 
9114   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9115   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9116     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9117       return true;
9118     if (ProvingStrictComparison) {
9119       if (!ProvedNonStrictComparison)
9120         ProvedNonStrictComparison =
9121             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9122       if (!ProvedNonEquality)
9123         ProvedNonEquality =
9124             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9125       if (ProvedNonStrictComparison && ProvedNonEquality)
9126         return true;
9127     }
9128     return false;
9129   };
9130 
9131   // Starting at the loop predecessor, climb up the predecessor chain, as long
9132   // as there are predecessors that can be found that have unique successors
9133   // leading to the original header.
9134   for (std::pair<BasicBlock *, BasicBlock *>
9135          Pair(L->getLoopPredecessor(), L->getHeader());
9136        Pair.first;
9137        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9138 
9139     if (ProveViaGuard(Pair.first))
9140       return true;
9141 
9142     BranchInst *LoopEntryPredicate =
9143       dyn_cast<BranchInst>(Pair.first->getTerminator());
9144     if (!LoopEntryPredicate ||
9145         LoopEntryPredicate->isUnconditional())
9146       continue;
9147 
9148     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9149                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9150       return true;
9151   }
9152 
9153   // Check conditions due to any @llvm.assume intrinsics.
9154   for (auto &AssumeVH : AC.assumptions()) {
9155     if (!AssumeVH)
9156       continue;
9157     auto *CI = cast<CallInst>(AssumeVH);
9158     if (!DT.dominates(CI, L->getHeader()))
9159       continue;
9160 
9161     if (ProveViaCond(CI->getArgOperand(0), false))
9162       return true;
9163   }
9164 
9165   return false;
9166 }
9167 
9168 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9169                                     const SCEV *LHS, const SCEV *RHS,
9170                                     Value *FoundCondValue,
9171                                     bool Inverse) {
9172   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9173     return false;
9174 
9175   auto ClearOnExit =
9176       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9177 
9178   // Recursively handle And and Or conditions.
9179   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9180     if (BO->getOpcode() == Instruction::And) {
9181       if (!Inverse)
9182         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9183                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9184     } else if (BO->getOpcode() == Instruction::Or) {
9185       if (Inverse)
9186         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9187                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9188     }
9189   }
9190 
9191   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9192   if (!ICI) return false;
9193 
9194   // Now that we found a conditional branch that dominates the loop or controls
9195   // the loop latch. Check to see if it is the comparison we are looking for.
9196   ICmpInst::Predicate FoundPred;
9197   if (Inverse)
9198     FoundPred = ICI->getInversePredicate();
9199   else
9200     FoundPred = ICI->getPredicate();
9201 
9202   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9203   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9204 
9205   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9206 }
9207 
9208 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9209                                     const SCEV *RHS,
9210                                     ICmpInst::Predicate FoundPred,
9211                                     const SCEV *FoundLHS,
9212                                     const SCEV *FoundRHS) {
9213   // Balance the types.
9214   if (getTypeSizeInBits(LHS->getType()) <
9215       getTypeSizeInBits(FoundLHS->getType())) {
9216     if (CmpInst::isSigned(Pred)) {
9217       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9218       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9219     } else {
9220       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9221       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9222     }
9223   } else if (getTypeSizeInBits(LHS->getType()) >
9224       getTypeSizeInBits(FoundLHS->getType())) {
9225     if (CmpInst::isSigned(FoundPred)) {
9226       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9227       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9228     } else {
9229       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9230       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9231     }
9232   }
9233 
9234   // Canonicalize the query to match the way instcombine will have
9235   // canonicalized the comparison.
9236   if (SimplifyICmpOperands(Pred, LHS, RHS))
9237     if (LHS == RHS)
9238       return CmpInst::isTrueWhenEqual(Pred);
9239   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9240     if (FoundLHS == FoundRHS)
9241       return CmpInst::isFalseWhenEqual(FoundPred);
9242 
9243   // Check to see if we can make the LHS or RHS match.
9244   if (LHS == FoundRHS || RHS == FoundLHS) {
9245     if (isa<SCEVConstant>(RHS)) {
9246       std::swap(FoundLHS, FoundRHS);
9247       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9248     } else {
9249       std::swap(LHS, RHS);
9250       Pred = ICmpInst::getSwappedPredicate(Pred);
9251     }
9252   }
9253 
9254   // Check whether the found predicate is the same as the desired predicate.
9255   if (FoundPred == Pred)
9256     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9257 
9258   // Check whether swapping the found predicate makes it the same as the
9259   // desired predicate.
9260   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9261     if (isa<SCEVConstant>(RHS))
9262       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9263     else
9264       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9265                                    RHS, LHS, FoundLHS, FoundRHS);
9266   }
9267 
9268   // Unsigned comparison is the same as signed comparison when both the operands
9269   // are non-negative.
9270   if (CmpInst::isUnsigned(FoundPred) &&
9271       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9272       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9273     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9274 
9275   // Check if we can make progress by sharpening ranges.
9276   if (FoundPred == ICmpInst::ICMP_NE &&
9277       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9278 
9279     const SCEVConstant *C = nullptr;
9280     const SCEV *V = nullptr;
9281 
9282     if (isa<SCEVConstant>(FoundLHS)) {
9283       C = cast<SCEVConstant>(FoundLHS);
9284       V = FoundRHS;
9285     } else {
9286       C = cast<SCEVConstant>(FoundRHS);
9287       V = FoundLHS;
9288     }
9289 
9290     // The guarding predicate tells us that C != V. If the known range
9291     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9292     // range we consider has to correspond to same signedness as the
9293     // predicate we're interested in folding.
9294 
9295     APInt Min = ICmpInst::isSigned(Pred) ?
9296         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9297 
9298     if (Min == C->getAPInt()) {
9299       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9300       // This is true even if (Min + 1) wraps around -- in case of
9301       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9302 
9303       APInt SharperMin = Min + 1;
9304 
9305       switch (Pred) {
9306         case ICmpInst::ICMP_SGE:
9307         case ICmpInst::ICMP_UGE:
9308           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9309           // RHS, we're done.
9310           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9311                                     getConstant(SharperMin)))
9312             return true;
9313           LLVM_FALLTHROUGH;
9314 
9315         case ICmpInst::ICMP_SGT:
9316         case ICmpInst::ICMP_UGT:
9317           // We know from the range information that (V `Pred` Min ||
9318           // V == Min).  We know from the guarding condition that !(V
9319           // == Min).  This gives us
9320           //
9321           //       V `Pred` Min || V == Min && !(V == Min)
9322           //   =>  V `Pred` Min
9323           //
9324           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9325 
9326           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9327             return true;
9328           LLVM_FALLTHROUGH;
9329 
9330         default:
9331           // No change
9332           break;
9333       }
9334     }
9335   }
9336 
9337   // Check whether the actual condition is beyond sufficient.
9338   if (FoundPred == ICmpInst::ICMP_EQ)
9339     if (ICmpInst::isTrueWhenEqual(Pred))
9340       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9341         return true;
9342   if (Pred == ICmpInst::ICMP_NE)
9343     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9344       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9345         return true;
9346 
9347   // Otherwise assume the worst.
9348   return false;
9349 }
9350 
9351 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9352                                      const SCEV *&L, const SCEV *&R,
9353                                      SCEV::NoWrapFlags &Flags) {
9354   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9355   if (!AE || AE->getNumOperands() != 2)
9356     return false;
9357 
9358   L = AE->getOperand(0);
9359   R = AE->getOperand(1);
9360   Flags = AE->getNoWrapFlags();
9361   return true;
9362 }
9363 
9364 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9365                                                            const SCEV *Less) {
9366   // We avoid subtracting expressions here because this function is usually
9367   // fairly deep in the call stack (i.e. is called many times).
9368 
9369   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9370     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9371     const auto *MAR = cast<SCEVAddRecExpr>(More);
9372 
9373     if (LAR->getLoop() != MAR->getLoop())
9374       return None;
9375 
9376     // We look at affine expressions only; not for correctness but to keep
9377     // getStepRecurrence cheap.
9378     if (!LAR->isAffine() || !MAR->isAffine())
9379       return None;
9380 
9381     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9382       return None;
9383 
9384     Less = LAR->getStart();
9385     More = MAR->getStart();
9386 
9387     // fall through
9388   }
9389 
9390   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9391     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9392     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9393     return M - L;
9394   }
9395 
9396   const SCEV *L, *R;
9397   SCEV::NoWrapFlags Flags;
9398   if (splitBinaryAdd(Less, L, R, Flags))
9399     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9400       if (R == More)
9401         return -(LC->getAPInt());
9402 
9403   if (splitBinaryAdd(More, L, R, Flags))
9404     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9405       if (R == Less)
9406         return LC->getAPInt();
9407 
9408   return None;
9409 }
9410 
9411 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9412     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9413     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9414   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9415     return false;
9416 
9417   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9418   if (!AddRecLHS)
9419     return false;
9420 
9421   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9422   if (!AddRecFoundLHS)
9423     return false;
9424 
9425   // We'd like to let SCEV reason about control dependencies, so we constrain
9426   // both the inequalities to be about add recurrences on the same loop.  This
9427   // way we can use isLoopEntryGuardedByCond later.
9428 
9429   const Loop *L = AddRecFoundLHS->getLoop();
9430   if (L != AddRecLHS->getLoop())
9431     return false;
9432 
9433   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9434   //
9435   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9436   //                                                                  ... (2)
9437   //
9438   // Informal proof for (2), assuming (1) [*]:
9439   //
9440   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9441   //
9442   // Then
9443   //
9444   //       FoundLHS s< FoundRHS s< INT_MIN - C
9445   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9446   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9447   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9448   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9449   // <=>  FoundLHS + C s< FoundRHS + C
9450   //
9451   // [*]: (1) can be proved by ruling out overflow.
9452   //
9453   // [**]: This can be proved by analyzing all the four possibilities:
9454   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9455   //    (A s>= 0, B s>= 0).
9456   //
9457   // Note:
9458   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9459   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9460   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9461   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9462   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9463   // C)".
9464 
9465   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9466   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9467   if (!LDiff || !RDiff || *LDiff != *RDiff)
9468     return false;
9469 
9470   if (LDiff->isMinValue())
9471     return true;
9472 
9473   APInt FoundRHSLimit;
9474 
9475   if (Pred == CmpInst::ICMP_ULT) {
9476     FoundRHSLimit = -(*RDiff);
9477   } else {
9478     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9479     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9480   }
9481 
9482   // Try to prove (1) or (2), as needed.
9483   return isAvailableAtLoopEntry(FoundRHS, L) &&
9484          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9485                                   getConstant(FoundRHSLimit));
9486 }
9487 
9488 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9489                                             const SCEV *LHS, const SCEV *RHS,
9490                                             const SCEV *FoundLHS,
9491                                             const SCEV *FoundRHS) {
9492   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9493     return true;
9494 
9495   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9496     return true;
9497 
9498   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9499                                      FoundLHS, FoundRHS) ||
9500          // ~x < ~y --> x > y
9501          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9502                                      getNotSCEV(FoundRHS),
9503                                      getNotSCEV(FoundLHS));
9504 }
9505 
9506 /// If Expr computes ~A, return A else return nullptr
9507 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9508   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9509   if (!Add || Add->getNumOperands() != 2 ||
9510       !Add->getOperand(0)->isAllOnesValue())
9511     return nullptr;
9512 
9513   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9514   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9515       !AddRHS->getOperand(0)->isAllOnesValue())
9516     return nullptr;
9517 
9518   return AddRHS->getOperand(1);
9519 }
9520 
9521 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9522 template<typename MaxExprType>
9523 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9524                               const SCEV *Candidate) {
9525   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9526   if (!MaxExpr) return false;
9527 
9528   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9529 }
9530 
9531 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9532 template<typename MaxExprType>
9533 static bool IsMinConsistingOf(ScalarEvolution &SE,
9534                               const SCEV *MaybeMinExpr,
9535                               const SCEV *Candidate) {
9536   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9537   if (!MaybeMaxExpr)
9538     return false;
9539 
9540   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9541 }
9542 
9543 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9544                                            ICmpInst::Predicate Pred,
9545                                            const SCEV *LHS, const SCEV *RHS) {
9546   // If both sides are affine addrecs for the same loop, with equal
9547   // steps, and we know the recurrences don't wrap, then we only
9548   // need to check the predicate on the starting values.
9549 
9550   if (!ICmpInst::isRelational(Pred))
9551     return false;
9552 
9553   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9554   if (!LAR)
9555     return false;
9556   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9557   if (!RAR)
9558     return false;
9559   if (LAR->getLoop() != RAR->getLoop())
9560     return false;
9561   if (!LAR->isAffine() || !RAR->isAffine())
9562     return false;
9563 
9564   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9565     return false;
9566 
9567   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9568                          SCEV::FlagNSW : SCEV::FlagNUW;
9569   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9570     return false;
9571 
9572   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9573 }
9574 
9575 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9576 /// expression?
9577 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9578                                         ICmpInst::Predicate Pred,
9579                                         const SCEV *LHS, const SCEV *RHS) {
9580   switch (Pred) {
9581   default:
9582     return false;
9583 
9584   case ICmpInst::ICMP_SGE:
9585     std::swap(LHS, RHS);
9586     LLVM_FALLTHROUGH;
9587   case ICmpInst::ICMP_SLE:
9588     return
9589       // min(A, ...) <= A
9590       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9591       // A <= max(A, ...)
9592       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9593 
9594   case ICmpInst::ICMP_UGE:
9595     std::swap(LHS, RHS);
9596     LLVM_FALLTHROUGH;
9597   case ICmpInst::ICMP_ULE:
9598     return
9599       // min(A, ...) <= A
9600       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9601       // A <= max(A, ...)
9602       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9603   }
9604 
9605   llvm_unreachable("covered switch fell through?!");
9606 }
9607 
9608 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9609                                              const SCEV *LHS, const SCEV *RHS,
9610                                              const SCEV *FoundLHS,
9611                                              const SCEV *FoundRHS,
9612                                              unsigned Depth) {
9613   assert(getTypeSizeInBits(LHS->getType()) ==
9614              getTypeSizeInBits(RHS->getType()) &&
9615          "LHS and RHS have different sizes?");
9616   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9617              getTypeSizeInBits(FoundRHS->getType()) &&
9618          "FoundLHS and FoundRHS have different sizes?");
9619   // We want to avoid hurting the compile time with analysis of too big trees.
9620   if (Depth > MaxSCEVOperationsImplicationDepth)
9621     return false;
9622   // We only want to work with ICMP_SGT comparison so far.
9623   // TODO: Extend to ICMP_UGT?
9624   if (Pred == ICmpInst::ICMP_SLT) {
9625     Pred = ICmpInst::ICMP_SGT;
9626     std::swap(LHS, RHS);
9627     std::swap(FoundLHS, FoundRHS);
9628   }
9629   if (Pred != ICmpInst::ICMP_SGT)
9630     return false;
9631 
9632   auto GetOpFromSExt = [&](const SCEV *S) {
9633     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9634       return Ext->getOperand();
9635     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9636     // the constant in some cases.
9637     return S;
9638   };
9639 
9640   // Acquire values from extensions.
9641   auto *OrigFoundLHS = FoundLHS;
9642   LHS = GetOpFromSExt(LHS);
9643   FoundLHS = GetOpFromSExt(FoundLHS);
9644 
9645   // Is the SGT predicate can be proved trivially or using the found context.
9646   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9647     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9648            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9649                                   FoundRHS, Depth + 1);
9650   };
9651 
9652   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9653     // We want to avoid creation of any new non-constant SCEV. Since we are
9654     // going to compare the operands to RHS, we should be certain that we don't
9655     // need any size extensions for this. So let's decline all cases when the
9656     // sizes of types of LHS and RHS do not match.
9657     // TODO: Maybe try to get RHS from sext to catch more cases?
9658     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9659       return false;
9660 
9661     // Should not overflow.
9662     if (!LHSAddExpr->hasNoSignedWrap())
9663       return false;
9664 
9665     auto *LL = LHSAddExpr->getOperand(0);
9666     auto *LR = LHSAddExpr->getOperand(1);
9667     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9668 
9669     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9670     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9671       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9672     };
9673     // Try to prove the following rule:
9674     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9675     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9676     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9677       return true;
9678   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9679     Value *LL, *LR;
9680     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9681 
9682     using namespace llvm::PatternMatch;
9683 
9684     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9685       // Rules for division.
9686       // We are going to perform some comparisons with Denominator and its
9687       // derivative expressions. In general case, creating a SCEV for it may
9688       // lead to a complex analysis of the entire graph, and in particular it
9689       // can request trip count recalculation for the same loop. This would
9690       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9691       // this, we only want to create SCEVs that are constants in this section.
9692       // So we bail if Denominator is not a constant.
9693       if (!isa<ConstantInt>(LR))
9694         return false;
9695 
9696       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9697 
9698       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9699       // then a SCEV for the numerator already exists and matches with FoundLHS.
9700       auto *Numerator = getExistingSCEV(LL);
9701       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9702         return false;
9703 
9704       // Make sure that the numerator matches with FoundLHS and the denominator
9705       // is positive.
9706       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9707         return false;
9708 
9709       auto *DTy = Denominator->getType();
9710       auto *FRHSTy = FoundRHS->getType();
9711       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9712         // One of types is a pointer and another one is not. We cannot extend
9713         // them properly to a wider type, so let us just reject this case.
9714         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9715         // to avoid this check.
9716         return false;
9717 
9718       // Given that:
9719       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9720       auto *WTy = getWiderType(DTy, FRHSTy);
9721       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9722       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9723 
9724       // Try to prove the following rule:
9725       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9726       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9727       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9728       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9729       if (isKnownNonPositive(RHS) &&
9730           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9731         return true;
9732 
9733       // Try to prove the following rule:
9734       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9735       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9736       // If we divide it by Denominator > 2, then:
9737       // 1. If FoundLHS is negative, then the result is 0.
9738       // 2. If FoundLHS is non-negative, then the result is non-negative.
9739       // Anyways, the result is non-negative.
9740       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9741       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9742       if (isKnownNegative(RHS) &&
9743           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9744         return true;
9745     }
9746   }
9747 
9748   return false;
9749 }
9750 
9751 bool
9752 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9753                                            const SCEV *LHS, const SCEV *RHS) {
9754   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9755          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9756          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9757          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9758 }
9759 
9760 bool
9761 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9762                                              const SCEV *LHS, const SCEV *RHS,
9763                                              const SCEV *FoundLHS,
9764                                              const SCEV *FoundRHS) {
9765   switch (Pred) {
9766   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9767   case ICmpInst::ICMP_EQ:
9768   case ICmpInst::ICMP_NE:
9769     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9770       return true;
9771     break;
9772   case ICmpInst::ICMP_SLT:
9773   case ICmpInst::ICMP_SLE:
9774     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9775         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9776       return true;
9777     break;
9778   case ICmpInst::ICMP_SGT:
9779   case ICmpInst::ICMP_SGE:
9780     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9781         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9782       return true;
9783     break;
9784   case ICmpInst::ICMP_ULT:
9785   case ICmpInst::ICMP_ULE:
9786     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9787         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9788       return true;
9789     break;
9790   case ICmpInst::ICMP_UGT:
9791   case ICmpInst::ICMP_UGE:
9792     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9793         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9794       return true;
9795     break;
9796   }
9797 
9798   // Maybe it can be proved via operations?
9799   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9800     return true;
9801 
9802   return false;
9803 }
9804 
9805 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9806                                                      const SCEV *LHS,
9807                                                      const SCEV *RHS,
9808                                                      const SCEV *FoundLHS,
9809                                                      const SCEV *FoundRHS) {
9810   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9811     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9812     // reduce the compile time impact of this optimization.
9813     return false;
9814 
9815   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9816   if (!Addend)
9817     return false;
9818 
9819   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9820 
9821   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9822   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9823   ConstantRange FoundLHSRange =
9824       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9825 
9826   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9827   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9828 
9829   // We can also compute the range of values for `LHS` that satisfy the
9830   // consequent, "`LHS` `Pred` `RHS`":
9831   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9832   ConstantRange SatisfyingLHSRange =
9833       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9834 
9835   // The antecedent implies the consequent if every value of `LHS` that
9836   // satisfies the antecedent also satisfies the consequent.
9837   return SatisfyingLHSRange.contains(LHSRange);
9838 }
9839 
9840 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9841                                          bool IsSigned, bool NoWrap) {
9842   assert(isKnownPositive(Stride) && "Positive stride expected!");
9843 
9844   if (NoWrap) return false;
9845 
9846   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9847   const SCEV *One = getOne(Stride->getType());
9848 
9849   if (IsSigned) {
9850     APInt MaxRHS = getSignedRangeMax(RHS);
9851     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9852     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9853 
9854     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9855     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9856   }
9857 
9858   APInt MaxRHS = getUnsignedRangeMax(RHS);
9859   APInt MaxValue = APInt::getMaxValue(BitWidth);
9860   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9861 
9862   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9863   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9864 }
9865 
9866 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9867                                          bool IsSigned, bool NoWrap) {
9868   if (NoWrap) return false;
9869 
9870   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9871   const SCEV *One = getOne(Stride->getType());
9872 
9873   if (IsSigned) {
9874     APInt MinRHS = getSignedRangeMin(RHS);
9875     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9876     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9877 
9878     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9879     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9880   }
9881 
9882   APInt MinRHS = getUnsignedRangeMin(RHS);
9883   APInt MinValue = APInt::getMinValue(BitWidth);
9884   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9885 
9886   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9887   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9888 }
9889 
9890 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9891                                             bool Equality) {
9892   const SCEV *One = getOne(Step->getType());
9893   Delta = Equality ? getAddExpr(Delta, Step)
9894                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9895   return getUDivExpr(Delta, Step);
9896 }
9897 
9898 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
9899                                                     const SCEV *Stride,
9900                                                     const SCEV *End,
9901                                                     unsigned BitWidth,
9902                                                     bool IsSigned) {
9903 
9904   assert(!isKnownNonPositive(Stride) &&
9905          "Stride is expected strictly positive!");
9906   // Calculate the maximum backedge count based on the range of values
9907   // permitted by Start, End, and Stride.
9908   const SCEV *MaxBECount;
9909   APInt MinStart =
9910       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
9911 
9912   APInt StrideForMaxBECount =
9913       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
9914 
9915   // We already know that the stride is positive, so we paper over conservatism
9916   // in our range computation by forcing StrideForMaxBECount to be at least one.
9917   // In theory this is unnecessary, but we expect MaxBECount to be a
9918   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
9919   // is nothing to constant fold it to).
9920   APInt One(BitWidth, 1, IsSigned);
9921   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
9922 
9923   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
9924                             : APInt::getMaxValue(BitWidth);
9925   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
9926 
9927   // Although End can be a MAX expression we estimate MaxEnd considering only
9928   // the case End = RHS of the loop termination condition. This is safe because
9929   // in the other case (End - Start) is zero, leading to a zero maximum backedge
9930   // taken count.
9931   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
9932                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
9933 
9934   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
9935                               getConstant(StrideForMaxBECount) /* Step */,
9936                               false /* Equality */);
9937 
9938   return MaxBECount;
9939 }
9940 
9941 ScalarEvolution::ExitLimit
9942 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9943                                   const Loop *L, bool IsSigned,
9944                                   bool ControlsExit, bool AllowPredicates) {
9945   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9946 
9947   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9948   bool PredicatedIV = false;
9949 
9950   if (!IV && AllowPredicates) {
9951     // Try to make this an AddRec using runtime tests, in the first X
9952     // iterations of this loop, where X is the SCEV expression found by the
9953     // algorithm below.
9954     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9955     PredicatedIV = true;
9956   }
9957 
9958   // Avoid weird loops
9959   if (!IV || IV->getLoop() != L || !IV->isAffine())
9960     return getCouldNotCompute();
9961 
9962   bool NoWrap = ControlsExit &&
9963                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9964 
9965   const SCEV *Stride = IV->getStepRecurrence(*this);
9966 
9967   bool PositiveStride = isKnownPositive(Stride);
9968 
9969   // Avoid negative or zero stride values.
9970   if (!PositiveStride) {
9971     // We can compute the correct backedge taken count for loops with unknown
9972     // strides if we can prove that the loop is not an infinite loop with side
9973     // effects. Here's the loop structure we are trying to handle -
9974     //
9975     // i = start
9976     // do {
9977     //   A[i] = i;
9978     //   i += s;
9979     // } while (i < end);
9980     //
9981     // The backedge taken count for such loops is evaluated as -
9982     // (max(end, start + stride) - start - 1) /u stride
9983     //
9984     // The additional preconditions that we need to check to prove correctness
9985     // of the above formula is as follows -
9986     //
9987     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9988     //    NoWrap flag).
9989     // b) loop is single exit with no side effects.
9990     //
9991     //
9992     // Precondition a) implies that if the stride is negative, this is a single
9993     // trip loop. The backedge taken count formula reduces to zero in this case.
9994     //
9995     // Precondition b) implies that the unknown stride cannot be zero otherwise
9996     // we have UB.
9997     //
9998     // The positive stride case is the same as isKnownPositive(Stride) returning
9999     // true (original behavior of the function).
10000     //
10001     // We want to make sure that the stride is truly unknown as there are edge
10002     // cases where ScalarEvolution propagates no wrap flags to the
10003     // post-increment/decrement IV even though the increment/decrement operation
10004     // itself is wrapping. The computed backedge taken count may be wrong in
10005     // such cases. This is prevented by checking that the stride is not known to
10006     // be either positive or non-positive. For example, no wrap flags are
10007     // propagated to the post-increment IV of this loop with a trip count of 2 -
10008     //
10009     // unsigned char i;
10010     // for(i=127; i<128; i+=129)
10011     //   A[i] = i;
10012     //
10013     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10014         !loopHasNoSideEffects(L))
10015       return getCouldNotCompute();
10016   } else if (!Stride->isOne() &&
10017              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10018     // Avoid proven overflow cases: this will ensure that the backedge taken
10019     // count will not generate any unsigned overflow. Relaxed no-overflow
10020     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10021     // undefined behaviors like the case of C language.
10022     return getCouldNotCompute();
10023 
10024   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10025                                       : ICmpInst::ICMP_ULT;
10026   const SCEV *Start = IV->getStart();
10027   const SCEV *End = RHS;
10028   // When the RHS is not invariant, we do not know the end bound of the loop and
10029   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10030   // calculate the MaxBECount, given the start, stride and max value for the end
10031   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10032   // checked above).
10033   if (!isLoopInvariant(RHS, L)) {
10034     const SCEV *MaxBECount = computeMaxBECountForLT(
10035         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10036     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10037                      false /*MaxOrZero*/, Predicates);
10038   }
10039   // If the backedge is taken at least once, then it will be taken
10040   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10041   // is the LHS value of the less-than comparison the first time it is evaluated
10042   // and End is the RHS.
10043   const SCEV *BECountIfBackedgeTaken =
10044     computeBECount(getMinusSCEV(End, Start), Stride, false);
10045   // If the loop entry is guarded by the result of the backedge test of the
10046   // first loop iteration, then we know the backedge will be taken at least
10047   // once and so the backedge taken count is as above. If not then we use the
10048   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10049   // as if the backedge is taken at least once max(End,Start) is End and so the
10050   // result is as above, and if not max(End,Start) is Start so we get a backedge
10051   // count of zero.
10052   const SCEV *BECount;
10053   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10054     BECount = BECountIfBackedgeTaken;
10055   else {
10056     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10057     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10058   }
10059 
10060   const SCEV *MaxBECount;
10061   bool MaxOrZero = false;
10062   if (isa<SCEVConstant>(BECount))
10063     MaxBECount = BECount;
10064   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10065     // If we know exactly how many times the backedge will be taken if it's
10066     // taken at least once, then the backedge count will either be that or
10067     // zero.
10068     MaxBECount = BECountIfBackedgeTaken;
10069     MaxOrZero = true;
10070   } else {
10071     MaxBECount = computeMaxBECountForLT(
10072         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10073   }
10074 
10075   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10076       !isa<SCEVCouldNotCompute>(BECount))
10077     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10078 
10079   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10080 }
10081 
10082 ScalarEvolution::ExitLimit
10083 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10084                                      const Loop *L, bool IsSigned,
10085                                      bool ControlsExit, bool AllowPredicates) {
10086   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10087   // We handle only IV > Invariant
10088   if (!isLoopInvariant(RHS, L))
10089     return getCouldNotCompute();
10090 
10091   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10092   if (!IV && AllowPredicates)
10093     // Try to make this an AddRec using runtime tests, in the first X
10094     // iterations of this loop, where X is the SCEV expression found by the
10095     // algorithm below.
10096     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10097 
10098   // Avoid weird loops
10099   if (!IV || IV->getLoop() != L || !IV->isAffine())
10100     return getCouldNotCompute();
10101 
10102   bool NoWrap = ControlsExit &&
10103                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10104 
10105   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10106 
10107   // Avoid negative or zero stride values
10108   if (!isKnownPositive(Stride))
10109     return getCouldNotCompute();
10110 
10111   // Avoid proven overflow cases: this will ensure that the backedge taken count
10112   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10113   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10114   // behaviors like the case of C language.
10115   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10116     return getCouldNotCompute();
10117 
10118   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10119                                       : ICmpInst::ICMP_UGT;
10120 
10121   const SCEV *Start = IV->getStart();
10122   const SCEV *End = RHS;
10123   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10124     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10125 
10126   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10127 
10128   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10129                             : getUnsignedRangeMax(Start);
10130 
10131   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10132                              : getUnsignedRangeMin(Stride);
10133 
10134   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10135   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10136                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10137 
10138   // Although End can be a MIN expression we estimate MinEnd considering only
10139   // the case End = RHS. This is safe because in the other case (Start - End)
10140   // is zero, leading to a zero maximum backedge taken count.
10141   APInt MinEnd =
10142     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10143              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10144 
10145 
10146   const SCEV *MaxBECount = getCouldNotCompute();
10147   if (isa<SCEVConstant>(BECount))
10148     MaxBECount = BECount;
10149   else
10150     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10151                                 getConstant(MinStride), false);
10152 
10153   if (isa<SCEVCouldNotCompute>(MaxBECount))
10154     MaxBECount = BECount;
10155 
10156   return ExitLimit(BECount, MaxBECount, false, Predicates);
10157 }
10158 
10159 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10160                                                     ScalarEvolution &SE) const {
10161   if (Range.isFullSet())  // Infinite loop.
10162     return SE.getCouldNotCompute();
10163 
10164   // If the start is a non-zero constant, shift the range to simplify things.
10165   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10166     if (!SC->getValue()->isZero()) {
10167       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10168       Operands[0] = SE.getZero(SC->getType());
10169       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10170                                              getNoWrapFlags(FlagNW));
10171       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10172         return ShiftedAddRec->getNumIterationsInRange(
10173             Range.subtract(SC->getAPInt()), SE);
10174       // This is strange and shouldn't happen.
10175       return SE.getCouldNotCompute();
10176     }
10177 
10178   // The only time we can solve this is when we have all constant indices.
10179   // Otherwise, we cannot determine the overflow conditions.
10180   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10181     return SE.getCouldNotCompute();
10182 
10183   // Okay at this point we know that all elements of the chrec are constants and
10184   // that the start element is zero.
10185 
10186   // First check to see if the range contains zero.  If not, the first
10187   // iteration exits.
10188   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10189   if (!Range.contains(APInt(BitWidth, 0)))
10190     return SE.getZero(getType());
10191 
10192   if (isAffine()) {
10193     // If this is an affine expression then we have this situation:
10194     //   Solve {0,+,A} in Range  ===  Ax in Range
10195 
10196     // We know that zero is in the range.  If A is positive then we know that
10197     // the upper value of the range must be the first possible exit value.
10198     // If A is negative then the lower of the range is the last possible loop
10199     // value.  Also note that we already checked for a full range.
10200     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10201     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10202 
10203     // The exit value should be (End+A)/A.
10204     APInt ExitVal = (End + A).udiv(A);
10205     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10206 
10207     // Evaluate at the exit value.  If we really did fall out of the valid
10208     // range, then we computed our trip count, otherwise wrap around or other
10209     // things must have happened.
10210     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10211     if (Range.contains(Val->getValue()))
10212       return SE.getCouldNotCompute();  // Something strange happened
10213 
10214     // Ensure that the previous value is in the range.  This is a sanity check.
10215     assert(Range.contains(
10216            EvaluateConstantChrecAtConstant(this,
10217            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10218            "Linear scev computation is off in a bad way!");
10219     return SE.getConstant(ExitValue);
10220   } else if (isQuadratic()) {
10221     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10222     // quadratic equation to solve it.  To do this, we must frame our problem in
10223     // terms of figuring out when zero is crossed, instead of when
10224     // Range.getUpper() is crossed.
10225     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10226     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10227     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10228 
10229     // Next, solve the constructed addrec
10230     if (auto Roots =
10231             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10232       const SCEVConstant *R1 = Roots->first;
10233       const SCEVConstant *R2 = Roots->second;
10234       // Pick the smallest positive root value.
10235       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10236               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10237         if (!CB->getZExtValue())
10238           std::swap(R1, R2); // R1 is the minimum root now.
10239 
10240         // Make sure the root is not off by one.  The returned iteration should
10241         // not be in the range, but the previous one should be.  When solving
10242         // for "X*X < 5", for example, we should not return a root of 2.
10243         ConstantInt *R1Val =
10244             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10245         if (Range.contains(R1Val->getValue())) {
10246           // The next iteration must be out of the range...
10247           ConstantInt *NextVal =
10248               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10249 
10250           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10251           if (!Range.contains(R1Val->getValue()))
10252             return SE.getConstant(NextVal);
10253           return SE.getCouldNotCompute(); // Something strange happened
10254         }
10255 
10256         // If R1 was not in the range, then it is a good return value.  Make
10257         // sure that R1-1 WAS in the range though, just in case.
10258         ConstantInt *NextVal =
10259             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10260         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10261         if (Range.contains(R1Val->getValue()))
10262           return R1;
10263         return SE.getCouldNotCompute(); // Something strange happened
10264       }
10265     }
10266   }
10267 
10268   return SE.getCouldNotCompute();
10269 }
10270 
10271 const SCEVAddRecExpr *
10272 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10273   assert(getNumOperands() > 1 && "AddRec with zero step?");
10274   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10275   // but in this case we cannot guarantee that the value returned will be an
10276   // AddRec because SCEV does not have a fixed point where it stops
10277   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10278   // may happen if we reach arithmetic depth limit while simplifying. So we
10279   // construct the returned value explicitly.
10280   SmallVector<const SCEV *, 3> Ops;
10281   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10282   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10283   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10284     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10285   // We know that the last operand is not a constant zero (otherwise it would
10286   // have been popped out earlier). This guarantees us that if the result has
10287   // the same last operand, then it will also not be popped out, meaning that
10288   // the returned value will be an AddRec.
10289   const SCEV *Last = getOperand(getNumOperands() - 1);
10290   assert(!Last->isZero() && "Recurrency with zero step?");
10291   Ops.push_back(Last);
10292   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10293                                                SCEV::FlagAnyWrap));
10294 }
10295 
10296 // Return true when S contains at least an undef value.
10297 static inline bool containsUndefs(const SCEV *S) {
10298   return SCEVExprContains(S, [](const SCEV *S) {
10299     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10300       return isa<UndefValue>(SU->getValue());
10301     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10302       return isa<UndefValue>(SC->getValue());
10303     return false;
10304   });
10305 }
10306 
10307 namespace {
10308 
10309 // Collect all steps of SCEV expressions.
10310 struct SCEVCollectStrides {
10311   ScalarEvolution &SE;
10312   SmallVectorImpl<const SCEV *> &Strides;
10313 
10314   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10315       : SE(SE), Strides(S) {}
10316 
10317   bool follow(const SCEV *S) {
10318     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10319       Strides.push_back(AR->getStepRecurrence(SE));
10320     return true;
10321   }
10322 
10323   bool isDone() const { return false; }
10324 };
10325 
10326 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10327 struct SCEVCollectTerms {
10328   SmallVectorImpl<const SCEV *> &Terms;
10329 
10330   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10331 
10332   bool follow(const SCEV *S) {
10333     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10334         isa<SCEVSignExtendExpr>(S)) {
10335       if (!containsUndefs(S))
10336         Terms.push_back(S);
10337 
10338       // Stop recursion: once we collected a term, do not walk its operands.
10339       return false;
10340     }
10341 
10342     // Keep looking.
10343     return true;
10344   }
10345 
10346   bool isDone() const { return false; }
10347 };
10348 
10349 // Check if a SCEV contains an AddRecExpr.
10350 struct SCEVHasAddRec {
10351   bool &ContainsAddRec;
10352 
10353   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10354     ContainsAddRec = false;
10355   }
10356 
10357   bool follow(const SCEV *S) {
10358     if (isa<SCEVAddRecExpr>(S)) {
10359       ContainsAddRec = true;
10360 
10361       // Stop recursion: once we collected a term, do not walk its operands.
10362       return false;
10363     }
10364 
10365     // Keep looking.
10366     return true;
10367   }
10368 
10369   bool isDone() const { return false; }
10370 };
10371 
10372 // Find factors that are multiplied with an expression that (possibly as a
10373 // subexpression) contains an AddRecExpr. In the expression:
10374 //
10375 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10376 //
10377 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10378 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10379 // parameters as they form a product with an induction variable.
10380 //
10381 // This collector expects all array size parameters to be in the same MulExpr.
10382 // It might be necessary to later add support for collecting parameters that are
10383 // spread over different nested MulExpr.
10384 struct SCEVCollectAddRecMultiplies {
10385   SmallVectorImpl<const SCEV *> &Terms;
10386   ScalarEvolution &SE;
10387 
10388   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10389       : Terms(T), SE(SE) {}
10390 
10391   bool follow(const SCEV *S) {
10392     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10393       bool HasAddRec = false;
10394       SmallVector<const SCEV *, 0> Operands;
10395       for (auto Op : Mul->operands()) {
10396         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10397         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10398           Operands.push_back(Op);
10399         } else if (Unknown) {
10400           HasAddRec = true;
10401         } else {
10402           bool ContainsAddRec;
10403           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10404           visitAll(Op, ContiansAddRec);
10405           HasAddRec |= ContainsAddRec;
10406         }
10407       }
10408       if (Operands.size() == 0)
10409         return true;
10410 
10411       if (!HasAddRec)
10412         return false;
10413 
10414       Terms.push_back(SE.getMulExpr(Operands));
10415       // Stop recursion: once we collected a term, do not walk its operands.
10416       return false;
10417     }
10418 
10419     // Keep looking.
10420     return true;
10421   }
10422 
10423   bool isDone() const { return false; }
10424 };
10425 
10426 } // end anonymous namespace
10427 
10428 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10429 /// two places:
10430 ///   1) The strides of AddRec expressions.
10431 ///   2) Unknowns that are multiplied with AddRec expressions.
10432 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10433     SmallVectorImpl<const SCEV *> &Terms) {
10434   SmallVector<const SCEV *, 4> Strides;
10435   SCEVCollectStrides StrideCollector(*this, Strides);
10436   visitAll(Expr, StrideCollector);
10437 
10438   DEBUG({
10439       dbgs() << "Strides:\n";
10440       for (const SCEV *S : Strides)
10441         dbgs() << *S << "\n";
10442     });
10443 
10444   for (const SCEV *S : Strides) {
10445     SCEVCollectTerms TermCollector(Terms);
10446     visitAll(S, TermCollector);
10447   }
10448 
10449   DEBUG({
10450       dbgs() << "Terms:\n";
10451       for (const SCEV *T : Terms)
10452         dbgs() << *T << "\n";
10453     });
10454 
10455   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10456   visitAll(Expr, MulCollector);
10457 }
10458 
10459 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10460                                    SmallVectorImpl<const SCEV *> &Terms,
10461                                    SmallVectorImpl<const SCEV *> &Sizes) {
10462   int Last = Terms.size() - 1;
10463   const SCEV *Step = Terms[Last];
10464 
10465   // End of recursion.
10466   if (Last == 0) {
10467     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10468       SmallVector<const SCEV *, 2> Qs;
10469       for (const SCEV *Op : M->operands())
10470         if (!isa<SCEVConstant>(Op))
10471           Qs.push_back(Op);
10472 
10473       Step = SE.getMulExpr(Qs);
10474     }
10475 
10476     Sizes.push_back(Step);
10477     return true;
10478   }
10479 
10480   for (const SCEV *&Term : Terms) {
10481     // Normalize the terms before the next call to findArrayDimensionsRec.
10482     const SCEV *Q, *R;
10483     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10484 
10485     // Bail out when GCD does not evenly divide one of the terms.
10486     if (!R->isZero())
10487       return false;
10488 
10489     Term = Q;
10490   }
10491 
10492   // Remove all SCEVConstants.
10493   Terms.erase(
10494       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10495       Terms.end());
10496 
10497   if (Terms.size() > 0)
10498     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10499       return false;
10500 
10501   Sizes.push_back(Step);
10502   return true;
10503 }
10504 
10505 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10506 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10507   for (const SCEV *T : Terms)
10508     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10509       return true;
10510   return false;
10511 }
10512 
10513 // Return the number of product terms in S.
10514 static inline int numberOfTerms(const SCEV *S) {
10515   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10516     return Expr->getNumOperands();
10517   return 1;
10518 }
10519 
10520 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10521   if (isa<SCEVConstant>(T))
10522     return nullptr;
10523 
10524   if (isa<SCEVUnknown>(T))
10525     return T;
10526 
10527   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10528     SmallVector<const SCEV *, 2> Factors;
10529     for (const SCEV *Op : M->operands())
10530       if (!isa<SCEVConstant>(Op))
10531         Factors.push_back(Op);
10532 
10533     return SE.getMulExpr(Factors);
10534   }
10535 
10536   return T;
10537 }
10538 
10539 /// Return the size of an element read or written by Inst.
10540 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10541   Type *Ty;
10542   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10543     Ty = Store->getValueOperand()->getType();
10544   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10545     Ty = Load->getType();
10546   else
10547     return nullptr;
10548 
10549   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10550   return getSizeOfExpr(ETy, Ty);
10551 }
10552 
10553 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10554                                           SmallVectorImpl<const SCEV *> &Sizes,
10555                                           const SCEV *ElementSize) {
10556   if (Terms.size() < 1 || !ElementSize)
10557     return;
10558 
10559   // Early return when Terms do not contain parameters: we do not delinearize
10560   // non parametric SCEVs.
10561   if (!containsParameters(Terms))
10562     return;
10563 
10564   DEBUG({
10565       dbgs() << "Terms:\n";
10566       for (const SCEV *T : Terms)
10567         dbgs() << *T << "\n";
10568     });
10569 
10570   // Remove duplicates.
10571   array_pod_sort(Terms.begin(), Terms.end());
10572   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10573 
10574   // Put larger terms first.
10575   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10576     return numberOfTerms(LHS) > numberOfTerms(RHS);
10577   });
10578 
10579   // Try to divide all terms by the element size. If term is not divisible by
10580   // element size, proceed with the original term.
10581   for (const SCEV *&Term : Terms) {
10582     const SCEV *Q, *R;
10583     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10584     if (!Q->isZero())
10585       Term = Q;
10586   }
10587 
10588   SmallVector<const SCEV *, 4> NewTerms;
10589 
10590   // Remove constant factors.
10591   for (const SCEV *T : Terms)
10592     if (const SCEV *NewT = removeConstantFactors(*this, T))
10593       NewTerms.push_back(NewT);
10594 
10595   DEBUG({
10596       dbgs() << "Terms after sorting:\n";
10597       for (const SCEV *T : NewTerms)
10598         dbgs() << *T << "\n";
10599     });
10600 
10601   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10602     Sizes.clear();
10603     return;
10604   }
10605 
10606   // The last element to be pushed into Sizes is the size of an element.
10607   Sizes.push_back(ElementSize);
10608 
10609   DEBUG({
10610       dbgs() << "Sizes:\n";
10611       for (const SCEV *S : Sizes)
10612         dbgs() << *S << "\n";
10613     });
10614 }
10615 
10616 void ScalarEvolution::computeAccessFunctions(
10617     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10618     SmallVectorImpl<const SCEV *> &Sizes) {
10619   // Early exit in case this SCEV is not an affine multivariate function.
10620   if (Sizes.empty())
10621     return;
10622 
10623   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10624     if (!AR->isAffine())
10625       return;
10626 
10627   const SCEV *Res = Expr;
10628   int Last = Sizes.size() - 1;
10629   for (int i = Last; i >= 0; i--) {
10630     const SCEV *Q, *R;
10631     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10632 
10633     DEBUG({
10634         dbgs() << "Res: " << *Res << "\n";
10635         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10636         dbgs() << "Res divided by Sizes[i]:\n";
10637         dbgs() << "Quotient: " << *Q << "\n";
10638         dbgs() << "Remainder: " << *R << "\n";
10639       });
10640 
10641     Res = Q;
10642 
10643     // Do not record the last subscript corresponding to the size of elements in
10644     // the array.
10645     if (i == Last) {
10646 
10647       // Bail out if the remainder is too complex.
10648       if (isa<SCEVAddRecExpr>(R)) {
10649         Subscripts.clear();
10650         Sizes.clear();
10651         return;
10652       }
10653 
10654       continue;
10655     }
10656 
10657     // Record the access function for the current subscript.
10658     Subscripts.push_back(R);
10659   }
10660 
10661   // Also push in last position the remainder of the last division: it will be
10662   // the access function of the innermost dimension.
10663   Subscripts.push_back(Res);
10664 
10665   std::reverse(Subscripts.begin(), Subscripts.end());
10666 
10667   DEBUG({
10668       dbgs() << "Subscripts:\n";
10669       for (const SCEV *S : Subscripts)
10670         dbgs() << *S << "\n";
10671     });
10672 }
10673 
10674 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10675 /// sizes of an array access. Returns the remainder of the delinearization that
10676 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10677 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10678 /// expressions in the stride and base of a SCEV corresponding to the
10679 /// computation of a GCD (greatest common divisor) of base and stride.  When
10680 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10681 ///
10682 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10683 ///
10684 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10685 ///
10686 ///    for (long i = 0; i < n; i++)
10687 ///      for (long j = 0; j < m; j++)
10688 ///        for (long k = 0; k < o; k++)
10689 ///          A[i][j][k] = 1.0;
10690 ///  }
10691 ///
10692 /// the delinearization input is the following AddRec SCEV:
10693 ///
10694 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10695 ///
10696 /// From this SCEV, we are able to say that the base offset of the access is %A
10697 /// because it appears as an offset that does not divide any of the strides in
10698 /// the loops:
10699 ///
10700 ///  CHECK: Base offset: %A
10701 ///
10702 /// and then SCEV->delinearize determines the size of some of the dimensions of
10703 /// the array as these are the multiples by which the strides are happening:
10704 ///
10705 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10706 ///
10707 /// Note that the outermost dimension remains of UnknownSize because there are
10708 /// no strides that would help identifying the size of the last dimension: when
10709 /// the array has been statically allocated, one could compute the size of that
10710 /// dimension by dividing the overall size of the array by the size of the known
10711 /// dimensions: %m * %o * 8.
10712 ///
10713 /// Finally delinearize provides the access functions for the array reference
10714 /// that does correspond to A[i][j][k] of the above C testcase:
10715 ///
10716 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10717 ///
10718 /// The testcases are checking the output of a function pass:
10719 /// DelinearizationPass that walks through all loads and stores of a function
10720 /// asking for the SCEV of the memory access with respect to all enclosing
10721 /// loops, calling SCEV->delinearize on that and printing the results.
10722 void ScalarEvolution::delinearize(const SCEV *Expr,
10723                                  SmallVectorImpl<const SCEV *> &Subscripts,
10724                                  SmallVectorImpl<const SCEV *> &Sizes,
10725                                  const SCEV *ElementSize) {
10726   // First step: collect parametric terms.
10727   SmallVector<const SCEV *, 4> Terms;
10728   collectParametricTerms(Expr, Terms);
10729 
10730   if (Terms.empty())
10731     return;
10732 
10733   // Second step: find subscript sizes.
10734   findArrayDimensions(Terms, Sizes, ElementSize);
10735 
10736   if (Sizes.empty())
10737     return;
10738 
10739   // Third step: compute the access functions for each subscript.
10740   computeAccessFunctions(Expr, Subscripts, Sizes);
10741 
10742   if (Subscripts.empty())
10743     return;
10744 
10745   DEBUG({
10746       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10747       dbgs() << "ArrayDecl[UnknownSize]";
10748       for (const SCEV *S : Sizes)
10749         dbgs() << "[" << *S << "]";
10750 
10751       dbgs() << "\nArrayRef";
10752       for (const SCEV *S : Subscripts)
10753         dbgs() << "[" << *S << "]";
10754       dbgs() << "\n";
10755     });
10756 }
10757 
10758 //===----------------------------------------------------------------------===//
10759 //                   SCEVCallbackVH Class Implementation
10760 //===----------------------------------------------------------------------===//
10761 
10762 void ScalarEvolution::SCEVCallbackVH::deleted() {
10763   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10764   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10765     SE->ConstantEvolutionLoopExitValue.erase(PN);
10766   SE->eraseValueFromMap(getValPtr());
10767   // this now dangles!
10768 }
10769 
10770 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10771   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10772 
10773   // Forget all the expressions associated with users of the old value,
10774   // so that future queries will recompute the expressions using the new
10775   // value.
10776   Value *Old = getValPtr();
10777   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10778   SmallPtrSet<User *, 8> Visited;
10779   while (!Worklist.empty()) {
10780     User *U = Worklist.pop_back_val();
10781     // Deleting the Old value will cause this to dangle. Postpone
10782     // that until everything else is done.
10783     if (U == Old)
10784       continue;
10785     if (!Visited.insert(U).second)
10786       continue;
10787     if (PHINode *PN = dyn_cast<PHINode>(U))
10788       SE->ConstantEvolutionLoopExitValue.erase(PN);
10789     SE->eraseValueFromMap(U);
10790     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10791   }
10792   // Delete the Old value.
10793   if (PHINode *PN = dyn_cast<PHINode>(Old))
10794     SE->ConstantEvolutionLoopExitValue.erase(PN);
10795   SE->eraseValueFromMap(Old);
10796   // this now dangles!
10797 }
10798 
10799 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10800   : CallbackVH(V), SE(se) {}
10801 
10802 //===----------------------------------------------------------------------===//
10803 //                   ScalarEvolution Class Implementation
10804 //===----------------------------------------------------------------------===//
10805 
10806 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10807                                  AssumptionCache &AC, DominatorTree &DT,
10808                                  LoopInfo &LI)
10809     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10810       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
10811       LoopDispositions(64), BlockDispositions(64) {
10812   // To use guards for proving predicates, we need to scan every instruction in
10813   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10814   // time if the IR does not actually contain any calls to
10815   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10816   //
10817   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10818   // to _add_ guards to the module when there weren't any before, and wants
10819   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10820   // efficient in lieu of being smart in that rather obscure case.
10821 
10822   auto *GuardDecl = F.getParent()->getFunction(
10823       Intrinsic::getName(Intrinsic::experimental_guard));
10824   HasGuards = GuardDecl && !GuardDecl->use_empty();
10825 }
10826 
10827 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10828     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10829       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10830       ValueExprMap(std::move(Arg.ValueExprMap)),
10831       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10832       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10833       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10834       PredicatedBackedgeTakenCounts(
10835           std::move(Arg.PredicatedBackedgeTakenCounts)),
10836       ConstantEvolutionLoopExitValue(
10837           std::move(Arg.ConstantEvolutionLoopExitValue)),
10838       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10839       LoopDispositions(std::move(Arg.LoopDispositions)),
10840       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10841       BlockDispositions(std::move(Arg.BlockDispositions)),
10842       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10843       SignedRanges(std::move(Arg.SignedRanges)),
10844       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10845       UniquePreds(std::move(Arg.UniquePreds)),
10846       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10847       LoopUsers(std::move(Arg.LoopUsers)),
10848       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10849       FirstUnknown(Arg.FirstUnknown) {
10850   Arg.FirstUnknown = nullptr;
10851 }
10852 
10853 ScalarEvolution::~ScalarEvolution() {
10854   // Iterate through all the SCEVUnknown instances and call their
10855   // destructors, so that they release their references to their values.
10856   for (SCEVUnknown *U = FirstUnknown; U;) {
10857     SCEVUnknown *Tmp = U;
10858     U = U->Next;
10859     Tmp->~SCEVUnknown();
10860   }
10861   FirstUnknown = nullptr;
10862 
10863   ExprValueMap.clear();
10864   ValueExprMap.clear();
10865   HasRecMap.clear();
10866 
10867   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10868   // that a loop had multiple computable exits.
10869   for (auto &BTCI : BackedgeTakenCounts)
10870     BTCI.second.clear();
10871   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10872     BTCI.second.clear();
10873 
10874   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10875   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10876   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10877 }
10878 
10879 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10880   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10881 }
10882 
10883 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10884                           const Loop *L) {
10885   // Print all inner loops first
10886   for (Loop *I : *L)
10887     PrintLoopInfo(OS, SE, I);
10888 
10889   OS << "Loop ";
10890   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10891   OS << ": ";
10892 
10893   SmallVector<BasicBlock *, 8> ExitBlocks;
10894   L->getExitBlocks(ExitBlocks);
10895   if (ExitBlocks.size() != 1)
10896     OS << "<multiple exits> ";
10897 
10898   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10899     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10900   } else {
10901     OS << "Unpredictable backedge-taken count. ";
10902   }
10903 
10904   OS << "\n"
10905         "Loop ";
10906   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10907   OS << ": ";
10908 
10909   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10910     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10911     if (SE->isBackedgeTakenCountMaxOrZero(L))
10912       OS << ", actual taken count either this or zero.";
10913   } else {
10914     OS << "Unpredictable max backedge-taken count. ";
10915   }
10916 
10917   OS << "\n"
10918         "Loop ";
10919   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10920   OS << ": ";
10921 
10922   SCEVUnionPredicate Pred;
10923   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10924   if (!isa<SCEVCouldNotCompute>(PBT)) {
10925     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10926     OS << " Predicates:\n";
10927     Pred.print(OS, 4);
10928   } else {
10929     OS << "Unpredictable predicated backedge-taken count. ";
10930   }
10931   OS << "\n";
10932 
10933   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10934     OS << "Loop ";
10935     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10936     OS << ": ";
10937     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10938   }
10939 }
10940 
10941 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10942   switch (LD) {
10943   case ScalarEvolution::LoopVariant:
10944     return "Variant";
10945   case ScalarEvolution::LoopInvariant:
10946     return "Invariant";
10947   case ScalarEvolution::LoopComputable:
10948     return "Computable";
10949   }
10950   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10951 }
10952 
10953 void ScalarEvolution::print(raw_ostream &OS) const {
10954   // ScalarEvolution's implementation of the print method is to print
10955   // out SCEV values of all instructions that are interesting. Doing
10956   // this potentially causes it to create new SCEV objects though,
10957   // which technically conflicts with the const qualifier. This isn't
10958   // observable from outside the class though, so casting away the
10959   // const isn't dangerous.
10960   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10961 
10962   OS << "Classifying expressions for: ";
10963   F.printAsOperand(OS, /*PrintType=*/false);
10964   OS << "\n";
10965   for (Instruction &I : instructions(F))
10966     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10967       OS << I << '\n';
10968       OS << "  -->  ";
10969       const SCEV *SV = SE.getSCEV(&I);
10970       SV->print(OS);
10971       if (!isa<SCEVCouldNotCompute>(SV)) {
10972         OS << " U: ";
10973         SE.getUnsignedRange(SV).print(OS);
10974         OS << " S: ";
10975         SE.getSignedRange(SV).print(OS);
10976       }
10977 
10978       const Loop *L = LI.getLoopFor(I.getParent());
10979 
10980       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10981       if (AtUse != SV) {
10982         OS << "  -->  ";
10983         AtUse->print(OS);
10984         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10985           OS << " U: ";
10986           SE.getUnsignedRange(AtUse).print(OS);
10987           OS << " S: ";
10988           SE.getSignedRange(AtUse).print(OS);
10989         }
10990       }
10991 
10992       if (L) {
10993         OS << "\t\t" "Exits: ";
10994         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10995         if (!SE.isLoopInvariant(ExitValue, L)) {
10996           OS << "<<Unknown>>";
10997         } else {
10998           OS << *ExitValue;
10999         }
11000 
11001         bool First = true;
11002         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11003           if (First) {
11004             OS << "\t\t" "LoopDispositions: { ";
11005             First = false;
11006           } else {
11007             OS << ", ";
11008           }
11009 
11010           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11011           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11012         }
11013 
11014         for (auto *InnerL : depth_first(L)) {
11015           if (InnerL == L)
11016             continue;
11017           if (First) {
11018             OS << "\t\t" "LoopDispositions: { ";
11019             First = false;
11020           } else {
11021             OS << ", ";
11022           }
11023 
11024           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11025           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11026         }
11027 
11028         OS << " }";
11029       }
11030 
11031       OS << "\n";
11032     }
11033 
11034   OS << "Determining loop execution counts for: ";
11035   F.printAsOperand(OS, /*PrintType=*/false);
11036   OS << "\n";
11037   for (Loop *I : LI)
11038     PrintLoopInfo(OS, &SE, I);
11039 }
11040 
11041 ScalarEvolution::LoopDisposition
11042 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11043   auto &Values = LoopDispositions[S];
11044   for (auto &V : Values) {
11045     if (V.getPointer() == L)
11046       return V.getInt();
11047   }
11048   Values.emplace_back(L, LoopVariant);
11049   LoopDisposition D = computeLoopDisposition(S, L);
11050   auto &Values2 = LoopDispositions[S];
11051   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11052     if (V.getPointer() == L) {
11053       V.setInt(D);
11054       break;
11055     }
11056   }
11057   return D;
11058 }
11059 
11060 ScalarEvolution::LoopDisposition
11061 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11062   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11063   case scConstant:
11064     return LoopInvariant;
11065   case scTruncate:
11066   case scZeroExtend:
11067   case scSignExtend:
11068     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11069   case scAddRecExpr: {
11070     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11071 
11072     // If L is the addrec's loop, it's computable.
11073     if (AR->getLoop() == L)
11074       return LoopComputable;
11075 
11076     // Add recurrences are never invariant in the function-body (null loop).
11077     if (!L)
11078       return LoopVariant;
11079 
11080     // Everything that is not defined at loop entry is variant.
11081     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11082       return LoopVariant;
11083     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11084            " dominate the contained loop's header?");
11085 
11086     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11087     if (AR->getLoop()->contains(L))
11088       return LoopInvariant;
11089 
11090     // This recurrence is variant w.r.t. L if any of its operands
11091     // are variant.
11092     for (auto *Op : AR->operands())
11093       if (!isLoopInvariant(Op, L))
11094         return LoopVariant;
11095 
11096     // Otherwise it's loop-invariant.
11097     return LoopInvariant;
11098   }
11099   case scAddExpr:
11100   case scMulExpr:
11101   case scUMaxExpr:
11102   case scSMaxExpr: {
11103     bool HasVarying = false;
11104     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11105       LoopDisposition D = getLoopDisposition(Op, L);
11106       if (D == LoopVariant)
11107         return LoopVariant;
11108       if (D == LoopComputable)
11109         HasVarying = true;
11110     }
11111     return HasVarying ? LoopComputable : LoopInvariant;
11112   }
11113   case scUDivExpr: {
11114     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11115     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11116     if (LD == LoopVariant)
11117       return LoopVariant;
11118     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11119     if (RD == LoopVariant)
11120       return LoopVariant;
11121     return (LD == LoopInvariant && RD == LoopInvariant) ?
11122            LoopInvariant : LoopComputable;
11123   }
11124   case scUnknown:
11125     // All non-instruction values are loop invariant.  All instructions are loop
11126     // invariant if they are not contained in the specified loop.
11127     // Instructions are never considered invariant in the function body
11128     // (null loop) because they are defined within the "loop".
11129     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11130       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11131     return LoopInvariant;
11132   case scCouldNotCompute:
11133     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11134   }
11135   llvm_unreachable("Unknown SCEV kind!");
11136 }
11137 
11138 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11139   return getLoopDisposition(S, L) == LoopInvariant;
11140 }
11141 
11142 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11143   return getLoopDisposition(S, L) == LoopComputable;
11144 }
11145 
11146 ScalarEvolution::BlockDisposition
11147 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11148   auto &Values = BlockDispositions[S];
11149   for (auto &V : Values) {
11150     if (V.getPointer() == BB)
11151       return V.getInt();
11152   }
11153   Values.emplace_back(BB, DoesNotDominateBlock);
11154   BlockDisposition D = computeBlockDisposition(S, BB);
11155   auto &Values2 = BlockDispositions[S];
11156   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11157     if (V.getPointer() == BB) {
11158       V.setInt(D);
11159       break;
11160     }
11161   }
11162   return D;
11163 }
11164 
11165 ScalarEvolution::BlockDisposition
11166 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11167   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11168   case scConstant:
11169     return ProperlyDominatesBlock;
11170   case scTruncate:
11171   case scZeroExtend:
11172   case scSignExtend:
11173     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11174   case scAddRecExpr: {
11175     // This uses a "dominates" query instead of "properly dominates" query
11176     // to test for proper dominance too, because the instruction which
11177     // produces the addrec's value is a PHI, and a PHI effectively properly
11178     // dominates its entire containing block.
11179     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11180     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11181       return DoesNotDominateBlock;
11182 
11183     // Fall through into SCEVNAryExpr handling.
11184     LLVM_FALLTHROUGH;
11185   }
11186   case scAddExpr:
11187   case scMulExpr:
11188   case scUMaxExpr:
11189   case scSMaxExpr: {
11190     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11191     bool Proper = true;
11192     for (const SCEV *NAryOp : NAry->operands()) {
11193       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11194       if (D == DoesNotDominateBlock)
11195         return DoesNotDominateBlock;
11196       if (D == DominatesBlock)
11197         Proper = false;
11198     }
11199     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11200   }
11201   case scUDivExpr: {
11202     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11203     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11204     BlockDisposition LD = getBlockDisposition(LHS, BB);
11205     if (LD == DoesNotDominateBlock)
11206       return DoesNotDominateBlock;
11207     BlockDisposition RD = getBlockDisposition(RHS, BB);
11208     if (RD == DoesNotDominateBlock)
11209       return DoesNotDominateBlock;
11210     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11211       ProperlyDominatesBlock : DominatesBlock;
11212   }
11213   case scUnknown:
11214     if (Instruction *I =
11215           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11216       if (I->getParent() == BB)
11217         return DominatesBlock;
11218       if (DT.properlyDominates(I->getParent(), BB))
11219         return ProperlyDominatesBlock;
11220       return DoesNotDominateBlock;
11221     }
11222     return ProperlyDominatesBlock;
11223   case scCouldNotCompute:
11224     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11225   }
11226   llvm_unreachable("Unknown SCEV kind!");
11227 }
11228 
11229 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11230   return getBlockDisposition(S, BB) >= DominatesBlock;
11231 }
11232 
11233 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11234   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11235 }
11236 
11237 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11238   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11239 }
11240 
11241 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11242   auto IsS = [&](const SCEV *X) { return S == X; };
11243   auto ContainsS = [&](const SCEV *X) {
11244     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11245   };
11246   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11247 }
11248 
11249 void
11250 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11251   ValuesAtScopes.erase(S);
11252   LoopDispositions.erase(S);
11253   BlockDispositions.erase(S);
11254   UnsignedRanges.erase(S);
11255   SignedRanges.erase(S);
11256   ExprValueMap.erase(S);
11257   HasRecMap.erase(S);
11258   MinTrailingZerosCache.erase(S);
11259 
11260   for (auto I = PredicatedSCEVRewrites.begin();
11261        I != PredicatedSCEVRewrites.end();) {
11262     std::pair<const SCEV *, const Loop *> Entry = I->first;
11263     if (Entry.first == S)
11264       PredicatedSCEVRewrites.erase(I++);
11265     else
11266       ++I;
11267   }
11268 
11269   auto RemoveSCEVFromBackedgeMap =
11270       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11271         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11272           BackedgeTakenInfo &BEInfo = I->second;
11273           if (BEInfo.hasOperand(S, this)) {
11274             BEInfo.clear();
11275             Map.erase(I++);
11276           } else
11277             ++I;
11278         }
11279       };
11280 
11281   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11282   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11283 }
11284 
11285 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11286   struct FindUsedLoops {
11287     SmallPtrSet<const Loop *, 8> LoopsUsed;
11288     bool follow(const SCEV *S) {
11289       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11290         LoopsUsed.insert(AR->getLoop());
11291       return true;
11292     }
11293 
11294     bool isDone() const { return false; }
11295   };
11296 
11297   FindUsedLoops F;
11298   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11299 
11300   for (auto *L : F.LoopsUsed)
11301     LoopUsers[L].push_back(S);
11302 }
11303 
11304 void ScalarEvolution::verify() const {
11305   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11306   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11307 
11308   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11309 
11310   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11311   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11312     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11313 
11314     const SCEV *visitConstant(const SCEVConstant *Constant) {
11315       return SE.getConstant(Constant->getAPInt());
11316     }
11317 
11318     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11319       return SE.getUnknown(Expr->getValue());
11320     }
11321 
11322     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11323       return SE.getCouldNotCompute();
11324     }
11325   };
11326 
11327   SCEVMapper SCM(SE2);
11328 
11329   while (!LoopStack.empty()) {
11330     auto *L = LoopStack.pop_back_val();
11331     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11332 
11333     auto *CurBECount = SCM.visit(
11334         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11335     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11336 
11337     if (CurBECount == SE2.getCouldNotCompute() ||
11338         NewBECount == SE2.getCouldNotCompute()) {
11339       // NB! This situation is legal, but is very suspicious -- whatever pass
11340       // change the loop to make a trip count go from could not compute to
11341       // computable or vice-versa *should have* invalidated SCEV.  However, we
11342       // choose not to assert here (for now) since we don't want false
11343       // positives.
11344       continue;
11345     }
11346 
11347     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11348       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11349       // not propagate undef aggressively).  This means we can (and do) fail
11350       // verification in cases where a transform makes the trip count of a loop
11351       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11352       // both cases the loop iterates "undef" times, but SCEV thinks we
11353       // increased the trip count of the loop by 1 incorrectly.
11354       continue;
11355     }
11356 
11357     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11358         SE.getTypeSizeInBits(NewBECount->getType()))
11359       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11360     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11361              SE.getTypeSizeInBits(NewBECount->getType()))
11362       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11363 
11364     auto *ConstantDelta =
11365         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11366 
11367     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11368       dbgs() << "Trip Count Changed!\n";
11369       dbgs() << "Old: " << *CurBECount << "\n";
11370       dbgs() << "New: " << *NewBECount << "\n";
11371       dbgs() << "Delta: " << *ConstantDelta << "\n";
11372       std::abort();
11373     }
11374   }
11375 }
11376 
11377 bool ScalarEvolution::invalidate(
11378     Function &F, const PreservedAnalyses &PA,
11379     FunctionAnalysisManager::Invalidator &Inv) {
11380   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11381   // of its dependencies is invalidated.
11382   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11383   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11384          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11385          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11386          Inv.invalidate<LoopAnalysis>(F, PA);
11387 }
11388 
11389 AnalysisKey ScalarEvolutionAnalysis::Key;
11390 
11391 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11392                                              FunctionAnalysisManager &AM) {
11393   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11394                          AM.getResult<AssumptionAnalysis>(F),
11395                          AM.getResult<DominatorTreeAnalysis>(F),
11396                          AM.getResult<LoopAnalysis>(F));
11397 }
11398 
11399 PreservedAnalyses
11400 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11401   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11402   return PreservedAnalyses::all();
11403 }
11404 
11405 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11406                       "Scalar Evolution Analysis", false, true)
11407 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11408 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11409 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11410 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11411 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11412                     "Scalar Evolution Analysis", false, true)
11413 
11414 char ScalarEvolutionWrapperPass::ID = 0;
11415 
11416 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11417   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11418 }
11419 
11420 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11421   SE.reset(new ScalarEvolution(
11422       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11423       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11424       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11425       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11426   return false;
11427 }
11428 
11429 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11430 
11431 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11432   SE->print(OS);
11433 }
11434 
11435 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11436   if (!VerifySCEV)
11437     return;
11438 
11439   SE->verify();
11440 }
11441 
11442 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11443   AU.setPreservesAll();
11444   AU.addRequiredTransitive<AssumptionCacheTracker>();
11445   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11446   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11447   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11448 }
11449 
11450 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11451                                                         const SCEV *RHS) {
11452   FoldingSetNodeID ID;
11453   assert(LHS->getType() == RHS->getType() &&
11454          "Type mismatch between LHS and RHS");
11455   // Unique this node based on the arguments
11456   ID.AddInteger(SCEVPredicate::P_Equal);
11457   ID.AddPointer(LHS);
11458   ID.AddPointer(RHS);
11459   void *IP = nullptr;
11460   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11461     return S;
11462   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11463       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11464   UniquePreds.InsertNode(Eq, IP);
11465   return Eq;
11466 }
11467 
11468 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11469     const SCEVAddRecExpr *AR,
11470     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11471   FoldingSetNodeID ID;
11472   // Unique this node based on the arguments
11473   ID.AddInteger(SCEVPredicate::P_Wrap);
11474   ID.AddPointer(AR);
11475   ID.AddInteger(AddedFlags);
11476   void *IP = nullptr;
11477   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11478     return S;
11479   auto *OF = new (SCEVAllocator)
11480       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11481   UniquePreds.InsertNode(OF, IP);
11482   return OF;
11483 }
11484 
11485 namespace {
11486 
11487 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11488 public:
11489 
11490   /// Rewrites \p S in the context of a loop L and the SCEV predication
11491   /// infrastructure.
11492   ///
11493   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11494   /// equivalences present in \p Pred.
11495   ///
11496   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11497   /// \p NewPreds such that the result will be an AddRecExpr.
11498   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11499                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11500                              SCEVUnionPredicate *Pred) {
11501     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11502     return Rewriter.visit(S);
11503   }
11504 
11505   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11506     if (Pred) {
11507       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11508       for (auto *Pred : ExprPreds)
11509         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11510           if (IPred->getLHS() == Expr)
11511             return IPred->getRHS();
11512     }
11513     return convertToAddRecWithPreds(Expr);
11514   }
11515 
11516   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11517     const SCEV *Operand = visit(Expr->getOperand());
11518     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11519     if (AR && AR->getLoop() == L && AR->isAffine()) {
11520       // This couldn't be folded because the operand didn't have the nuw
11521       // flag. Add the nusw flag as an assumption that we could make.
11522       const SCEV *Step = AR->getStepRecurrence(SE);
11523       Type *Ty = Expr->getType();
11524       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11525         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11526                                 SE.getSignExtendExpr(Step, Ty), L,
11527                                 AR->getNoWrapFlags());
11528     }
11529     return SE.getZeroExtendExpr(Operand, Expr->getType());
11530   }
11531 
11532   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11533     const SCEV *Operand = visit(Expr->getOperand());
11534     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11535     if (AR && AR->getLoop() == L && AR->isAffine()) {
11536       // This couldn't be folded because the operand didn't have the nsw
11537       // flag. Add the nssw flag as an assumption that we could make.
11538       const SCEV *Step = AR->getStepRecurrence(SE);
11539       Type *Ty = Expr->getType();
11540       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11541         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11542                                 SE.getSignExtendExpr(Step, Ty), L,
11543                                 AR->getNoWrapFlags());
11544     }
11545     return SE.getSignExtendExpr(Operand, Expr->getType());
11546   }
11547 
11548 private:
11549   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11550                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11551                         SCEVUnionPredicate *Pred)
11552       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11553 
11554   bool addOverflowAssumption(const SCEVPredicate *P) {
11555     if (!NewPreds) {
11556       // Check if we've already made this assumption.
11557       return Pred && Pred->implies(P);
11558     }
11559     NewPreds->insert(P);
11560     return true;
11561   }
11562 
11563   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11564                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11565     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11566     return addOverflowAssumption(A);
11567   }
11568 
11569   // If \p Expr represents a PHINode, we try to see if it can be represented
11570   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11571   // to add this predicate as a runtime overflow check, we return the AddRec.
11572   // If \p Expr does not meet these conditions (is not a PHI node, or we
11573   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11574   // return \p Expr.
11575   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11576     if (!isa<PHINode>(Expr->getValue()))
11577       return Expr;
11578     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11579     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11580     if (!PredicatedRewrite)
11581       return Expr;
11582     for (auto *P : PredicatedRewrite->second){
11583       if (!addOverflowAssumption(P))
11584         return Expr;
11585     }
11586     return PredicatedRewrite->first;
11587   }
11588 
11589   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11590   SCEVUnionPredicate *Pred;
11591   const Loop *L;
11592 };
11593 
11594 } // end anonymous namespace
11595 
11596 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11597                                                    SCEVUnionPredicate &Preds) {
11598   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11599 }
11600 
11601 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11602     const SCEV *S, const Loop *L,
11603     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11604   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11605   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11606   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11607 
11608   if (!AddRec)
11609     return nullptr;
11610 
11611   // Since the transformation was successful, we can now transfer the SCEV
11612   // predicates.
11613   for (auto *P : TransformPreds)
11614     Preds.insert(P);
11615 
11616   return AddRec;
11617 }
11618 
11619 /// SCEV predicates
11620 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11621                              SCEVPredicateKind Kind)
11622     : FastID(ID), Kind(Kind) {}
11623 
11624 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11625                                        const SCEV *LHS, const SCEV *RHS)
11626     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11627   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11628   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11629 }
11630 
11631 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11632   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11633 
11634   if (!Op)
11635     return false;
11636 
11637   return Op->LHS == LHS && Op->RHS == RHS;
11638 }
11639 
11640 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11641 
11642 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11643 
11644 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11645   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11646 }
11647 
11648 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11649                                      const SCEVAddRecExpr *AR,
11650                                      IncrementWrapFlags Flags)
11651     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11652 
11653 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11654 
11655 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11656   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11657 
11658   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11659 }
11660 
11661 bool SCEVWrapPredicate::isAlwaysTrue() const {
11662   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11663   IncrementWrapFlags IFlags = Flags;
11664 
11665   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11666     IFlags = clearFlags(IFlags, IncrementNSSW);
11667 
11668   return IFlags == IncrementAnyWrap;
11669 }
11670 
11671 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11672   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11673   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11674     OS << "<nusw>";
11675   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11676     OS << "<nssw>";
11677   OS << "\n";
11678 }
11679 
11680 SCEVWrapPredicate::IncrementWrapFlags
11681 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11682                                    ScalarEvolution &SE) {
11683   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11684   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11685 
11686   // We can safely transfer the NSW flag as NSSW.
11687   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11688     ImpliedFlags = IncrementNSSW;
11689 
11690   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11691     // If the increment is positive, the SCEV NUW flag will also imply the
11692     // WrapPredicate NUSW flag.
11693     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11694       if (Step->getValue()->getValue().isNonNegative())
11695         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11696   }
11697 
11698   return ImpliedFlags;
11699 }
11700 
11701 /// Union predicates don't get cached so create a dummy set ID for it.
11702 SCEVUnionPredicate::SCEVUnionPredicate()
11703     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11704 
11705 bool SCEVUnionPredicate::isAlwaysTrue() const {
11706   return all_of(Preds,
11707                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11708 }
11709 
11710 ArrayRef<const SCEVPredicate *>
11711 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11712   auto I = SCEVToPreds.find(Expr);
11713   if (I == SCEVToPreds.end())
11714     return ArrayRef<const SCEVPredicate *>();
11715   return I->second;
11716 }
11717 
11718 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11719   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11720     return all_of(Set->Preds,
11721                   [this](const SCEVPredicate *I) { return this->implies(I); });
11722 
11723   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11724   if (ScevPredsIt == SCEVToPreds.end())
11725     return false;
11726   auto &SCEVPreds = ScevPredsIt->second;
11727 
11728   return any_of(SCEVPreds,
11729                 [N](const SCEVPredicate *I) { return I->implies(N); });
11730 }
11731 
11732 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11733 
11734 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11735   for (auto Pred : Preds)
11736     Pred->print(OS, Depth);
11737 }
11738 
11739 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11740   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11741     for (auto Pred : Set->Preds)
11742       add(Pred);
11743     return;
11744   }
11745 
11746   if (implies(N))
11747     return;
11748 
11749   const SCEV *Key = N->getExpr();
11750   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11751                 " associated expression!");
11752 
11753   SCEVToPreds[Key].push_back(N);
11754   Preds.push_back(N);
11755 }
11756 
11757 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11758                                                      Loop &L)
11759     : SE(SE), L(L) {}
11760 
11761 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11762   const SCEV *Expr = SE.getSCEV(V);
11763   RewriteEntry &Entry = RewriteMap[Expr];
11764 
11765   // If we already have an entry and the version matches, return it.
11766   if (Entry.second && Generation == Entry.first)
11767     return Entry.second;
11768 
11769   // We found an entry but it's stale. Rewrite the stale entry
11770   // according to the current predicate.
11771   if (Entry.second)
11772     Expr = Entry.second;
11773 
11774   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11775   Entry = {Generation, NewSCEV};
11776 
11777   return NewSCEV;
11778 }
11779 
11780 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11781   if (!BackedgeCount) {
11782     SCEVUnionPredicate BackedgePred;
11783     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11784     addPredicate(BackedgePred);
11785   }
11786   return BackedgeCount;
11787 }
11788 
11789 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11790   if (Preds.implies(&Pred))
11791     return;
11792   Preds.add(&Pred);
11793   updateGeneration();
11794 }
11795 
11796 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11797   return Preds;
11798 }
11799 
11800 void PredicatedScalarEvolution::updateGeneration() {
11801   // If the generation number wrapped recompute everything.
11802   if (++Generation == 0) {
11803     for (auto &II : RewriteMap) {
11804       const SCEV *Rewritten = II.second.second;
11805       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11806     }
11807   }
11808 }
11809 
11810 void PredicatedScalarEvolution::setNoOverflow(
11811     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11812   const SCEV *Expr = getSCEV(V);
11813   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11814 
11815   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11816 
11817   // Clear the statically implied flags.
11818   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11819   addPredicate(*SE.getWrapPredicate(AR, Flags));
11820 
11821   auto II = FlagsMap.insert({V, Flags});
11822   if (!II.second)
11823     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11824 }
11825 
11826 bool PredicatedScalarEvolution::hasNoOverflow(
11827     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11828   const SCEV *Expr = getSCEV(V);
11829   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11830 
11831   Flags = SCEVWrapPredicate::clearFlags(
11832       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11833 
11834   auto II = FlagsMap.find(V);
11835 
11836   if (II != FlagsMap.end())
11837     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11838 
11839   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11840 }
11841 
11842 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11843   const SCEV *Expr = this->getSCEV(V);
11844   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11845   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11846 
11847   if (!New)
11848     return nullptr;
11849 
11850   for (auto *P : NewPreds)
11851     Preds.add(P);
11852 
11853   updateGeneration();
11854   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11855   return New;
11856 }
11857 
11858 PredicatedScalarEvolution::PredicatedScalarEvolution(
11859     const PredicatedScalarEvolution &Init)
11860     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11861       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11862   for (const auto &I : Init.FlagsMap)
11863     FlagsMap.insert(I);
11864 }
11865 
11866 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11867   // For each block.
11868   for (auto *BB : L.getBlocks())
11869     for (auto &I : *BB) {
11870       if (!SE.isSCEVable(I.getType()))
11871         continue;
11872 
11873       auto *Expr = SE.getSCEV(&I);
11874       auto II = RewriteMap.find(Expr);
11875 
11876       if (II == RewriteMap.end())
11877         continue;
11878 
11879       // Don't print things that are not interesting.
11880       if (II->second.second == Expr)
11881         continue;
11882 
11883       OS.indent(Depth) << "[PSE]" << I << ":\n";
11884       OS.indent(Depth + 2) << *Expr << "\n";
11885       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11886     }
11887 }
11888