xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision d34e60ca8532511acb8c93ef26297e349fbec86a)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/CallSite.h"
91 #include "llvm/IR/Constant.h"
92 #include "llvm/IR/ConstantRange.h"
93 #include "llvm/IR/Constants.h"
94 #include "llvm/IR/DataLayout.h"
95 #include "llvm/IR/DerivedTypes.h"
96 #include "llvm/IR/Dominators.h"
97 #include "llvm/IR/Function.h"
98 #include "llvm/IR/GlobalAlias.h"
99 #include "llvm/IR/GlobalValue.h"
100 #include "llvm/IR/GlobalVariable.h"
101 #include "llvm/IR/InstIterator.h"
102 #include "llvm/IR/InstrTypes.h"
103 #include "llvm/IR/Instruction.h"
104 #include "llvm/IR/Instructions.h"
105 #include "llvm/IR/IntrinsicInst.h"
106 #include "llvm/IR/Intrinsics.h"
107 #include "llvm/IR/LLVMContext.h"
108 #include "llvm/IR/Metadata.h"
109 #include "llvm/IR/Operator.h"
110 #include "llvm/IR/PatternMatch.h"
111 #include "llvm/IR/Type.h"
112 #include "llvm/IR/Use.h"
113 #include "llvm/IR/User.h"
114 #include "llvm/IR/Value.h"
115 #include "llvm/Pass.h"
116 #include "llvm/Support/Casting.h"
117 #include "llvm/Support/CommandLine.h"
118 #include "llvm/Support/Compiler.h"
119 #include "llvm/Support/Debug.h"
120 #include "llvm/Support/ErrorHandling.h"
121 #include "llvm/Support/KnownBits.h"
122 #include "llvm/Support/SaveAndRestore.h"
123 #include "llvm/Support/raw_ostream.h"
124 #include <algorithm>
125 #include <cassert>
126 #include <climits>
127 #include <cstddef>
128 #include <cstdint>
129 #include <cstdlib>
130 #include <map>
131 #include <memory>
132 #include <tuple>
133 #include <utility>
134 #include <vector>
135 
136 using namespace llvm;
137 
138 #define DEBUG_TYPE "scalar-evolution"
139 
140 STATISTIC(NumArrayLenItCounts,
141           "Number of trip counts computed with array length");
142 STATISTIC(NumTripCountsComputed,
143           "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145           "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147           "Number of loops with trip counts computed by force");
148 
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151                         cl::desc("Maximum number of iterations SCEV will "
152                                  "symbolically execute a constant "
153                                  "derived loop"),
154                         cl::init(100));
155 
156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157 static cl::opt<bool> VerifySCEV(
158     "verify-scev", cl::Hidden,
159     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160 static cl::opt<bool>
161     VerifySCEVMap("verify-scev-maps", cl::Hidden,
162                   cl::desc("Verify no dangling value in ScalarEvolution's "
163                            "ExprValueMap (slow)"));
164 
165 static cl::opt<unsigned> MulOpsInlineThreshold(
166     "scev-mulops-inline-threshold", cl::Hidden,
167     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
168     cl::init(32));
169 
170 static cl::opt<unsigned> AddOpsInlineThreshold(
171     "scev-addops-inline-threshold", cl::Hidden,
172     cl::desc("Threshold for inlining addition operands into a SCEV"),
173     cl::init(500));
174 
175 static cl::opt<unsigned> MaxSCEVCompareDepth(
176     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
177     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
181     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
182     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
183     cl::init(2));
184 
185 static cl::opt<unsigned> MaxValueCompareDepth(
186     "scalar-evolution-max-value-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive value complexity comparisons"),
188     cl::init(2));
189 
190 static cl::opt<unsigned>
191     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
192                   cl::desc("Maximum depth of recursive arithmetics"),
193                   cl::init(32));
194 
195 static cl::opt<unsigned> MaxConstantEvolvingDepth(
196     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
198 
199 static cl::opt<unsigned>
200     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
201                 cl::desc("Maximum depth of recursive SExt/ZExt"),
202                 cl::init(8));
203 
204 static cl::opt<unsigned>
205     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
206                   cl::desc("Max coefficients in AddRec during evolving"),
207                   cl::init(16));
208 
209 //===----------------------------------------------------------------------===//
210 //                           SCEV class definitions
211 //===----------------------------------------------------------------------===//
212 
213 //===----------------------------------------------------------------------===//
214 // Implementation of the SCEV class.
215 //
216 
217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218 LLVM_DUMP_METHOD void SCEV::dump() const {
219   print(dbgs());
220   dbgs() << '\n';
221 }
222 #endif
223 
224 void SCEV::print(raw_ostream &OS) const {
225   switch (static_cast<SCEVTypes>(getSCEVType())) {
226   case scConstant:
227     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
228     return;
229   case scTruncate: {
230     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
231     const SCEV *Op = Trunc->getOperand();
232     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
233        << *Trunc->getType() << ")";
234     return;
235   }
236   case scZeroExtend: {
237     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
238     const SCEV *Op = ZExt->getOperand();
239     OS << "(zext " << *Op->getType() << " " << *Op << " to "
240        << *ZExt->getType() << ")";
241     return;
242   }
243   case scSignExtend: {
244     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
245     const SCEV *Op = SExt->getOperand();
246     OS << "(sext " << *Op->getType() << " " << *Op << " to "
247        << *SExt->getType() << ")";
248     return;
249   }
250   case scAddRecExpr: {
251     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
252     OS << "{" << *AR->getOperand(0);
253     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
254       OS << ",+," << *AR->getOperand(i);
255     OS << "}<";
256     if (AR->hasNoUnsignedWrap())
257       OS << "nuw><";
258     if (AR->hasNoSignedWrap())
259       OS << "nsw><";
260     if (AR->hasNoSelfWrap() &&
261         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
262       OS << "nw><";
263     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
264     OS << ">";
265     return;
266   }
267   case scAddExpr:
268   case scMulExpr:
269   case scUMaxExpr:
270   case scSMaxExpr: {
271     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
272     const char *OpStr = nullptr;
273     switch (NAry->getSCEVType()) {
274     case scAddExpr: OpStr = " + "; break;
275     case scMulExpr: OpStr = " * "; break;
276     case scUMaxExpr: OpStr = " umax "; break;
277     case scSMaxExpr: OpStr = " smax "; break;
278     }
279     OS << "(";
280     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
281          I != E; ++I) {
282       OS << **I;
283       if (std::next(I) != E)
284         OS << OpStr;
285     }
286     OS << ")";
287     switch (NAry->getSCEVType()) {
288     case scAddExpr:
289     case scMulExpr:
290       if (NAry->hasNoUnsignedWrap())
291         OS << "<nuw>";
292       if (NAry->hasNoSignedWrap())
293         OS << "<nsw>";
294     }
295     return;
296   }
297   case scUDivExpr: {
298     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
299     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
300     return;
301   }
302   case scUnknown: {
303     const SCEVUnknown *U = cast<SCEVUnknown>(this);
304     Type *AllocTy;
305     if (U->isSizeOf(AllocTy)) {
306       OS << "sizeof(" << *AllocTy << ")";
307       return;
308     }
309     if (U->isAlignOf(AllocTy)) {
310       OS << "alignof(" << *AllocTy << ")";
311       return;
312     }
313 
314     Type *CTy;
315     Constant *FieldNo;
316     if (U->isOffsetOf(CTy, FieldNo)) {
317       OS << "offsetof(" << *CTy << ", ";
318       FieldNo->printAsOperand(OS, false);
319       OS << ")";
320       return;
321     }
322 
323     // Otherwise just print it normally.
324     U->getValue()->printAsOperand(OS, false);
325     return;
326   }
327   case scCouldNotCompute:
328     OS << "***COULDNOTCOMPUTE***";
329     return;
330   }
331   llvm_unreachable("Unknown SCEV kind!");
332 }
333 
334 Type *SCEV::getType() const {
335   switch (static_cast<SCEVTypes>(getSCEVType())) {
336   case scConstant:
337     return cast<SCEVConstant>(this)->getType();
338   case scTruncate:
339   case scZeroExtend:
340   case scSignExtend:
341     return cast<SCEVCastExpr>(this)->getType();
342   case scAddRecExpr:
343   case scMulExpr:
344   case scUMaxExpr:
345   case scSMaxExpr:
346     return cast<SCEVNAryExpr>(this)->getType();
347   case scAddExpr:
348     return cast<SCEVAddExpr>(this)->getType();
349   case scUDivExpr:
350     return cast<SCEVUDivExpr>(this)->getType();
351   case scUnknown:
352     return cast<SCEVUnknown>(this)->getType();
353   case scCouldNotCompute:
354     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
355   }
356   llvm_unreachable("Unknown SCEV kind!");
357 }
358 
359 bool SCEV::isZero() const {
360   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
361     return SC->getValue()->isZero();
362   return false;
363 }
364 
365 bool SCEV::isOne() const {
366   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
367     return SC->getValue()->isOne();
368   return false;
369 }
370 
371 bool SCEV::isAllOnesValue() const {
372   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
373     return SC->getValue()->isMinusOne();
374   return false;
375 }
376 
377 bool SCEV::isNonConstantNegative() const {
378   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
379   if (!Mul) return false;
380 
381   // If there is a constant factor, it will be first.
382   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
383   if (!SC) return false;
384 
385   // Return true if the value is negative, this matches things like (-42 * V).
386   return SC->getAPInt().isNegative();
387 }
388 
389 SCEVCouldNotCompute::SCEVCouldNotCompute() :
390   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
391 
392 bool SCEVCouldNotCompute::classof(const SCEV *S) {
393   return S->getSCEVType() == scCouldNotCompute;
394 }
395 
396 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
397   FoldingSetNodeID ID;
398   ID.AddInteger(scConstant);
399   ID.AddPointer(V);
400   void *IP = nullptr;
401   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
402   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
403   UniqueSCEVs.InsertNode(S, IP);
404   return S;
405 }
406 
407 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
408   return getConstant(ConstantInt::get(getContext(), Val));
409 }
410 
411 const SCEV *
412 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
413   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
414   return getConstant(ConstantInt::get(ITy, V, isSigned));
415 }
416 
417 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
418                            unsigned SCEVTy, const SCEV *op, Type *ty)
419   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
420 
421 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
422                                    const SCEV *op, Type *ty)
423   : SCEVCastExpr(ID, scTruncate, op, ty) {
424   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
425          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
426          "Cannot truncate non-integer value!");
427 }
428 
429 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
430                                        const SCEV *op, Type *ty)
431   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
432   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
433          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
434          "Cannot zero extend non-integer value!");
435 }
436 
437 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
438                                        const SCEV *op, Type *ty)
439   : SCEVCastExpr(ID, scSignExtend, op, ty) {
440   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
441          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
442          "Cannot sign extend non-integer value!");
443 }
444 
445 void SCEVUnknown::deleted() {
446   // Clear this SCEVUnknown from various maps.
447   SE->forgetMemoizedResults(this);
448 
449   // Remove this SCEVUnknown from the uniquing map.
450   SE->UniqueSCEVs.RemoveNode(this);
451 
452   // Release the value.
453   setValPtr(nullptr);
454 }
455 
456 void SCEVUnknown::allUsesReplacedWith(Value *New) {
457   // Remove this SCEVUnknown from the uniquing map.
458   SE->UniqueSCEVs.RemoveNode(this);
459 
460   // Update this SCEVUnknown to point to the new value. This is needed
461   // because there may still be outstanding SCEVs which still point to
462   // this SCEVUnknown.
463   setValPtr(New);
464 }
465 
466 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
467   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
468     if (VCE->getOpcode() == Instruction::PtrToInt)
469       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
470         if (CE->getOpcode() == Instruction::GetElementPtr &&
471             CE->getOperand(0)->isNullValue() &&
472             CE->getNumOperands() == 2)
473           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
474             if (CI->isOne()) {
475               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
476                                  ->getElementType();
477               return true;
478             }
479 
480   return false;
481 }
482 
483 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
484   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
485     if (VCE->getOpcode() == Instruction::PtrToInt)
486       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
487         if (CE->getOpcode() == Instruction::GetElementPtr &&
488             CE->getOperand(0)->isNullValue()) {
489           Type *Ty =
490             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
491           if (StructType *STy = dyn_cast<StructType>(Ty))
492             if (!STy->isPacked() &&
493                 CE->getNumOperands() == 3 &&
494                 CE->getOperand(1)->isNullValue()) {
495               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
496                 if (CI->isOne() &&
497                     STy->getNumElements() == 2 &&
498                     STy->getElementType(0)->isIntegerTy(1)) {
499                   AllocTy = STy->getElementType(1);
500                   return true;
501                 }
502             }
503         }
504 
505   return false;
506 }
507 
508 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
509   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
510     if (VCE->getOpcode() == Instruction::PtrToInt)
511       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
512         if (CE->getOpcode() == Instruction::GetElementPtr &&
513             CE->getNumOperands() == 3 &&
514             CE->getOperand(0)->isNullValue() &&
515             CE->getOperand(1)->isNullValue()) {
516           Type *Ty =
517             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
518           // Ignore vector types here so that ScalarEvolutionExpander doesn't
519           // emit getelementptrs that index into vectors.
520           if (Ty->isStructTy() || Ty->isArrayTy()) {
521             CTy = Ty;
522             FieldNo = CE->getOperand(2);
523             return true;
524           }
525         }
526 
527   return false;
528 }
529 
530 //===----------------------------------------------------------------------===//
531 //                               SCEV Utilities
532 //===----------------------------------------------------------------------===//
533 
534 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
535 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
536 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
537 /// have been previously deemed to be "equally complex" by this routine.  It is
538 /// intended to avoid exponential time complexity in cases like:
539 ///
540 ///   %a = f(%x, %y)
541 ///   %b = f(%a, %a)
542 ///   %c = f(%b, %b)
543 ///
544 ///   %d = f(%x, %y)
545 ///   %e = f(%d, %d)
546 ///   %f = f(%e, %e)
547 ///
548 ///   CompareValueComplexity(%f, %c)
549 ///
550 /// Since we do not continue running this routine on expression trees once we
551 /// have seen unequal values, there is no need to track them in the cache.
552 static int
553 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
554                        const LoopInfo *const LI, Value *LV, Value *RV,
555                        unsigned Depth) {
556   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
557     return 0;
558 
559   // Order pointer values after integer values. This helps SCEVExpander form
560   // GEPs.
561   bool LIsPointer = LV->getType()->isPointerTy(),
562        RIsPointer = RV->getType()->isPointerTy();
563   if (LIsPointer != RIsPointer)
564     return (int)LIsPointer - (int)RIsPointer;
565 
566   // Compare getValueID values.
567   unsigned LID = LV->getValueID(), RID = RV->getValueID();
568   if (LID != RID)
569     return (int)LID - (int)RID;
570 
571   // Sort arguments by their position.
572   if (const auto *LA = dyn_cast<Argument>(LV)) {
573     const auto *RA = cast<Argument>(RV);
574     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
575     return (int)LArgNo - (int)RArgNo;
576   }
577 
578   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
579     const auto *RGV = cast<GlobalValue>(RV);
580 
581     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
582       auto LT = GV->getLinkage();
583       return !(GlobalValue::isPrivateLinkage(LT) ||
584                GlobalValue::isInternalLinkage(LT));
585     };
586 
587     // Use the names to distinguish the two values, but only if the
588     // names are semantically important.
589     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
590       return LGV->getName().compare(RGV->getName());
591   }
592 
593   // For instructions, compare their loop depth, and their operand count.  This
594   // is pretty loose.
595   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
596     const auto *RInst = cast<Instruction>(RV);
597 
598     // Compare loop depths.
599     const BasicBlock *LParent = LInst->getParent(),
600                      *RParent = RInst->getParent();
601     if (LParent != RParent) {
602       unsigned LDepth = LI->getLoopDepth(LParent),
603                RDepth = LI->getLoopDepth(RParent);
604       if (LDepth != RDepth)
605         return (int)LDepth - (int)RDepth;
606     }
607 
608     // Compare the number of operands.
609     unsigned LNumOps = LInst->getNumOperands(),
610              RNumOps = RInst->getNumOperands();
611     if (LNumOps != RNumOps)
612       return (int)LNumOps - (int)RNumOps;
613 
614     for (unsigned Idx : seq(0u, LNumOps)) {
615       int Result =
616           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
617                                  RInst->getOperand(Idx), Depth + 1);
618       if (Result != 0)
619         return Result;
620     }
621   }
622 
623   EqCacheValue.unionSets(LV, RV);
624   return 0;
625 }
626 
627 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
628 // than RHS, respectively. A three-way result allows recursive comparisons to be
629 // more efficient.
630 static int CompareSCEVComplexity(
631     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
632     EquivalenceClasses<const Value *> &EqCacheValue,
633     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
634     DominatorTree &DT, unsigned Depth = 0) {
635   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
636   if (LHS == RHS)
637     return 0;
638 
639   // Primarily, sort the SCEVs by their getSCEVType().
640   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
641   if (LType != RType)
642     return (int)LType - (int)RType;
643 
644   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
645     return 0;
646   // Aside from the getSCEVType() ordering, the particular ordering
647   // isn't very important except that it's beneficial to be consistent,
648   // so that (a + b) and (b + a) don't end up as different expressions.
649   switch (static_cast<SCEVTypes>(LType)) {
650   case scUnknown: {
651     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
652     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
653 
654     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
655                                    RU->getValue(), Depth + 1);
656     if (X == 0)
657       EqCacheSCEV.unionSets(LHS, RHS);
658     return X;
659   }
660 
661   case scConstant: {
662     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
663     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
664 
665     // Compare constant values.
666     const APInt &LA = LC->getAPInt();
667     const APInt &RA = RC->getAPInt();
668     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
669     if (LBitWidth != RBitWidth)
670       return (int)LBitWidth - (int)RBitWidth;
671     return LA.ult(RA) ? -1 : 1;
672   }
673 
674   case scAddRecExpr: {
675     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
676     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
677 
678     // There is always a dominance between two recs that are used by one SCEV,
679     // so we can safely sort recs by loop header dominance. We require such
680     // order in getAddExpr.
681     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
682     if (LLoop != RLoop) {
683       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
684       assert(LHead != RHead && "Two loops share the same header?");
685       if (DT.dominates(LHead, RHead))
686         return 1;
687       else
688         assert(DT.dominates(RHead, LHead) &&
689                "No dominance between recurrences used by one SCEV?");
690       return -1;
691     }
692 
693     // Addrec complexity grows with operand count.
694     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
695     if (LNumOps != RNumOps)
696       return (int)LNumOps - (int)RNumOps;
697 
698     // Compare NoWrap flags.
699     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
700       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
701 
702     // Lexicographically compare.
703     for (unsigned i = 0; i != LNumOps; ++i) {
704       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
705                                     LA->getOperand(i), RA->getOperand(i), DT,
706                                     Depth + 1);
707       if (X != 0)
708         return X;
709     }
710     EqCacheSCEV.unionSets(LHS, RHS);
711     return 0;
712   }
713 
714   case scAddExpr:
715   case scMulExpr:
716   case scSMaxExpr:
717   case scUMaxExpr: {
718     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
719     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
720 
721     // Lexicographically compare n-ary expressions.
722     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
723     if (LNumOps != RNumOps)
724       return (int)LNumOps - (int)RNumOps;
725 
726     // Compare NoWrap flags.
727     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
728       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
729 
730     for (unsigned i = 0; i != LNumOps; ++i) {
731       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
732                                     LC->getOperand(i), RC->getOperand(i), DT,
733                                     Depth + 1);
734       if (X != 0)
735         return X;
736     }
737     EqCacheSCEV.unionSets(LHS, RHS);
738     return 0;
739   }
740 
741   case scUDivExpr: {
742     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
743     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
744 
745     // Lexicographically compare udiv expressions.
746     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
747                                   RC->getLHS(), DT, Depth + 1);
748     if (X != 0)
749       return X;
750     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
751                               RC->getRHS(), DT, Depth + 1);
752     if (X == 0)
753       EqCacheSCEV.unionSets(LHS, RHS);
754     return X;
755   }
756 
757   case scTruncate:
758   case scZeroExtend:
759   case scSignExtend: {
760     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
761     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
762 
763     // Compare cast expressions by operand.
764     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
765                                   LC->getOperand(), RC->getOperand(), DT,
766                                   Depth + 1);
767     if (X == 0)
768       EqCacheSCEV.unionSets(LHS, RHS);
769     return X;
770   }
771 
772   case scCouldNotCompute:
773     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
774   }
775   llvm_unreachable("Unknown SCEV kind!");
776 }
777 
778 /// Given a list of SCEV objects, order them by their complexity, and group
779 /// objects of the same complexity together by value.  When this routine is
780 /// finished, we know that any duplicates in the vector are consecutive and that
781 /// complexity is monotonically increasing.
782 ///
783 /// Note that we go take special precautions to ensure that we get deterministic
784 /// results from this routine.  In other words, we don't want the results of
785 /// this to depend on where the addresses of various SCEV objects happened to
786 /// land in memory.
787 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
788                               LoopInfo *LI, DominatorTree &DT) {
789   if (Ops.size() < 2) return;  // Noop
790 
791   EquivalenceClasses<const SCEV *> EqCacheSCEV;
792   EquivalenceClasses<const Value *> EqCacheValue;
793   if (Ops.size() == 2) {
794     // This is the common case, which also happens to be trivially simple.
795     // Special case it.
796     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
797     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
798       std::swap(LHS, RHS);
799     return;
800   }
801 
802   // Do the rough sort by complexity.
803   std::stable_sort(Ops.begin(), Ops.end(),
804                    [&](const SCEV *LHS, const SCEV *RHS) {
805                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
806                                                   LHS, RHS, DT) < 0;
807                    });
808 
809   // Now that we are sorted by complexity, group elements of the same
810   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
811   // be extremely short in practice.  Note that we take this approach because we
812   // do not want to depend on the addresses of the objects we are grouping.
813   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
814     const SCEV *S = Ops[i];
815     unsigned Complexity = S->getSCEVType();
816 
817     // If there are any objects of the same complexity and same value as this
818     // one, group them.
819     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
820       if (Ops[j] == S) { // Found a duplicate.
821         // Move it to immediately after i'th element.
822         std::swap(Ops[i+1], Ops[j]);
823         ++i;   // no need to rescan it.
824         if (i == e-2) return;  // Done!
825       }
826     }
827   }
828 }
829 
830 // Returns the size of the SCEV S.
831 static inline int sizeOfSCEV(const SCEV *S) {
832   struct FindSCEVSize {
833     int Size = 0;
834 
835     FindSCEVSize() = default;
836 
837     bool follow(const SCEV *S) {
838       ++Size;
839       // Keep looking at all operands of S.
840       return true;
841     }
842 
843     bool isDone() const {
844       return false;
845     }
846   };
847 
848   FindSCEVSize F;
849   SCEVTraversal<FindSCEVSize> ST(F);
850   ST.visitAll(S);
851   return F.Size;
852 }
853 
854 namespace {
855 
856 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
857 public:
858   // Computes the Quotient and Remainder of the division of Numerator by
859   // Denominator.
860   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
861                      const SCEV *Denominator, const SCEV **Quotient,
862                      const SCEV **Remainder) {
863     assert(Numerator && Denominator && "Uninitialized SCEV");
864 
865     SCEVDivision D(SE, Numerator, Denominator);
866 
867     // Check for the trivial case here to avoid having to check for it in the
868     // rest of the code.
869     if (Numerator == Denominator) {
870       *Quotient = D.One;
871       *Remainder = D.Zero;
872       return;
873     }
874 
875     if (Numerator->isZero()) {
876       *Quotient = D.Zero;
877       *Remainder = D.Zero;
878       return;
879     }
880 
881     // A simple case when N/1. The quotient is N.
882     if (Denominator->isOne()) {
883       *Quotient = Numerator;
884       *Remainder = D.Zero;
885       return;
886     }
887 
888     // Split the Denominator when it is a product.
889     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
890       const SCEV *Q, *R;
891       *Quotient = Numerator;
892       for (const SCEV *Op : T->operands()) {
893         divide(SE, *Quotient, Op, &Q, &R);
894         *Quotient = Q;
895 
896         // Bail out when the Numerator is not divisible by one of the terms of
897         // the Denominator.
898         if (!R->isZero()) {
899           *Quotient = D.Zero;
900           *Remainder = Numerator;
901           return;
902         }
903       }
904       *Remainder = D.Zero;
905       return;
906     }
907 
908     D.visit(Numerator);
909     *Quotient = D.Quotient;
910     *Remainder = D.Remainder;
911   }
912 
913   // Except in the trivial case described above, we do not know how to divide
914   // Expr by Denominator for the following functions with empty implementation.
915   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
916   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
917   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
918   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
919   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
920   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
921   void visitUnknown(const SCEVUnknown *Numerator) {}
922   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
923 
924   void visitConstant(const SCEVConstant *Numerator) {
925     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
926       APInt NumeratorVal = Numerator->getAPInt();
927       APInt DenominatorVal = D->getAPInt();
928       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
929       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
930 
931       if (NumeratorBW > DenominatorBW)
932         DenominatorVal = DenominatorVal.sext(NumeratorBW);
933       else if (NumeratorBW < DenominatorBW)
934         NumeratorVal = NumeratorVal.sext(DenominatorBW);
935 
936       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
937       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
938       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
939       Quotient = SE.getConstant(QuotientVal);
940       Remainder = SE.getConstant(RemainderVal);
941       return;
942     }
943   }
944 
945   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
946     const SCEV *StartQ, *StartR, *StepQ, *StepR;
947     if (!Numerator->isAffine())
948       return cannotDivide(Numerator);
949     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
950     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
951     // Bail out if the types do not match.
952     Type *Ty = Denominator->getType();
953     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
954         Ty != StepQ->getType() || Ty != StepR->getType())
955       return cannotDivide(Numerator);
956     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
957                                 Numerator->getNoWrapFlags());
958     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
959                                  Numerator->getNoWrapFlags());
960   }
961 
962   void visitAddExpr(const SCEVAddExpr *Numerator) {
963     SmallVector<const SCEV *, 2> Qs, Rs;
964     Type *Ty = Denominator->getType();
965 
966     for (const SCEV *Op : Numerator->operands()) {
967       const SCEV *Q, *R;
968       divide(SE, Op, Denominator, &Q, &R);
969 
970       // Bail out if types do not match.
971       if (Ty != Q->getType() || Ty != R->getType())
972         return cannotDivide(Numerator);
973 
974       Qs.push_back(Q);
975       Rs.push_back(R);
976     }
977 
978     if (Qs.size() == 1) {
979       Quotient = Qs[0];
980       Remainder = Rs[0];
981       return;
982     }
983 
984     Quotient = SE.getAddExpr(Qs);
985     Remainder = SE.getAddExpr(Rs);
986   }
987 
988   void visitMulExpr(const SCEVMulExpr *Numerator) {
989     SmallVector<const SCEV *, 2> Qs;
990     Type *Ty = Denominator->getType();
991 
992     bool FoundDenominatorTerm = false;
993     for (const SCEV *Op : Numerator->operands()) {
994       // Bail out if types do not match.
995       if (Ty != Op->getType())
996         return cannotDivide(Numerator);
997 
998       if (FoundDenominatorTerm) {
999         Qs.push_back(Op);
1000         continue;
1001       }
1002 
1003       // Check whether Denominator divides one of the product operands.
1004       const SCEV *Q, *R;
1005       divide(SE, Op, Denominator, &Q, &R);
1006       if (!R->isZero()) {
1007         Qs.push_back(Op);
1008         continue;
1009       }
1010 
1011       // Bail out if types do not match.
1012       if (Ty != Q->getType())
1013         return cannotDivide(Numerator);
1014 
1015       FoundDenominatorTerm = true;
1016       Qs.push_back(Q);
1017     }
1018 
1019     if (FoundDenominatorTerm) {
1020       Remainder = Zero;
1021       if (Qs.size() == 1)
1022         Quotient = Qs[0];
1023       else
1024         Quotient = SE.getMulExpr(Qs);
1025       return;
1026     }
1027 
1028     if (!isa<SCEVUnknown>(Denominator))
1029       return cannotDivide(Numerator);
1030 
1031     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1032     ValueToValueMap RewriteMap;
1033     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1034         cast<SCEVConstant>(Zero)->getValue();
1035     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1036 
1037     if (Remainder->isZero()) {
1038       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1039       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1040           cast<SCEVConstant>(One)->getValue();
1041       Quotient =
1042           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1043       return;
1044     }
1045 
1046     // Quotient is (Numerator - Remainder) divided by Denominator.
1047     const SCEV *Q, *R;
1048     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1049     // This SCEV does not seem to simplify: fail the division here.
1050     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1051       return cannotDivide(Numerator);
1052     divide(SE, Diff, Denominator, &Q, &R);
1053     if (R != Zero)
1054       return cannotDivide(Numerator);
1055     Quotient = Q;
1056   }
1057 
1058 private:
1059   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1060                const SCEV *Denominator)
1061       : SE(S), Denominator(Denominator) {
1062     Zero = SE.getZero(Denominator->getType());
1063     One = SE.getOne(Denominator->getType());
1064 
1065     // We generally do not know how to divide Expr by Denominator. We
1066     // initialize the division to a "cannot divide" state to simplify the rest
1067     // of the code.
1068     cannotDivide(Numerator);
1069   }
1070 
1071   // Convenience function for giving up on the division. We set the quotient to
1072   // be equal to zero and the remainder to be equal to the numerator.
1073   void cannotDivide(const SCEV *Numerator) {
1074     Quotient = Zero;
1075     Remainder = Numerator;
1076   }
1077 
1078   ScalarEvolution &SE;
1079   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1080 };
1081 
1082 } // end anonymous namespace
1083 
1084 //===----------------------------------------------------------------------===//
1085 //                      Simple SCEV method implementations
1086 //===----------------------------------------------------------------------===//
1087 
1088 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1089 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1090                                        ScalarEvolution &SE,
1091                                        Type *ResultTy) {
1092   // Handle the simplest case efficiently.
1093   if (K == 1)
1094     return SE.getTruncateOrZeroExtend(It, ResultTy);
1095 
1096   // We are using the following formula for BC(It, K):
1097   //
1098   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1099   //
1100   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1101   // overflow.  Hence, we must assure that the result of our computation is
1102   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1103   // safe in modular arithmetic.
1104   //
1105   // However, this code doesn't use exactly that formula; the formula it uses
1106   // is something like the following, where T is the number of factors of 2 in
1107   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1108   // exponentiation:
1109   //
1110   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1111   //
1112   // This formula is trivially equivalent to the previous formula.  However,
1113   // this formula can be implemented much more efficiently.  The trick is that
1114   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1115   // arithmetic.  To do exact division in modular arithmetic, all we have
1116   // to do is multiply by the inverse.  Therefore, this step can be done at
1117   // width W.
1118   //
1119   // The next issue is how to safely do the division by 2^T.  The way this
1120   // is done is by doing the multiplication step at a width of at least W + T
1121   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1122   // when we perform the division by 2^T (which is equivalent to a right shift
1123   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1124   // truncated out after the division by 2^T.
1125   //
1126   // In comparison to just directly using the first formula, this technique
1127   // is much more efficient; using the first formula requires W * K bits,
1128   // but this formula less than W + K bits. Also, the first formula requires
1129   // a division step, whereas this formula only requires multiplies and shifts.
1130   //
1131   // It doesn't matter whether the subtraction step is done in the calculation
1132   // width or the input iteration count's width; if the subtraction overflows,
1133   // the result must be zero anyway.  We prefer here to do it in the width of
1134   // the induction variable because it helps a lot for certain cases; CodeGen
1135   // isn't smart enough to ignore the overflow, which leads to much less
1136   // efficient code if the width of the subtraction is wider than the native
1137   // register width.
1138   //
1139   // (It's possible to not widen at all by pulling out factors of 2 before
1140   // the multiplication; for example, K=2 can be calculated as
1141   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1142   // extra arithmetic, so it's not an obvious win, and it gets
1143   // much more complicated for K > 3.)
1144 
1145   // Protection from insane SCEVs; this bound is conservative,
1146   // but it probably doesn't matter.
1147   if (K > 1000)
1148     return SE.getCouldNotCompute();
1149 
1150   unsigned W = SE.getTypeSizeInBits(ResultTy);
1151 
1152   // Calculate K! / 2^T and T; we divide out the factors of two before
1153   // multiplying for calculating K! / 2^T to avoid overflow.
1154   // Other overflow doesn't matter because we only care about the bottom
1155   // W bits of the result.
1156   APInt OddFactorial(W, 1);
1157   unsigned T = 1;
1158   for (unsigned i = 3; i <= K; ++i) {
1159     APInt Mult(W, i);
1160     unsigned TwoFactors = Mult.countTrailingZeros();
1161     T += TwoFactors;
1162     Mult.lshrInPlace(TwoFactors);
1163     OddFactorial *= Mult;
1164   }
1165 
1166   // We need at least W + T bits for the multiplication step
1167   unsigned CalculationBits = W + T;
1168 
1169   // Calculate 2^T, at width T+W.
1170   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1171 
1172   // Calculate the multiplicative inverse of K! / 2^T;
1173   // this multiplication factor will perform the exact division by
1174   // K! / 2^T.
1175   APInt Mod = APInt::getSignedMinValue(W+1);
1176   APInt MultiplyFactor = OddFactorial.zext(W+1);
1177   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1178   MultiplyFactor = MultiplyFactor.trunc(W);
1179 
1180   // Calculate the product, at width T+W
1181   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1182                                                       CalculationBits);
1183   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1184   for (unsigned i = 1; i != K; ++i) {
1185     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1186     Dividend = SE.getMulExpr(Dividend,
1187                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1188   }
1189 
1190   // Divide by 2^T
1191   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1192 
1193   // Truncate the result, and divide by K! / 2^T.
1194 
1195   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1196                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1197 }
1198 
1199 /// Return the value of this chain of recurrences at the specified iteration
1200 /// number.  We can evaluate this recurrence by multiplying each element in the
1201 /// chain by the binomial coefficient corresponding to it.  In other words, we
1202 /// can evaluate {A,+,B,+,C,+,D} as:
1203 ///
1204 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1205 ///
1206 /// where BC(It, k) stands for binomial coefficient.
1207 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1208                                                 ScalarEvolution &SE) const {
1209   const SCEV *Result = getStart();
1210   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1211     // The computation is correct in the face of overflow provided that the
1212     // multiplication is performed _after_ the evaluation of the binomial
1213     // coefficient.
1214     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1215     if (isa<SCEVCouldNotCompute>(Coeff))
1216       return Coeff;
1217 
1218     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1219   }
1220   return Result;
1221 }
1222 
1223 //===----------------------------------------------------------------------===//
1224 //                    SCEV Expression folder implementations
1225 //===----------------------------------------------------------------------===//
1226 
1227 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1228                                              Type *Ty) {
1229   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1230          "This is not a truncating conversion!");
1231   assert(isSCEVable(Ty) &&
1232          "This is not a conversion to a SCEVable type!");
1233   Ty = getEffectiveSCEVType(Ty);
1234 
1235   FoldingSetNodeID ID;
1236   ID.AddInteger(scTruncate);
1237   ID.AddPointer(Op);
1238   ID.AddPointer(Ty);
1239   void *IP = nullptr;
1240   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1241 
1242   // Fold if the operand is constant.
1243   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1244     return getConstant(
1245       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1246 
1247   // trunc(trunc(x)) --> trunc(x)
1248   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1249     return getTruncateExpr(ST->getOperand(), Ty);
1250 
1251   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1252   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1253     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1254 
1255   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1256   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1257     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1258 
1259   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1260   // eliminate all the truncates, or we replace other casts with truncates.
1261   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1262     SmallVector<const SCEV *, 4> Operands;
1263     bool hasTrunc = false;
1264     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1265       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1266       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1267         hasTrunc = isa<SCEVTruncateExpr>(S);
1268       Operands.push_back(S);
1269     }
1270     if (!hasTrunc)
1271       return getAddExpr(Operands);
1272     // In spite we checked in the beginning that ID is not in the cache,
1273     // it is possible that during recursion and different modification
1274     // ID came to cache, so if we found it, just return it.
1275     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1276       return S;
1277   }
1278 
1279   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1280   // eliminate all the truncates, or we replace other casts with truncates.
1281   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1282     SmallVector<const SCEV *, 4> Operands;
1283     bool hasTrunc = false;
1284     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1285       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1286       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1287         hasTrunc = isa<SCEVTruncateExpr>(S);
1288       Operands.push_back(S);
1289     }
1290     if (!hasTrunc)
1291       return getMulExpr(Operands);
1292     // In spite we checked in the beginning that ID is not in the cache,
1293     // it is possible that during recursion and different modification
1294     // ID came to cache, so if we found it, just return it.
1295     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1296       return S;
1297   }
1298 
1299   // If the input value is a chrec scev, truncate the chrec's operands.
1300   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1301     SmallVector<const SCEV *, 4> Operands;
1302     for (const SCEV *Op : AddRec->operands())
1303       Operands.push_back(getTruncateExpr(Op, Ty));
1304     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1305   }
1306 
1307   // The cast wasn't folded; create an explicit cast node. We can reuse
1308   // the existing insert position since if we get here, we won't have
1309   // made any changes which would invalidate it.
1310   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1311                                                  Op, Ty);
1312   UniqueSCEVs.InsertNode(S, IP);
1313   addToLoopUseLists(S);
1314   return S;
1315 }
1316 
1317 // Get the limit of a recurrence such that incrementing by Step cannot cause
1318 // signed overflow as long as the value of the recurrence within the
1319 // loop does not exceed this limit before incrementing.
1320 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1321                                                  ICmpInst::Predicate *Pred,
1322                                                  ScalarEvolution *SE) {
1323   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1324   if (SE->isKnownPositive(Step)) {
1325     *Pred = ICmpInst::ICMP_SLT;
1326     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1327                            SE->getSignedRangeMax(Step));
1328   }
1329   if (SE->isKnownNegative(Step)) {
1330     *Pred = ICmpInst::ICMP_SGT;
1331     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1332                            SE->getSignedRangeMin(Step));
1333   }
1334   return nullptr;
1335 }
1336 
1337 // Get the limit of a recurrence such that incrementing by Step cannot cause
1338 // unsigned overflow as long as the value of the recurrence within the loop does
1339 // not exceed this limit before incrementing.
1340 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1341                                                    ICmpInst::Predicate *Pred,
1342                                                    ScalarEvolution *SE) {
1343   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1344   *Pred = ICmpInst::ICMP_ULT;
1345 
1346   return SE->getConstant(APInt::getMinValue(BitWidth) -
1347                          SE->getUnsignedRangeMax(Step));
1348 }
1349 
1350 namespace {
1351 
1352 struct ExtendOpTraitsBase {
1353   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1354                                                           unsigned);
1355 };
1356 
1357 // Used to make code generic over signed and unsigned overflow.
1358 template <typename ExtendOp> struct ExtendOpTraits {
1359   // Members present:
1360   //
1361   // static const SCEV::NoWrapFlags WrapType;
1362   //
1363   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1364   //
1365   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1366   //                                           ICmpInst::Predicate *Pred,
1367   //                                           ScalarEvolution *SE);
1368 };
1369 
1370 template <>
1371 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1372   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1373 
1374   static const GetExtendExprTy GetExtendExpr;
1375 
1376   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1377                                              ICmpInst::Predicate *Pred,
1378                                              ScalarEvolution *SE) {
1379     return getSignedOverflowLimitForStep(Step, Pred, SE);
1380   }
1381 };
1382 
1383 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1384     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1385 
1386 template <>
1387 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1388   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1389 
1390   static const GetExtendExprTy GetExtendExpr;
1391 
1392   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1393                                              ICmpInst::Predicate *Pred,
1394                                              ScalarEvolution *SE) {
1395     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1396   }
1397 };
1398 
1399 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1400     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1401 
1402 } // end anonymous namespace
1403 
1404 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1405 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1406 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1407 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1408 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1409 // expression "Step + sext/zext(PreIncAR)" is congruent with
1410 // "sext/zext(PostIncAR)"
1411 template <typename ExtendOpTy>
1412 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1413                                         ScalarEvolution *SE, unsigned Depth) {
1414   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1415   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1416 
1417   const Loop *L = AR->getLoop();
1418   const SCEV *Start = AR->getStart();
1419   const SCEV *Step = AR->getStepRecurrence(*SE);
1420 
1421   // Check for a simple looking step prior to loop entry.
1422   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1423   if (!SA)
1424     return nullptr;
1425 
1426   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1427   // subtraction is expensive. For this purpose, perform a quick and dirty
1428   // difference, by checking for Step in the operand list.
1429   SmallVector<const SCEV *, 4> DiffOps;
1430   for (const SCEV *Op : SA->operands())
1431     if (Op != Step)
1432       DiffOps.push_back(Op);
1433 
1434   if (DiffOps.size() == SA->getNumOperands())
1435     return nullptr;
1436 
1437   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1438   // `Step`:
1439 
1440   // 1. NSW/NUW flags on the step increment.
1441   auto PreStartFlags =
1442     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1443   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1444   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1445       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1446 
1447   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1448   // "S+X does not sign/unsign-overflow".
1449   //
1450 
1451   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1452   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1453       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1454     return PreStart;
1455 
1456   // 2. Direct overflow check on the step operation's expression.
1457   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1458   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1459   const SCEV *OperandExtendedStart =
1460       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1461                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1462   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1463     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1464       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1465       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1466       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1467       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1468     }
1469     return PreStart;
1470   }
1471 
1472   // 3. Loop precondition.
1473   ICmpInst::Predicate Pred;
1474   const SCEV *OverflowLimit =
1475       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1476 
1477   if (OverflowLimit &&
1478       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1479     return PreStart;
1480 
1481   return nullptr;
1482 }
1483 
1484 // Get the normalized zero or sign extended expression for this AddRec's Start.
1485 template <typename ExtendOpTy>
1486 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1487                                         ScalarEvolution *SE,
1488                                         unsigned Depth) {
1489   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1490 
1491   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1492   if (!PreStart)
1493     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1494 
1495   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1496                                              Depth),
1497                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1498 }
1499 
1500 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1501 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1502 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1503 //
1504 // Formally:
1505 //
1506 //     {S,+,X} == {S-T,+,X} + T
1507 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1508 //
1509 // If ({S-T,+,X} + T) does not overflow  ... (1)
1510 //
1511 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1512 //
1513 // If {S-T,+,X} does not overflow  ... (2)
1514 //
1515 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1516 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1517 //
1518 // If (S-T)+T does not overflow  ... (3)
1519 //
1520 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1521 //      == {Ext(S),+,Ext(X)} == LHS
1522 //
1523 // Thus, if (1), (2) and (3) are true for some T, then
1524 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1525 //
1526 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1527 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1528 // to check for (1) and (2).
1529 //
1530 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1531 // is `Delta` (defined below).
1532 template <typename ExtendOpTy>
1533 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1534                                                 const SCEV *Step,
1535                                                 const Loop *L) {
1536   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1537 
1538   // We restrict `Start` to a constant to prevent SCEV from spending too much
1539   // time here.  It is correct (but more expensive) to continue with a
1540   // non-constant `Start` and do a general SCEV subtraction to compute
1541   // `PreStart` below.
1542   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1543   if (!StartC)
1544     return false;
1545 
1546   APInt StartAI = StartC->getAPInt();
1547 
1548   for (unsigned Delta : {-2, -1, 1, 2}) {
1549     const SCEV *PreStart = getConstant(StartAI - Delta);
1550 
1551     FoldingSetNodeID ID;
1552     ID.AddInteger(scAddRecExpr);
1553     ID.AddPointer(PreStart);
1554     ID.AddPointer(Step);
1555     ID.AddPointer(L);
1556     void *IP = nullptr;
1557     const auto *PreAR =
1558       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1559 
1560     // Give up if we don't already have the add recurrence we need because
1561     // actually constructing an add recurrence is relatively expensive.
1562     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1563       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1564       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1565       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1566           DeltaS, &Pred, this);
1567       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1568         return true;
1569     }
1570   }
1571 
1572   return false;
1573 }
1574 
1575 const SCEV *
1576 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1577   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1578          "This is not an extending conversion!");
1579   assert(isSCEVable(Ty) &&
1580          "This is not a conversion to a SCEVable type!");
1581   Ty = getEffectiveSCEVType(Ty);
1582 
1583   // Fold if the operand is constant.
1584   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1585     return getConstant(
1586       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1587 
1588   // zext(zext(x)) --> zext(x)
1589   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1590     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1591 
1592   // Before doing any expensive analysis, check to see if we've already
1593   // computed a SCEV for this Op and Ty.
1594   FoldingSetNodeID ID;
1595   ID.AddInteger(scZeroExtend);
1596   ID.AddPointer(Op);
1597   ID.AddPointer(Ty);
1598   void *IP = nullptr;
1599   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1600   if (Depth > MaxExtDepth) {
1601     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1602                                                      Op, Ty);
1603     UniqueSCEVs.InsertNode(S, IP);
1604     addToLoopUseLists(S);
1605     return S;
1606   }
1607 
1608   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1609   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1610     // It's possible the bits taken off by the truncate were all zero bits. If
1611     // so, we should be able to simplify this further.
1612     const SCEV *X = ST->getOperand();
1613     ConstantRange CR = getUnsignedRange(X);
1614     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1615     unsigned NewBits = getTypeSizeInBits(Ty);
1616     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1617             CR.zextOrTrunc(NewBits)))
1618       return getTruncateOrZeroExtend(X, Ty);
1619   }
1620 
1621   // If the input value is a chrec scev, and we can prove that the value
1622   // did not overflow the old, smaller, value, we can zero extend all of the
1623   // operands (often constants).  This allows analysis of something like
1624   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1625   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1626     if (AR->isAffine()) {
1627       const SCEV *Start = AR->getStart();
1628       const SCEV *Step = AR->getStepRecurrence(*this);
1629       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1630       const Loop *L = AR->getLoop();
1631 
1632       if (!AR->hasNoUnsignedWrap()) {
1633         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1634         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1635       }
1636 
1637       // If we have special knowledge that this addrec won't overflow,
1638       // we don't need to do any further analysis.
1639       if (AR->hasNoUnsignedWrap())
1640         return getAddRecExpr(
1641             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1642             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1643 
1644       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1645       // Note that this serves two purposes: It filters out loops that are
1646       // simply not analyzable, and it covers the case where this code is
1647       // being called from within backedge-taken count analysis, such that
1648       // attempting to ask for the backedge-taken count would likely result
1649       // in infinite recursion. In the later case, the analysis code will
1650       // cope with a conservative value, and it will take care to purge
1651       // that value once it has finished.
1652       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1653       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1654         // Manually compute the final value for AR, checking for
1655         // overflow.
1656 
1657         // Check whether the backedge-taken count can be losslessly casted to
1658         // the addrec's type. The count is always unsigned.
1659         const SCEV *CastedMaxBECount =
1660           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1661         const SCEV *RecastedMaxBECount =
1662           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1663         if (MaxBECount == RecastedMaxBECount) {
1664           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1665           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1666           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1667                                         SCEV::FlagAnyWrap, Depth + 1);
1668           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1669                                                           SCEV::FlagAnyWrap,
1670                                                           Depth + 1),
1671                                                WideTy, Depth + 1);
1672           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1673           const SCEV *WideMaxBECount =
1674             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1675           const SCEV *OperandExtendedAdd =
1676             getAddExpr(WideStart,
1677                        getMulExpr(WideMaxBECount,
1678                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1679                                   SCEV::FlagAnyWrap, Depth + 1),
1680                        SCEV::FlagAnyWrap, Depth + 1);
1681           if (ZAdd == OperandExtendedAdd) {
1682             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1683             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1684             // Return the expression with the addrec on the outside.
1685             return getAddRecExpr(
1686                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1687                                                          Depth + 1),
1688                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1689                 AR->getNoWrapFlags());
1690           }
1691           // Similar to above, only this time treat the step value as signed.
1692           // This covers loops that count down.
1693           OperandExtendedAdd =
1694             getAddExpr(WideStart,
1695                        getMulExpr(WideMaxBECount,
1696                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1697                                   SCEV::FlagAnyWrap, Depth + 1),
1698                        SCEV::FlagAnyWrap, Depth + 1);
1699           if (ZAdd == OperandExtendedAdd) {
1700             // Cache knowledge of AR NW, which is propagated to this AddRec.
1701             // Negative step causes unsigned wrap, but it still can't self-wrap.
1702             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1703             // Return the expression with the addrec on the outside.
1704             return getAddRecExpr(
1705                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1706                                                          Depth + 1),
1707                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1708                 AR->getNoWrapFlags());
1709           }
1710         }
1711       }
1712 
1713       // Normally, in the cases we can prove no-overflow via a
1714       // backedge guarding condition, we can also compute a backedge
1715       // taken count for the loop.  The exceptions are assumptions and
1716       // guards present in the loop -- SCEV is not great at exploiting
1717       // these to compute max backedge taken counts, but can still use
1718       // these to prove lack of overflow.  Use this fact to avoid
1719       // doing extra work that may not pay off.
1720       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1721           !AC.assumptions().empty()) {
1722         // If the backedge is guarded by a comparison with the pre-inc
1723         // value the addrec is safe. Also, if the entry is guarded by
1724         // a comparison with the start value and the backedge is
1725         // guarded by a comparison with the post-inc value, the addrec
1726         // is safe.
1727         if (isKnownPositive(Step)) {
1728           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1729                                       getUnsignedRangeMax(Step));
1730           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1731               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1732             // Cache knowledge of AR NUW, which is propagated to this
1733             // AddRec.
1734             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1735             // Return the expression with the addrec on the outside.
1736             return getAddRecExpr(
1737                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1738                                                          Depth + 1),
1739                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1740                 AR->getNoWrapFlags());
1741           }
1742         } else if (isKnownNegative(Step)) {
1743           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1744                                       getSignedRangeMin(Step));
1745           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1746               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1747             // Cache knowledge of AR NW, which is propagated to this
1748             // AddRec.  Negative step causes unsigned wrap, but it
1749             // still can't self-wrap.
1750             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1751             // Return the expression with the addrec on the outside.
1752             return getAddRecExpr(
1753                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1754                                                          Depth + 1),
1755                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1756                 AR->getNoWrapFlags());
1757           }
1758         }
1759       }
1760 
1761       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1762         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1763         return getAddRecExpr(
1764             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1765             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1766       }
1767     }
1768 
1769   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1770     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1771     if (SA->hasNoUnsignedWrap()) {
1772       // If the addition does not unsign overflow then we can, by definition,
1773       // commute the zero extension with the addition operation.
1774       SmallVector<const SCEV *, 4> Ops;
1775       for (const auto *Op : SA->operands())
1776         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1777       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1778     }
1779   }
1780 
1781   // The cast wasn't folded; create an explicit cast node.
1782   // Recompute the insert position, as it may have been invalidated.
1783   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1784   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1785                                                    Op, Ty);
1786   UniqueSCEVs.InsertNode(S, IP);
1787   addToLoopUseLists(S);
1788   return S;
1789 }
1790 
1791 const SCEV *
1792 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1793   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1794          "This is not an extending conversion!");
1795   assert(isSCEVable(Ty) &&
1796          "This is not a conversion to a SCEVable type!");
1797   Ty = getEffectiveSCEVType(Ty);
1798 
1799   // Fold if the operand is constant.
1800   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1801     return getConstant(
1802       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1803 
1804   // sext(sext(x)) --> sext(x)
1805   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1806     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1807 
1808   // sext(zext(x)) --> zext(x)
1809   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1810     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1811 
1812   // Before doing any expensive analysis, check to see if we've already
1813   // computed a SCEV for this Op and Ty.
1814   FoldingSetNodeID ID;
1815   ID.AddInteger(scSignExtend);
1816   ID.AddPointer(Op);
1817   ID.AddPointer(Ty);
1818   void *IP = nullptr;
1819   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1820   // Limit recursion depth.
1821   if (Depth > MaxExtDepth) {
1822     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1823                                                      Op, Ty);
1824     UniqueSCEVs.InsertNode(S, IP);
1825     addToLoopUseLists(S);
1826     return S;
1827   }
1828 
1829   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1830   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1831     // It's possible the bits taken off by the truncate were all sign bits. If
1832     // so, we should be able to simplify this further.
1833     const SCEV *X = ST->getOperand();
1834     ConstantRange CR = getSignedRange(X);
1835     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1836     unsigned NewBits = getTypeSizeInBits(Ty);
1837     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1838             CR.sextOrTrunc(NewBits)))
1839       return getTruncateOrSignExtend(X, Ty);
1840   }
1841 
1842   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1843   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1844     if (SA->getNumOperands() == 2) {
1845       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1846       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1847       if (SMul && SC1) {
1848         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1849           const APInt &C1 = SC1->getAPInt();
1850           const APInt &C2 = SC2->getAPInt();
1851           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1852               C2.ugt(C1) && C2.isPowerOf2())
1853             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1854                               getSignExtendExpr(SMul, Ty, Depth + 1),
1855                               SCEV::FlagAnyWrap, Depth + 1);
1856         }
1857       }
1858     }
1859 
1860     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1861     if (SA->hasNoSignedWrap()) {
1862       // If the addition does not sign overflow then we can, by definition,
1863       // commute the sign extension with the addition operation.
1864       SmallVector<const SCEV *, 4> Ops;
1865       for (const auto *Op : SA->operands())
1866         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1867       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1868     }
1869   }
1870   // If the input value is a chrec scev, and we can prove that the value
1871   // did not overflow the old, smaller, value, we can sign extend all of the
1872   // operands (often constants).  This allows analysis of something like
1873   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1874   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1875     if (AR->isAffine()) {
1876       const SCEV *Start = AR->getStart();
1877       const SCEV *Step = AR->getStepRecurrence(*this);
1878       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1879       const Loop *L = AR->getLoop();
1880 
1881       if (!AR->hasNoSignedWrap()) {
1882         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1883         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1884       }
1885 
1886       // If we have special knowledge that this addrec won't overflow,
1887       // we don't need to do any further analysis.
1888       if (AR->hasNoSignedWrap())
1889         return getAddRecExpr(
1890             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1891             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1892 
1893       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1894       // Note that this serves two purposes: It filters out loops that are
1895       // simply not analyzable, and it covers the case where this code is
1896       // being called from within backedge-taken count analysis, such that
1897       // attempting to ask for the backedge-taken count would likely result
1898       // in infinite recursion. In the later case, the analysis code will
1899       // cope with a conservative value, and it will take care to purge
1900       // that value once it has finished.
1901       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1902       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1903         // Manually compute the final value for AR, checking for
1904         // overflow.
1905 
1906         // Check whether the backedge-taken count can be losslessly casted to
1907         // the addrec's type. The count is always unsigned.
1908         const SCEV *CastedMaxBECount =
1909           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1910         const SCEV *RecastedMaxBECount =
1911           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1912         if (MaxBECount == RecastedMaxBECount) {
1913           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1914           // Check whether Start+Step*MaxBECount has no signed overflow.
1915           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1916                                         SCEV::FlagAnyWrap, Depth + 1);
1917           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1918                                                           SCEV::FlagAnyWrap,
1919                                                           Depth + 1),
1920                                                WideTy, Depth + 1);
1921           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1922           const SCEV *WideMaxBECount =
1923             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1924           const SCEV *OperandExtendedAdd =
1925             getAddExpr(WideStart,
1926                        getMulExpr(WideMaxBECount,
1927                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1928                                   SCEV::FlagAnyWrap, Depth + 1),
1929                        SCEV::FlagAnyWrap, Depth + 1);
1930           if (SAdd == OperandExtendedAdd) {
1931             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1932             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1933             // Return the expression with the addrec on the outside.
1934             return getAddRecExpr(
1935                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1936                                                          Depth + 1),
1937                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1938                 AR->getNoWrapFlags());
1939           }
1940           // Similar to above, only this time treat the step value as unsigned.
1941           // This covers loops that count up with an unsigned step.
1942           OperandExtendedAdd =
1943             getAddExpr(WideStart,
1944                        getMulExpr(WideMaxBECount,
1945                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1946                                   SCEV::FlagAnyWrap, Depth + 1),
1947                        SCEV::FlagAnyWrap, Depth + 1);
1948           if (SAdd == OperandExtendedAdd) {
1949             // If AR wraps around then
1950             //
1951             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1952             // => SAdd != OperandExtendedAdd
1953             //
1954             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1955             // (SAdd == OperandExtendedAdd => AR is NW)
1956 
1957             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1958 
1959             // Return the expression with the addrec on the outside.
1960             return getAddRecExpr(
1961                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1962                                                          Depth + 1),
1963                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1964                 AR->getNoWrapFlags());
1965           }
1966         }
1967       }
1968 
1969       // Normally, in the cases we can prove no-overflow via a
1970       // backedge guarding condition, we can also compute a backedge
1971       // taken count for the loop.  The exceptions are assumptions and
1972       // guards present in the loop -- SCEV is not great at exploiting
1973       // these to compute max backedge taken counts, but can still use
1974       // these to prove lack of overflow.  Use this fact to avoid
1975       // doing extra work that may not pay off.
1976 
1977       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1978           !AC.assumptions().empty()) {
1979         // If the backedge is guarded by a comparison with the pre-inc
1980         // value the addrec is safe. Also, if the entry is guarded by
1981         // a comparison with the start value and the backedge is
1982         // guarded by a comparison with the post-inc value, the addrec
1983         // is safe.
1984         ICmpInst::Predicate Pred;
1985         const SCEV *OverflowLimit =
1986             getSignedOverflowLimitForStep(Step, &Pred, this);
1987         if (OverflowLimit &&
1988             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1989              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
1990           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1991           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1992           return getAddRecExpr(
1993               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1994               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1995         }
1996       }
1997 
1998       // If Start and Step are constants, check if we can apply this
1999       // transformation:
2000       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2001       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2002       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2003       if (SC1 && SC2) {
2004         const APInt &C1 = SC1->getAPInt();
2005         const APInt &C2 = SC2->getAPInt();
2006         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2007             C2.isPowerOf2()) {
2008           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2009           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2010                                             AR->getNoWrapFlags());
2011           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2012                             SCEV::FlagAnyWrap, Depth + 1);
2013         }
2014       }
2015 
2016       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2017         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2018         return getAddRecExpr(
2019             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2020             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2021       }
2022     }
2023 
2024   // If the input value is provably positive and we could not simplify
2025   // away the sext build a zext instead.
2026   if (isKnownNonNegative(Op))
2027     return getZeroExtendExpr(Op, Ty, Depth + 1);
2028 
2029   // The cast wasn't folded; create an explicit cast node.
2030   // Recompute the insert position, as it may have been invalidated.
2031   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2032   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2033                                                    Op, Ty);
2034   UniqueSCEVs.InsertNode(S, IP);
2035   addToLoopUseLists(S);
2036   return S;
2037 }
2038 
2039 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2040 /// unspecified bits out to the given type.
2041 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2042                                               Type *Ty) {
2043   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2044          "This is not an extending conversion!");
2045   assert(isSCEVable(Ty) &&
2046          "This is not a conversion to a SCEVable type!");
2047   Ty = getEffectiveSCEVType(Ty);
2048 
2049   // Sign-extend negative constants.
2050   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2051     if (SC->getAPInt().isNegative())
2052       return getSignExtendExpr(Op, Ty);
2053 
2054   // Peel off a truncate cast.
2055   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2056     const SCEV *NewOp = T->getOperand();
2057     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2058       return getAnyExtendExpr(NewOp, Ty);
2059     return getTruncateOrNoop(NewOp, Ty);
2060   }
2061 
2062   // Next try a zext cast. If the cast is folded, use it.
2063   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2064   if (!isa<SCEVZeroExtendExpr>(ZExt))
2065     return ZExt;
2066 
2067   // Next try a sext cast. If the cast is folded, use it.
2068   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2069   if (!isa<SCEVSignExtendExpr>(SExt))
2070     return SExt;
2071 
2072   // Force the cast to be folded into the operands of an addrec.
2073   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2074     SmallVector<const SCEV *, 4> Ops;
2075     for (const SCEV *Op : AR->operands())
2076       Ops.push_back(getAnyExtendExpr(Op, Ty));
2077     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2078   }
2079 
2080   // If the expression is obviously signed, use the sext cast value.
2081   if (isa<SCEVSMaxExpr>(Op))
2082     return SExt;
2083 
2084   // Absent any other information, use the zext cast value.
2085   return ZExt;
2086 }
2087 
2088 /// Process the given Ops list, which is a list of operands to be added under
2089 /// the given scale, update the given map. This is a helper function for
2090 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2091 /// that would form an add expression like this:
2092 ///
2093 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2094 ///
2095 /// where A and B are constants, update the map with these values:
2096 ///
2097 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2098 ///
2099 /// and add 13 + A*B*29 to AccumulatedConstant.
2100 /// This will allow getAddRecExpr to produce this:
2101 ///
2102 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2103 ///
2104 /// This form often exposes folding opportunities that are hidden in
2105 /// the original operand list.
2106 ///
2107 /// Return true iff it appears that any interesting folding opportunities
2108 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2109 /// the common case where no interesting opportunities are present, and
2110 /// is also used as a check to avoid infinite recursion.
2111 static bool
2112 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2113                              SmallVectorImpl<const SCEV *> &NewOps,
2114                              APInt &AccumulatedConstant,
2115                              const SCEV *const *Ops, size_t NumOperands,
2116                              const APInt &Scale,
2117                              ScalarEvolution &SE) {
2118   bool Interesting = false;
2119 
2120   // Iterate over the add operands. They are sorted, with constants first.
2121   unsigned i = 0;
2122   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2123     ++i;
2124     // Pull a buried constant out to the outside.
2125     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2126       Interesting = true;
2127     AccumulatedConstant += Scale * C->getAPInt();
2128   }
2129 
2130   // Next comes everything else. We're especially interested in multiplies
2131   // here, but they're in the middle, so just visit the rest with one loop.
2132   for (; i != NumOperands; ++i) {
2133     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2134     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2135       APInt NewScale =
2136           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2137       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2138         // A multiplication of a constant with another add; recurse.
2139         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2140         Interesting |=
2141           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2142                                        Add->op_begin(), Add->getNumOperands(),
2143                                        NewScale, SE);
2144       } else {
2145         // A multiplication of a constant with some other value. Update
2146         // the map.
2147         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2148         const SCEV *Key = SE.getMulExpr(MulOps);
2149         auto Pair = M.insert({Key, NewScale});
2150         if (Pair.second) {
2151           NewOps.push_back(Pair.first->first);
2152         } else {
2153           Pair.first->second += NewScale;
2154           // The map already had an entry for this value, which may indicate
2155           // a folding opportunity.
2156           Interesting = true;
2157         }
2158       }
2159     } else {
2160       // An ordinary operand. Update the map.
2161       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2162           M.insert({Ops[i], Scale});
2163       if (Pair.second) {
2164         NewOps.push_back(Pair.first->first);
2165       } else {
2166         Pair.first->second += Scale;
2167         // The map already had an entry for this value, which may indicate
2168         // a folding opportunity.
2169         Interesting = true;
2170       }
2171     }
2172   }
2173 
2174   return Interesting;
2175 }
2176 
2177 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2178 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2179 // can't-overflow flags for the operation if possible.
2180 static SCEV::NoWrapFlags
2181 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2182                       const SmallVectorImpl<const SCEV *> &Ops,
2183                       SCEV::NoWrapFlags Flags) {
2184   using namespace std::placeholders;
2185 
2186   using OBO = OverflowingBinaryOperator;
2187 
2188   bool CanAnalyze =
2189       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2190   (void)CanAnalyze;
2191   assert(CanAnalyze && "don't call from other places!");
2192 
2193   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2194   SCEV::NoWrapFlags SignOrUnsignWrap =
2195       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2196 
2197   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2198   auto IsKnownNonNegative = [&](const SCEV *S) {
2199     return SE->isKnownNonNegative(S);
2200   };
2201 
2202   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2203     Flags =
2204         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2205 
2206   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2207 
2208   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2209       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2210 
2211     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2212     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2213 
2214     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2215     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2216       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2217           Instruction::Add, C, OBO::NoSignedWrap);
2218       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2219         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2220     }
2221     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2222       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2223           Instruction::Add, C, OBO::NoUnsignedWrap);
2224       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2225         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2226     }
2227   }
2228 
2229   return Flags;
2230 }
2231 
2232 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2233   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2234 }
2235 
2236 /// Get a canonical add expression, or something simpler if possible.
2237 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2238                                         SCEV::NoWrapFlags Flags,
2239                                         unsigned Depth) {
2240   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2241          "only nuw or nsw allowed");
2242   assert(!Ops.empty() && "Cannot get empty add!");
2243   if (Ops.size() == 1) return Ops[0];
2244 #ifndef NDEBUG
2245   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2246   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2247     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2248            "SCEVAddExpr operand types don't match!");
2249 #endif
2250 
2251   // Sort by complexity, this groups all similar expression types together.
2252   GroupByComplexity(Ops, &LI, DT);
2253 
2254   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2255 
2256   // If there are any constants, fold them together.
2257   unsigned Idx = 0;
2258   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2259     ++Idx;
2260     assert(Idx < Ops.size());
2261     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2262       // We found two constants, fold them together!
2263       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2264       if (Ops.size() == 2) return Ops[0];
2265       Ops.erase(Ops.begin()+1);  // Erase the folded element
2266       LHSC = cast<SCEVConstant>(Ops[0]);
2267     }
2268 
2269     // If we are left with a constant zero being added, strip it off.
2270     if (LHSC->getValue()->isZero()) {
2271       Ops.erase(Ops.begin());
2272       --Idx;
2273     }
2274 
2275     if (Ops.size() == 1) return Ops[0];
2276   }
2277 
2278   // Limit recursion calls depth.
2279   if (Depth > MaxArithDepth)
2280     return getOrCreateAddExpr(Ops, Flags);
2281 
2282   // Okay, check to see if the same value occurs in the operand list more than
2283   // once.  If so, merge them together into an multiply expression.  Since we
2284   // sorted the list, these values are required to be adjacent.
2285   Type *Ty = Ops[0]->getType();
2286   bool FoundMatch = false;
2287   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2288     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2289       // Scan ahead to count how many equal operands there are.
2290       unsigned Count = 2;
2291       while (i+Count != e && Ops[i+Count] == Ops[i])
2292         ++Count;
2293       // Merge the values into a multiply.
2294       const SCEV *Scale = getConstant(Ty, Count);
2295       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2296       if (Ops.size() == Count)
2297         return Mul;
2298       Ops[i] = Mul;
2299       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2300       --i; e -= Count - 1;
2301       FoundMatch = true;
2302     }
2303   if (FoundMatch)
2304     return getAddExpr(Ops, Flags, Depth + 1);
2305 
2306   // Check for truncates. If all the operands are truncated from the same
2307   // type, see if factoring out the truncate would permit the result to be
2308   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2309   // if the contents of the resulting outer trunc fold to something simple.
2310   auto FindTruncSrcType = [&]() -> Type * {
2311     // We're ultimately looking to fold an addrec of truncs and muls of only
2312     // constants and truncs, so if we find any other types of SCEV
2313     // as operands of the addrec then we bail and return nullptr here.
2314     // Otherwise, we return the type of the operand of a trunc that we find.
2315     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2316       return T->getOperand()->getType();
2317     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2318       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2319       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2320         return T->getOperand()->getType();
2321     }
2322     return nullptr;
2323   };
2324   if (auto *SrcType = FindTruncSrcType()) {
2325     SmallVector<const SCEV *, 8> LargeOps;
2326     bool Ok = true;
2327     // Check all the operands to see if they can be represented in the
2328     // source type of the truncate.
2329     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2330       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2331         if (T->getOperand()->getType() != SrcType) {
2332           Ok = false;
2333           break;
2334         }
2335         LargeOps.push_back(T->getOperand());
2336       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2337         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2338       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2339         SmallVector<const SCEV *, 8> LargeMulOps;
2340         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2341           if (const SCEVTruncateExpr *T =
2342                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2343             if (T->getOperand()->getType() != SrcType) {
2344               Ok = false;
2345               break;
2346             }
2347             LargeMulOps.push_back(T->getOperand());
2348           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2349             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2350           } else {
2351             Ok = false;
2352             break;
2353           }
2354         }
2355         if (Ok)
2356           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2357       } else {
2358         Ok = false;
2359         break;
2360       }
2361     }
2362     if (Ok) {
2363       // Evaluate the expression in the larger type.
2364       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2365       // If it folds to something simple, use it. Otherwise, don't.
2366       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2367         return getTruncateExpr(Fold, Ty);
2368     }
2369   }
2370 
2371   // Skip past any other cast SCEVs.
2372   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2373     ++Idx;
2374 
2375   // If there are add operands they would be next.
2376   if (Idx < Ops.size()) {
2377     bool DeletedAdd = false;
2378     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2379       if (Ops.size() > AddOpsInlineThreshold ||
2380           Add->getNumOperands() > AddOpsInlineThreshold)
2381         break;
2382       // If we have an add, expand the add operands onto the end of the operands
2383       // list.
2384       Ops.erase(Ops.begin()+Idx);
2385       Ops.append(Add->op_begin(), Add->op_end());
2386       DeletedAdd = true;
2387     }
2388 
2389     // If we deleted at least one add, we added operands to the end of the list,
2390     // and they are not necessarily sorted.  Recurse to resort and resimplify
2391     // any operands we just acquired.
2392     if (DeletedAdd)
2393       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2394   }
2395 
2396   // Skip over the add expression until we get to a multiply.
2397   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2398     ++Idx;
2399 
2400   // Check to see if there are any folding opportunities present with
2401   // operands multiplied by constant values.
2402   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2403     uint64_t BitWidth = getTypeSizeInBits(Ty);
2404     DenseMap<const SCEV *, APInt> M;
2405     SmallVector<const SCEV *, 8> NewOps;
2406     APInt AccumulatedConstant(BitWidth, 0);
2407     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2408                                      Ops.data(), Ops.size(),
2409                                      APInt(BitWidth, 1), *this)) {
2410       struct APIntCompare {
2411         bool operator()(const APInt &LHS, const APInt &RHS) const {
2412           return LHS.ult(RHS);
2413         }
2414       };
2415 
2416       // Some interesting folding opportunity is present, so its worthwhile to
2417       // re-generate the operands list. Group the operands by constant scale,
2418       // to avoid multiplying by the same constant scale multiple times.
2419       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2420       for (const SCEV *NewOp : NewOps)
2421         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2422       // Re-generate the operands list.
2423       Ops.clear();
2424       if (AccumulatedConstant != 0)
2425         Ops.push_back(getConstant(AccumulatedConstant));
2426       for (auto &MulOp : MulOpLists)
2427         if (MulOp.first != 0)
2428           Ops.push_back(getMulExpr(
2429               getConstant(MulOp.first),
2430               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2431               SCEV::FlagAnyWrap, Depth + 1));
2432       if (Ops.empty())
2433         return getZero(Ty);
2434       if (Ops.size() == 1)
2435         return Ops[0];
2436       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2437     }
2438   }
2439 
2440   // If we are adding something to a multiply expression, make sure the
2441   // something is not already an operand of the multiply.  If so, merge it into
2442   // the multiply.
2443   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2444     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2445     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2446       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2447       if (isa<SCEVConstant>(MulOpSCEV))
2448         continue;
2449       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2450         if (MulOpSCEV == Ops[AddOp]) {
2451           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2452           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2453           if (Mul->getNumOperands() != 2) {
2454             // If the multiply has more than two operands, we must get the
2455             // Y*Z term.
2456             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2457                                                 Mul->op_begin()+MulOp);
2458             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2459             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2460           }
2461           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2462           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2463           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2464                                             SCEV::FlagAnyWrap, Depth + 1);
2465           if (Ops.size() == 2) return OuterMul;
2466           if (AddOp < Idx) {
2467             Ops.erase(Ops.begin()+AddOp);
2468             Ops.erase(Ops.begin()+Idx-1);
2469           } else {
2470             Ops.erase(Ops.begin()+Idx);
2471             Ops.erase(Ops.begin()+AddOp-1);
2472           }
2473           Ops.push_back(OuterMul);
2474           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2475         }
2476 
2477       // Check this multiply against other multiplies being added together.
2478       for (unsigned OtherMulIdx = Idx+1;
2479            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2480            ++OtherMulIdx) {
2481         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2482         // If MulOp occurs in OtherMul, we can fold the two multiplies
2483         // together.
2484         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2485              OMulOp != e; ++OMulOp)
2486           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2487             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2488             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2489             if (Mul->getNumOperands() != 2) {
2490               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2491                                                   Mul->op_begin()+MulOp);
2492               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2493               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2494             }
2495             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2496             if (OtherMul->getNumOperands() != 2) {
2497               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2498                                                   OtherMul->op_begin()+OMulOp);
2499               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2500               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2501             }
2502             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2503             const SCEV *InnerMulSum =
2504                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2505             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2506                                               SCEV::FlagAnyWrap, Depth + 1);
2507             if (Ops.size() == 2) return OuterMul;
2508             Ops.erase(Ops.begin()+Idx);
2509             Ops.erase(Ops.begin()+OtherMulIdx-1);
2510             Ops.push_back(OuterMul);
2511             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2512           }
2513       }
2514     }
2515   }
2516 
2517   // If there are any add recurrences in the operands list, see if any other
2518   // added values are loop invariant.  If so, we can fold them into the
2519   // recurrence.
2520   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2521     ++Idx;
2522 
2523   // Scan over all recurrences, trying to fold loop invariants into them.
2524   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2525     // Scan all of the other operands to this add and add them to the vector if
2526     // they are loop invariant w.r.t. the recurrence.
2527     SmallVector<const SCEV *, 8> LIOps;
2528     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2529     const Loop *AddRecLoop = AddRec->getLoop();
2530     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2531       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2532         LIOps.push_back(Ops[i]);
2533         Ops.erase(Ops.begin()+i);
2534         --i; --e;
2535       }
2536 
2537     // If we found some loop invariants, fold them into the recurrence.
2538     if (!LIOps.empty()) {
2539       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2540       LIOps.push_back(AddRec->getStart());
2541 
2542       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2543                                              AddRec->op_end());
2544       // This follows from the fact that the no-wrap flags on the outer add
2545       // expression are applicable on the 0th iteration, when the add recurrence
2546       // will be equal to its start value.
2547       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2548 
2549       // Build the new addrec. Propagate the NUW and NSW flags if both the
2550       // outer add and the inner addrec are guaranteed to have no overflow.
2551       // Always propagate NW.
2552       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2553       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2554 
2555       // If all of the other operands were loop invariant, we are done.
2556       if (Ops.size() == 1) return NewRec;
2557 
2558       // Otherwise, add the folded AddRec by the non-invariant parts.
2559       for (unsigned i = 0;; ++i)
2560         if (Ops[i] == AddRec) {
2561           Ops[i] = NewRec;
2562           break;
2563         }
2564       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2565     }
2566 
2567     // Okay, if there weren't any loop invariants to be folded, check to see if
2568     // there are multiple AddRec's with the same loop induction variable being
2569     // added together.  If so, we can fold them.
2570     for (unsigned OtherIdx = Idx+1;
2571          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2572          ++OtherIdx) {
2573       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2574       // so that the 1st found AddRecExpr is dominated by all others.
2575       assert(DT.dominates(
2576            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2577            AddRec->getLoop()->getHeader()) &&
2578         "AddRecExprs are not sorted in reverse dominance order?");
2579       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2580         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2581         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2582                                                AddRec->op_end());
2583         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2584              ++OtherIdx) {
2585           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2586           if (OtherAddRec->getLoop() == AddRecLoop) {
2587             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2588                  i != e; ++i) {
2589               if (i >= AddRecOps.size()) {
2590                 AddRecOps.append(OtherAddRec->op_begin()+i,
2591                                  OtherAddRec->op_end());
2592                 break;
2593               }
2594               SmallVector<const SCEV *, 2> TwoOps = {
2595                   AddRecOps[i], OtherAddRec->getOperand(i)};
2596               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2597             }
2598             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2599           }
2600         }
2601         // Step size has changed, so we cannot guarantee no self-wraparound.
2602         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2603         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2604       }
2605     }
2606 
2607     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2608     // next one.
2609   }
2610 
2611   // Okay, it looks like we really DO need an add expr.  Check to see if we
2612   // already have one, otherwise create a new one.
2613   return getOrCreateAddExpr(Ops, Flags);
2614 }
2615 
2616 const SCEV *
2617 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2618                                     SCEV::NoWrapFlags Flags) {
2619   FoldingSetNodeID ID;
2620   ID.AddInteger(scAddExpr);
2621   for (const SCEV *Op : Ops)
2622     ID.AddPointer(Op);
2623   void *IP = nullptr;
2624   SCEVAddExpr *S =
2625       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2626   if (!S) {
2627     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2628     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2629     S = new (SCEVAllocator)
2630         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2631     UniqueSCEVs.InsertNode(S, IP);
2632     addToLoopUseLists(S);
2633   }
2634   S->setNoWrapFlags(Flags);
2635   return S;
2636 }
2637 
2638 const SCEV *
2639 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2640                                     SCEV::NoWrapFlags Flags) {
2641   FoldingSetNodeID ID;
2642   ID.AddInteger(scMulExpr);
2643   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2644     ID.AddPointer(Ops[i]);
2645   void *IP = nullptr;
2646   SCEVMulExpr *S =
2647     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2648   if (!S) {
2649     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2650     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2651     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2652                                         O, Ops.size());
2653     UniqueSCEVs.InsertNode(S, IP);
2654     addToLoopUseLists(S);
2655   }
2656   S->setNoWrapFlags(Flags);
2657   return S;
2658 }
2659 
2660 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2661   uint64_t k = i*j;
2662   if (j > 1 && k / j != i) Overflow = true;
2663   return k;
2664 }
2665 
2666 /// Compute the result of "n choose k", the binomial coefficient.  If an
2667 /// intermediate computation overflows, Overflow will be set and the return will
2668 /// be garbage. Overflow is not cleared on absence of overflow.
2669 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2670   // We use the multiplicative formula:
2671   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2672   // At each iteration, we take the n-th term of the numeral and divide by the
2673   // (k-n)th term of the denominator.  This division will always produce an
2674   // integral result, and helps reduce the chance of overflow in the
2675   // intermediate computations. However, we can still overflow even when the
2676   // final result would fit.
2677 
2678   if (n == 0 || n == k) return 1;
2679   if (k > n) return 0;
2680 
2681   if (k > n/2)
2682     k = n-k;
2683 
2684   uint64_t r = 1;
2685   for (uint64_t i = 1; i <= k; ++i) {
2686     r = umul_ov(r, n-(i-1), Overflow);
2687     r /= i;
2688   }
2689   return r;
2690 }
2691 
2692 /// Determine if any of the operands in this SCEV are a constant or if
2693 /// any of the add or multiply expressions in this SCEV contain a constant.
2694 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2695   struct FindConstantInAddMulChain {
2696     bool FoundConstant = false;
2697 
2698     bool follow(const SCEV *S) {
2699       FoundConstant |= isa<SCEVConstant>(S);
2700       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2701     }
2702 
2703     bool isDone() const {
2704       return FoundConstant;
2705     }
2706   };
2707 
2708   FindConstantInAddMulChain F;
2709   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2710   ST.visitAll(StartExpr);
2711   return F.FoundConstant;
2712 }
2713 
2714 /// Get a canonical multiply expression, or something simpler if possible.
2715 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2716                                         SCEV::NoWrapFlags Flags,
2717                                         unsigned Depth) {
2718   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2719          "only nuw or nsw allowed");
2720   assert(!Ops.empty() && "Cannot get empty mul!");
2721   if (Ops.size() == 1) return Ops[0];
2722 #ifndef NDEBUG
2723   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2724   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2725     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2726            "SCEVMulExpr operand types don't match!");
2727 #endif
2728 
2729   // Sort by complexity, this groups all similar expression types together.
2730   GroupByComplexity(Ops, &LI, DT);
2731 
2732   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2733 
2734   // Limit recursion calls depth.
2735   if (Depth > MaxArithDepth)
2736     return getOrCreateMulExpr(Ops, Flags);
2737 
2738   // If there are any constants, fold them together.
2739   unsigned Idx = 0;
2740   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2741 
2742     // C1*(C2+V) -> C1*C2 + C1*V
2743     if (Ops.size() == 2)
2744         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2745           // If any of Add's ops are Adds or Muls with a constant,
2746           // apply this transformation as well.
2747           if (Add->getNumOperands() == 2)
2748             // TODO: There are some cases where this transformation is not
2749             // profitable, for example:
2750             // Add = (C0 + X) * Y + Z.
2751             // Maybe the scope of this transformation should be narrowed down.
2752             if (containsConstantInAddMulChain(Add))
2753               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2754                                            SCEV::FlagAnyWrap, Depth + 1),
2755                                 getMulExpr(LHSC, Add->getOperand(1),
2756                                            SCEV::FlagAnyWrap, Depth + 1),
2757                                 SCEV::FlagAnyWrap, Depth + 1);
2758 
2759     ++Idx;
2760     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2761       // We found two constants, fold them together!
2762       ConstantInt *Fold =
2763           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2764       Ops[0] = getConstant(Fold);
2765       Ops.erase(Ops.begin()+1);  // Erase the folded element
2766       if (Ops.size() == 1) return Ops[0];
2767       LHSC = cast<SCEVConstant>(Ops[0]);
2768     }
2769 
2770     // If we are left with a constant one being multiplied, strip it off.
2771     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2772       Ops.erase(Ops.begin());
2773       --Idx;
2774     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2775       // If we have a multiply of zero, it will always be zero.
2776       return Ops[0];
2777     } else if (Ops[0]->isAllOnesValue()) {
2778       // If we have a mul by -1 of an add, try distributing the -1 among the
2779       // add operands.
2780       if (Ops.size() == 2) {
2781         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2782           SmallVector<const SCEV *, 4> NewOps;
2783           bool AnyFolded = false;
2784           for (const SCEV *AddOp : Add->operands()) {
2785             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2786                                          Depth + 1);
2787             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2788             NewOps.push_back(Mul);
2789           }
2790           if (AnyFolded)
2791             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2792         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2793           // Negation preserves a recurrence's no self-wrap property.
2794           SmallVector<const SCEV *, 4> Operands;
2795           for (const SCEV *AddRecOp : AddRec->operands())
2796             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2797                                           Depth + 1));
2798 
2799           return getAddRecExpr(Operands, AddRec->getLoop(),
2800                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2801         }
2802       }
2803     }
2804 
2805     if (Ops.size() == 1)
2806       return Ops[0];
2807   }
2808 
2809   // Skip over the add expression until we get to a multiply.
2810   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2811     ++Idx;
2812 
2813   // If there are mul operands inline them all into this expression.
2814   if (Idx < Ops.size()) {
2815     bool DeletedMul = false;
2816     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2817       if (Ops.size() > MulOpsInlineThreshold)
2818         break;
2819       // If we have an mul, expand the mul operands onto the end of the
2820       // operands list.
2821       Ops.erase(Ops.begin()+Idx);
2822       Ops.append(Mul->op_begin(), Mul->op_end());
2823       DeletedMul = true;
2824     }
2825 
2826     // If we deleted at least one mul, we added operands to the end of the
2827     // list, and they are not necessarily sorted.  Recurse to resort and
2828     // resimplify any operands we just acquired.
2829     if (DeletedMul)
2830       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2831   }
2832 
2833   // If there are any add recurrences in the operands list, see if any other
2834   // added values are loop invariant.  If so, we can fold them into the
2835   // recurrence.
2836   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2837     ++Idx;
2838 
2839   // Scan over all recurrences, trying to fold loop invariants into them.
2840   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2841     // Scan all of the other operands to this mul and add them to the vector
2842     // if they are loop invariant w.r.t. the recurrence.
2843     SmallVector<const SCEV *, 8> LIOps;
2844     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2845     const Loop *AddRecLoop = AddRec->getLoop();
2846     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2847       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2848         LIOps.push_back(Ops[i]);
2849         Ops.erase(Ops.begin()+i);
2850         --i; --e;
2851       }
2852 
2853     // If we found some loop invariants, fold them into the recurrence.
2854     if (!LIOps.empty()) {
2855       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2856       SmallVector<const SCEV *, 4> NewOps;
2857       NewOps.reserve(AddRec->getNumOperands());
2858       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2859       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2860         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2861                                     SCEV::FlagAnyWrap, Depth + 1));
2862 
2863       // Build the new addrec. Propagate the NUW and NSW flags if both the
2864       // outer mul and the inner addrec are guaranteed to have no overflow.
2865       //
2866       // No self-wrap cannot be guaranteed after changing the step size, but
2867       // will be inferred if either NUW or NSW is true.
2868       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2869       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2870 
2871       // If all of the other operands were loop invariant, we are done.
2872       if (Ops.size() == 1) return NewRec;
2873 
2874       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2875       for (unsigned i = 0;; ++i)
2876         if (Ops[i] == AddRec) {
2877           Ops[i] = NewRec;
2878           break;
2879         }
2880       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2881     }
2882 
2883     // Okay, if there weren't any loop invariants to be folded, check to see
2884     // if there are multiple AddRec's with the same loop induction variable
2885     // being multiplied together.  If so, we can fold them.
2886 
2887     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2888     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2889     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2890     //   ]]],+,...up to x=2n}.
2891     // Note that the arguments to choose() are always integers with values
2892     // known at compile time, never SCEV objects.
2893     //
2894     // The implementation avoids pointless extra computations when the two
2895     // addrec's are of different length (mathematically, it's equivalent to
2896     // an infinite stream of zeros on the right).
2897     bool OpsModified = false;
2898     for (unsigned OtherIdx = Idx+1;
2899          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2900          ++OtherIdx) {
2901       const SCEVAddRecExpr *OtherAddRec =
2902         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2903       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2904         continue;
2905 
2906       // Limit max number of arguments to avoid creation of unreasonably big
2907       // SCEVAddRecs with very complex operands.
2908       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2909           MaxAddRecSize)
2910         continue;
2911 
2912       bool Overflow = false;
2913       Type *Ty = AddRec->getType();
2914       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2915       SmallVector<const SCEV*, 7> AddRecOps;
2916       for (int x = 0, xe = AddRec->getNumOperands() +
2917              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2918         const SCEV *Term = getZero(Ty);
2919         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2920           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2921           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2922                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2923                z < ze && !Overflow; ++z) {
2924             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2925             uint64_t Coeff;
2926             if (LargerThan64Bits)
2927               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2928             else
2929               Coeff = Coeff1*Coeff2;
2930             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2931             const SCEV *Term1 = AddRec->getOperand(y-z);
2932             const SCEV *Term2 = OtherAddRec->getOperand(z);
2933             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2934                                                SCEV::FlagAnyWrap, Depth + 1),
2935                               SCEV::FlagAnyWrap, Depth + 1);
2936           }
2937         }
2938         AddRecOps.push_back(Term);
2939       }
2940       if (!Overflow) {
2941         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2942                                               SCEV::FlagAnyWrap);
2943         if (Ops.size() == 2) return NewAddRec;
2944         Ops[Idx] = NewAddRec;
2945         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2946         OpsModified = true;
2947         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2948         if (!AddRec)
2949           break;
2950       }
2951     }
2952     if (OpsModified)
2953       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2954 
2955     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2956     // next one.
2957   }
2958 
2959   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2960   // already have one, otherwise create a new one.
2961   return getOrCreateMulExpr(Ops, Flags);
2962 }
2963 
2964 /// Represents an unsigned remainder expression based on unsigned division.
2965 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
2966                                          const SCEV *RHS) {
2967   assert(getEffectiveSCEVType(LHS->getType()) ==
2968          getEffectiveSCEVType(RHS->getType()) &&
2969          "SCEVURemExpr operand types don't match!");
2970 
2971   // Short-circuit easy cases
2972   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2973     // If constant is one, the result is trivial
2974     if (RHSC->getValue()->isOne())
2975       return getZero(LHS->getType()); // X urem 1 --> 0
2976 
2977     // If constant is a power of two, fold into a zext(trunc(LHS)).
2978     if (RHSC->getAPInt().isPowerOf2()) {
2979       Type *FullTy = LHS->getType();
2980       Type *TruncTy =
2981           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
2982       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
2983     }
2984   }
2985 
2986   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
2987   const SCEV *UDiv = getUDivExpr(LHS, RHS);
2988   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
2989   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
2990 }
2991 
2992 /// Get a canonical unsigned division expression, or something simpler if
2993 /// possible.
2994 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2995                                          const SCEV *RHS) {
2996   assert(getEffectiveSCEVType(LHS->getType()) ==
2997          getEffectiveSCEVType(RHS->getType()) &&
2998          "SCEVUDivExpr operand types don't match!");
2999 
3000   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3001     if (RHSC->getValue()->isOne())
3002       return LHS;                               // X udiv 1 --> x
3003     // If the denominator is zero, the result of the udiv is undefined. Don't
3004     // try to analyze it, because the resolution chosen here may differ from
3005     // the resolution chosen in other parts of the compiler.
3006     if (!RHSC->getValue()->isZero()) {
3007       // Determine if the division can be folded into the operands of
3008       // its operands.
3009       // TODO: Generalize this to non-constants by using known-bits information.
3010       Type *Ty = LHS->getType();
3011       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3012       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3013       // For non-power-of-two values, effectively round the value up to the
3014       // nearest power of two.
3015       if (!RHSC->getAPInt().isPowerOf2())
3016         ++MaxShiftAmt;
3017       IntegerType *ExtTy =
3018         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3019       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3020         if (const SCEVConstant *Step =
3021             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3022           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3023           const APInt &StepInt = Step->getAPInt();
3024           const APInt &DivInt = RHSC->getAPInt();
3025           if (!StepInt.urem(DivInt) &&
3026               getZeroExtendExpr(AR, ExtTy) ==
3027               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3028                             getZeroExtendExpr(Step, ExtTy),
3029                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3030             SmallVector<const SCEV *, 4> Operands;
3031             for (const SCEV *Op : AR->operands())
3032               Operands.push_back(getUDivExpr(Op, RHS));
3033             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3034           }
3035           /// Get a canonical UDivExpr for a recurrence.
3036           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3037           // We can currently only fold X%N if X is constant.
3038           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3039           if (StartC && !DivInt.urem(StepInt) &&
3040               getZeroExtendExpr(AR, ExtTy) ==
3041               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3042                             getZeroExtendExpr(Step, ExtTy),
3043                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3044             const APInt &StartInt = StartC->getAPInt();
3045             const APInt &StartRem = StartInt.urem(StepInt);
3046             if (StartRem != 0)
3047               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3048                                   AR->getLoop(), SCEV::FlagNW);
3049           }
3050         }
3051       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3052       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3053         SmallVector<const SCEV *, 4> Operands;
3054         for (const SCEV *Op : M->operands())
3055           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3056         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3057           // Find an operand that's safely divisible.
3058           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3059             const SCEV *Op = M->getOperand(i);
3060             const SCEV *Div = getUDivExpr(Op, RHSC);
3061             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3062               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3063                                                       M->op_end());
3064               Operands[i] = Div;
3065               return getMulExpr(Operands);
3066             }
3067           }
3068       }
3069       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3070       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3071         SmallVector<const SCEV *, 4> Operands;
3072         for (const SCEV *Op : A->operands())
3073           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3074         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3075           Operands.clear();
3076           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3077             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3078             if (isa<SCEVUDivExpr>(Op) ||
3079                 getMulExpr(Op, RHS) != A->getOperand(i))
3080               break;
3081             Operands.push_back(Op);
3082           }
3083           if (Operands.size() == A->getNumOperands())
3084             return getAddExpr(Operands);
3085         }
3086       }
3087 
3088       // Fold if both operands are constant.
3089       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3090         Constant *LHSCV = LHSC->getValue();
3091         Constant *RHSCV = RHSC->getValue();
3092         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3093                                                                    RHSCV)));
3094       }
3095     }
3096   }
3097 
3098   FoldingSetNodeID ID;
3099   ID.AddInteger(scUDivExpr);
3100   ID.AddPointer(LHS);
3101   ID.AddPointer(RHS);
3102   void *IP = nullptr;
3103   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3104   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3105                                              LHS, RHS);
3106   UniqueSCEVs.InsertNode(S, IP);
3107   addToLoopUseLists(S);
3108   return S;
3109 }
3110 
3111 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3112   APInt A = C1->getAPInt().abs();
3113   APInt B = C2->getAPInt().abs();
3114   uint32_t ABW = A.getBitWidth();
3115   uint32_t BBW = B.getBitWidth();
3116 
3117   if (ABW > BBW)
3118     B = B.zext(ABW);
3119   else if (ABW < BBW)
3120     A = A.zext(BBW);
3121 
3122   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3123 }
3124 
3125 /// Get a canonical unsigned division expression, or something simpler if
3126 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3127 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3128 /// it's not exact because the udiv may be clearing bits.
3129 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3130                                               const SCEV *RHS) {
3131   // TODO: we could try to find factors in all sorts of things, but for now we
3132   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3133   // end of this file for inspiration.
3134 
3135   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3136   if (!Mul || !Mul->hasNoUnsignedWrap())
3137     return getUDivExpr(LHS, RHS);
3138 
3139   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3140     // If the mulexpr multiplies by a constant, then that constant must be the
3141     // first element of the mulexpr.
3142     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3143       if (LHSCst == RHSCst) {
3144         SmallVector<const SCEV *, 2> Operands;
3145         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3146         return getMulExpr(Operands);
3147       }
3148 
3149       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3150       // that there's a factor provided by one of the other terms. We need to
3151       // check.
3152       APInt Factor = gcd(LHSCst, RHSCst);
3153       if (!Factor.isIntN(1)) {
3154         LHSCst =
3155             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3156         RHSCst =
3157             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3158         SmallVector<const SCEV *, 2> Operands;
3159         Operands.push_back(LHSCst);
3160         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3161         LHS = getMulExpr(Operands);
3162         RHS = RHSCst;
3163         Mul = dyn_cast<SCEVMulExpr>(LHS);
3164         if (!Mul)
3165           return getUDivExactExpr(LHS, RHS);
3166       }
3167     }
3168   }
3169 
3170   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3171     if (Mul->getOperand(i) == RHS) {
3172       SmallVector<const SCEV *, 2> Operands;
3173       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3174       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3175       return getMulExpr(Operands);
3176     }
3177   }
3178 
3179   return getUDivExpr(LHS, RHS);
3180 }
3181 
3182 /// Get an add recurrence expression for the specified loop.  Simplify the
3183 /// expression as much as possible.
3184 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3185                                            const Loop *L,
3186                                            SCEV::NoWrapFlags Flags) {
3187   SmallVector<const SCEV *, 4> Operands;
3188   Operands.push_back(Start);
3189   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3190     if (StepChrec->getLoop() == L) {
3191       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3192       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3193     }
3194 
3195   Operands.push_back(Step);
3196   return getAddRecExpr(Operands, L, Flags);
3197 }
3198 
3199 /// Get an add recurrence expression for the specified loop.  Simplify the
3200 /// expression as much as possible.
3201 const SCEV *
3202 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3203                                const Loop *L, SCEV::NoWrapFlags Flags) {
3204   if (Operands.size() == 1) return Operands[0];
3205 #ifndef NDEBUG
3206   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3207   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3208     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3209            "SCEVAddRecExpr operand types don't match!");
3210   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3211     assert(isLoopInvariant(Operands[i], L) &&
3212            "SCEVAddRecExpr operand is not loop-invariant!");
3213 #endif
3214 
3215   if (Operands.back()->isZero()) {
3216     Operands.pop_back();
3217     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3218   }
3219 
3220   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3221   // use that information to infer NUW and NSW flags. However, computing a
3222   // BE count requires calling getAddRecExpr, so we may not yet have a
3223   // meaningful BE count at this point (and if we don't, we'd be stuck
3224   // with a SCEVCouldNotCompute as the cached BE count).
3225 
3226   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3227 
3228   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3229   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3230     const Loop *NestedLoop = NestedAR->getLoop();
3231     if (L->contains(NestedLoop)
3232             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3233             : (!NestedLoop->contains(L) &&
3234                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3235       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3236                                                   NestedAR->op_end());
3237       Operands[0] = NestedAR->getStart();
3238       // AddRecs require their operands be loop-invariant with respect to their
3239       // loops. Don't perform this transformation if it would break this
3240       // requirement.
3241       bool AllInvariant = all_of(
3242           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3243 
3244       if (AllInvariant) {
3245         // Create a recurrence for the outer loop with the same step size.
3246         //
3247         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3248         // inner recurrence has the same property.
3249         SCEV::NoWrapFlags OuterFlags =
3250           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3251 
3252         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3253         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3254           return isLoopInvariant(Op, NestedLoop);
3255         });
3256 
3257         if (AllInvariant) {
3258           // Ok, both add recurrences are valid after the transformation.
3259           //
3260           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3261           // the outer recurrence has the same property.
3262           SCEV::NoWrapFlags InnerFlags =
3263             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3264           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3265         }
3266       }
3267       // Reset Operands to its original state.
3268       Operands[0] = NestedAR;
3269     }
3270   }
3271 
3272   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3273   // already have one, otherwise create a new one.
3274   FoldingSetNodeID ID;
3275   ID.AddInteger(scAddRecExpr);
3276   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3277     ID.AddPointer(Operands[i]);
3278   ID.AddPointer(L);
3279   void *IP = nullptr;
3280   SCEVAddRecExpr *S =
3281     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3282   if (!S) {
3283     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3284     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3285     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3286                                            O, Operands.size(), L);
3287     UniqueSCEVs.InsertNode(S, IP);
3288     addToLoopUseLists(S);
3289   }
3290   S->setNoWrapFlags(Flags);
3291   return S;
3292 }
3293 
3294 const SCEV *
3295 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3296                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3297   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3298   // getSCEV(Base)->getType() has the same address space as Base->getType()
3299   // because SCEV::getType() preserves the address space.
3300   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3301   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3302   // instruction to its SCEV, because the Instruction may be guarded by control
3303   // flow and the no-overflow bits may not be valid for the expression in any
3304   // context. This can be fixed similarly to how these flags are handled for
3305   // adds.
3306   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3307                                              : SCEV::FlagAnyWrap;
3308 
3309   const SCEV *TotalOffset = getZero(IntPtrTy);
3310   // The array size is unimportant. The first thing we do on CurTy is getting
3311   // its element type.
3312   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3313   for (const SCEV *IndexExpr : IndexExprs) {
3314     // Compute the (potentially symbolic) offset in bytes for this index.
3315     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3316       // For a struct, add the member offset.
3317       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3318       unsigned FieldNo = Index->getZExtValue();
3319       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3320 
3321       // Add the field offset to the running total offset.
3322       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3323 
3324       // Update CurTy to the type of the field at Index.
3325       CurTy = STy->getTypeAtIndex(Index);
3326     } else {
3327       // Update CurTy to its element type.
3328       CurTy = cast<SequentialType>(CurTy)->getElementType();
3329       // For an array, add the element offset, explicitly scaled.
3330       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3331       // Getelementptr indices are signed.
3332       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3333 
3334       // Multiply the index by the element size to compute the element offset.
3335       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3336 
3337       // Add the element offset to the running total offset.
3338       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3339     }
3340   }
3341 
3342   // Add the total offset from all the GEP indices to the base.
3343   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3344 }
3345 
3346 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3347                                          const SCEV *RHS) {
3348   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3349   return getSMaxExpr(Ops);
3350 }
3351 
3352 const SCEV *
3353 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3354   assert(!Ops.empty() && "Cannot get empty smax!");
3355   if (Ops.size() == 1) return Ops[0];
3356 #ifndef NDEBUG
3357   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3358   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3359     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3360            "SCEVSMaxExpr operand types don't match!");
3361 #endif
3362 
3363   // Sort by complexity, this groups all similar expression types together.
3364   GroupByComplexity(Ops, &LI, DT);
3365 
3366   // If there are any constants, fold them together.
3367   unsigned Idx = 0;
3368   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3369     ++Idx;
3370     assert(Idx < Ops.size());
3371     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3372       // We found two constants, fold them together!
3373       ConstantInt *Fold = ConstantInt::get(
3374           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3375       Ops[0] = getConstant(Fold);
3376       Ops.erase(Ops.begin()+1);  // Erase the folded element
3377       if (Ops.size() == 1) return Ops[0];
3378       LHSC = cast<SCEVConstant>(Ops[0]);
3379     }
3380 
3381     // If we are left with a constant minimum-int, strip it off.
3382     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3383       Ops.erase(Ops.begin());
3384       --Idx;
3385     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3386       // If we have an smax with a constant maximum-int, it will always be
3387       // maximum-int.
3388       return Ops[0];
3389     }
3390 
3391     if (Ops.size() == 1) return Ops[0];
3392   }
3393 
3394   // Find the first SMax
3395   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3396     ++Idx;
3397 
3398   // Check to see if one of the operands is an SMax. If so, expand its operands
3399   // onto our operand list, and recurse to simplify.
3400   if (Idx < Ops.size()) {
3401     bool DeletedSMax = false;
3402     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3403       Ops.erase(Ops.begin()+Idx);
3404       Ops.append(SMax->op_begin(), SMax->op_end());
3405       DeletedSMax = true;
3406     }
3407 
3408     if (DeletedSMax)
3409       return getSMaxExpr(Ops);
3410   }
3411 
3412   // Okay, check to see if the same value occurs in the operand list twice.  If
3413   // so, delete one.  Since we sorted the list, these values are required to
3414   // be adjacent.
3415   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3416     //  X smax Y smax Y  -->  X smax Y
3417     //  X smax Y         -->  X, if X is always greater than Y
3418     if (Ops[i] == Ops[i+1] ||
3419         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3420       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3421       --i; --e;
3422     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3423       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3424       --i; --e;
3425     }
3426 
3427   if (Ops.size() == 1) return Ops[0];
3428 
3429   assert(!Ops.empty() && "Reduced smax down to nothing!");
3430 
3431   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3432   // already have one, otherwise create a new one.
3433   FoldingSetNodeID ID;
3434   ID.AddInteger(scSMaxExpr);
3435   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3436     ID.AddPointer(Ops[i]);
3437   void *IP = nullptr;
3438   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3439   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3440   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3441   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3442                                              O, Ops.size());
3443   UniqueSCEVs.InsertNode(S, IP);
3444   addToLoopUseLists(S);
3445   return S;
3446 }
3447 
3448 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3449                                          const SCEV *RHS) {
3450   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3451   return getUMaxExpr(Ops);
3452 }
3453 
3454 const SCEV *
3455 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3456   assert(!Ops.empty() && "Cannot get empty umax!");
3457   if (Ops.size() == 1) return Ops[0];
3458 #ifndef NDEBUG
3459   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3460   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3461     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3462            "SCEVUMaxExpr operand types don't match!");
3463 #endif
3464 
3465   // Sort by complexity, this groups all similar expression types together.
3466   GroupByComplexity(Ops, &LI, DT);
3467 
3468   // If there are any constants, fold them together.
3469   unsigned Idx = 0;
3470   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3471     ++Idx;
3472     assert(Idx < Ops.size());
3473     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3474       // We found two constants, fold them together!
3475       ConstantInt *Fold = ConstantInt::get(
3476           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3477       Ops[0] = getConstant(Fold);
3478       Ops.erase(Ops.begin()+1);  // Erase the folded element
3479       if (Ops.size() == 1) return Ops[0];
3480       LHSC = cast<SCEVConstant>(Ops[0]);
3481     }
3482 
3483     // If we are left with a constant minimum-int, strip it off.
3484     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3485       Ops.erase(Ops.begin());
3486       --Idx;
3487     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3488       // If we have an umax with a constant maximum-int, it will always be
3489       // maximum-int.
3490       return Ops[0];
3491     }
3492 
3493     if (Ops.size() == 1) return Ops[0];
3494   }
3495 
3496   // Find the first UMax
3497   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3498     ++Idx;
3499 
3500   // Check to see if one of the operands is a UMax. If so, expand its operands
3501   // onto our operand list, and recurse to simplify.
3502   if (Idx < Ops.size()) {
3503     bool DeletedUMax = false;
3504     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3505       Ops.erase(Ops.begin()+Idx);
3506       Ops.append(UMax->op_begin(), UMax->op_end());
3507       DeletedUMax = true;
3508     }
3509 
3510     if (DeletedUMax)
3511       return getUMaxExpr(Ops);
3512   }
3513 
3514   // Okay, check to see if the same value occurs in the operand list twice.  If
3515   // so, delete one.  Since we sorted the list, these values are required to
3516   // be adjacent.
3517   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3518     //  X umax Y umax Y  -->  X umax Y
3519     //  X umax Y         -->  X, if X is always greater than Y
3520     if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
3521                                     ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
3522       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3523       --i; --e;
3524     } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
3525                                                Ops[i + 1])) {
3526       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3527       --i; --e;
3528     }
3529 
3530   if (Ops.size() == 1) return Ops[0];
3531 
3532   assert(!Ops.empty() && "Reduced umax down to nothing!");
3533 
3534   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3535   // already have one, otherwise create a new one.
3536   FoldingSetNodeID ID;
3537   ID.AddInteger(scUMaxExpr);
3538   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3539     ID.AddPointer(Ops[i]);
3540   void *IP = nullptr;
3541   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3542   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3543   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3544   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3545                                              O, Ops.size());
3546   UniqueSCEVs.InsertNode(S, IP);
3547   addToLoopUseLists(S);
3548   return S;
3549 }
3550 
3551 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3552                                          const SCEV *RHS) {
3553   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3554   return getSMinExpr(Ops);
3555 }
3556 
3557 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3558   // ~smax(~x, ~y, ~z) == smin(x, y, z).
3559   SmallVector<const SCEV *, 2> NotOps;
3560   for (auto *S : Ops)
3561     NotOps.push_back(getNotSCEV(S));
3562   return getNotSCEV(getSMaxExpr(NotOps));
3563 }
3564 
3565 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3566                                          const SCEV *RHS) {
3567   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3568   return getUMinExpr(Ops);
3569 }
3570 
3571 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3572   assert(!Ops.empty() && "At least one operand must be!");
3573   // Trivial case.
3574   if (Ops.size() == 1)
3575     return Ops[0];
3576 
3577   // ~umax(~x, ~y, ~z) == umin(x, y, z).
3578   SmallVector<const SCEV *, 2> NotOps;
3579   for (auto *S : Ops)
3580     NotOps.push_back(getNotSCEV(S));
3581   return getNotSCEV(getUMaxExpr(NotOps));
3582 }
3583 
3584 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3585   // We can bypass creating a target-independent
3586   // constant expression and then folding it back into a ConstantInt.
3587   // This is just a compile-time optimization.
3588   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3589 }
3590 
3591 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3592                                              StructType *STy,
3593                                              unsigned FieldNo) {
3594   // We can bypass creating a target-independent
3595   // constant expression and then folding it back into a ConstantInt.
3596   // This is just a compile-time optimization.
3597   return getConstant(
3598       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3599 }
3600 
3601 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3602   // Don't attempt to do anything other than create a SCEVUnknown object
3603   // here.  createSCEV only calls getUnknown after checking for all other
3604   // interesting possibilities, and any other code that calls getUnknown
3605   // is doing so in order to hide a value from SCEV canonicalization.
3606 
3607   FoldingSetNodeID ID;
3608   ID.AddInteger(scUnknown);
3609   ID.AddPointer(V);
3610   void *IP = nullptr;
3611   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3612     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3613            "Stale SCEVUnknown in uniquing map!");
3614     return S;
3615   }
3616   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3617                                             FirstUnknown);
3618   FirstUnknown = cast<SCEVUnknown>(S);
3619   UniqueSCEVs.InsertNode(S, IP);
3620   return S;
3621 }
3622 
3623 //===----------------------------------------------------------------------===//
3624 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3625 //
3626 
3627 /// Test if values of the given type are analyzable within the SCEV
3628 /// framework. This primarily includes integer types, and it can optionally
3629 /// include pointer types if the ScalarEvolution class has access to
3630 /// target-specific information.
3631 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3632   // Integers and pointers are always SCEVable.
3633   return Ty->isIntegerTy() || Ty->isPointerTy();
3634 }
3635 
3636 /// Return the size in bits of the specified type, for which isSCEVable must
3637 /// return true.
3638 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3639   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3640   if (Ty->isPointerTy())
3641     return getDataLayout().getIndexTypeSizeInBits(Ty);
3642   return getDataLayout().getTypeSizeInBits(Ty);
3643 }
3644 
3645 /// Return a type with the same bitwidth as the given type and which represents
3646 /// how SCEV will treat the given type, for which isSCEVable must return
3647 /// true. For pointer types, this is the pointer-sized integer type.
3648 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3649   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3650 
3651   if (Ty->isIntegerTy())
3652     return Ty;
3653 
3654   // The only other support type is pointer.
3655   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3656   return getDataLayout().getIntPtrType(Ty);
3657 }
3658 
3659 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3660   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3661 }
3662 
3663 const SCEV *ScalarEvolution::getCouldNotCompute() {
3664   return CouldNotCompute.get();
3665 }
3666 
3667 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3668   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3669     auto *SU = dyn_cast<SCEVUnknown>(S);
3670     return SU && SU->getValue() == nullptr;
3671   });
3672 
3673   return !ContainsNulls;
3674 }
3675 
3676 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3677   HasRecMapType::iterator I = HasRecMap.find(S);
3678   if (I != HasRecMap.end())
3679     return I->second;
3680 
3681   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3682   HasRecMap.insert({S, FoundAddRec});
3683   return FoundAddRec;
3684 }
3685 
3686 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3687 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3688 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3689 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3690   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3691   if (!Add)
3692     return {S, nullptr};
3693 
3694   if (Add->getNumOperands() != 2)
3695     return {S, nullptr};
3696 
3697   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3698   if (!ConstOp)
3699     return {S, nullptr};
3700 
3701   return {Add->getOperand(1), ConstOp->getValue()};
3702 }
3703 
3704 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3705 /// by the value and offset from any ValueOffsetPair in the set.
3706 SetVector<ScalarEvolution::ValueOffsetPair> *
3707 ScalarEvolution::getSCEVValues(const SCEV *S) {
3708   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3709   if (SI == ExprValueMap.end())
3710     return nullptr;
3711 #ifndef NDEBUG
3712   if (VerifySCEVMap) {
3713     // Check there is no dangling Value in the set returned.
3714     for (const auto &VE : SI->second)
3715       assert(ValueExprMap.count(VE.first));
3716   }
3717 #endif
3718   return &SI->second;
3719 }
3720 
3721 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3722 /// cannot be used separately. eraseValueFromMap should be used to remove
3723 /// V from ValueExprMap and ExprValueMap at the same time.
3724 void ScalarEvolution::eraseValueFromMap(Value *V) {
3725   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3726   if (I != ValueExprMap.end()) {
3727     const SCEV *S = I->second;
3728     // Remove {V, 0} from the set of ExprValueMap[S]
3729     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3730       SV->remove({V, nullptr});
3731 
3732     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3733     const SCEV *Stripped;
3734     ConstantInt *Offset;
3735     std::tie(Stripped, Offset) = splitAddExpr(S);
3736     if (Offset != nullptr) {
3737       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3738         SV->remove({V, Offset});
3739     }
3740     ValueExprMap.erase(V);
3741   }
3742 }
3743 
3744 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3745 /// TODO: In reality it is better to check the poison recursevely
3746 /// but this is better than nothing.
3747 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3748   if (auto *I = dyn_cast<Instruction>(V)) {
3749     if (isa<OverflowingBinaryOperator>(I)) {
3750       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3751         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3752           return true;
3753         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3754           return true;
3755       }
3756     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3757       return true;
3758   }
3759   return false;
3760 }
3761 
3762 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3763 /// create a new one.
3764 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3765   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3766 
3767   const SCEV *S = getExistingSCEV(V);
3768   if (S == nullptr) {
3769     S = createSCEV(V);
3770     // During PHI resolution, it is possible to create two SCEVs for the same
3771     // V, so it is needed to double check whether V->S is inserted into
3772     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3773     std::pair<ValueExprMapType::iterator, bool> Pair =
3774         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3775     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3776       ExprValueMap[S].insert({V, nullptr});
3777 
3778       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3779       // ExprValueMap.
3780       const SCEV *Stripped = S;
3781       ConstantInt *Offset = nullptr;
3782       std::tie(Stripped, Offset) = splitAddExpr(S);
3783       // If stripped is SCEVUnknown, don't bother to save
3784       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3785       // increase the complexity of the expansion code.
3786       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3787       // because it may generate add/sub instead of GEP in SCEV expansion.
3788       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3789           !isa<GetElementPtrInst>(V))
3790         ExprValueMap[Stripped].insert({V, Offset});
3791     }
3792   }
3793   return S;
3794 }
3795 
3796 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3797   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3798 
3799   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3800   if (I != ValueExprMap.end()) {
3801     const SCEV *S = I->second;
3802     if (checkValidity(S))
3803       return S;
3804     eraseValueFromMap(V);
3805     forgetMemoizedResults(S);
3806   }
3807   return nullptr;
3808 }
3809 
3810 /// Return a SCEV corresponding to -V = -1*V
3811 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3812                                              SCEV::NoWrapFlags Flags) {
3813   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3814     return getConstant(
3815                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3816 
3817   Type *Ty = V->getType();
3818   Ty = getEffectiveSCEVType(Ty);
3819   return getMulExpr(
3820       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3821 }
3822 
3823 /// Return a SCEV corresponding to ~V = -1-V
3824 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3825   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3826     return getConstant(
3827                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3828 
3829   Type *Ty = V->getType();
3830   Ty = getEffectiveSCEVType(Ty);
3831   const SCEV *AllOnes =
3832                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3833   return getMinusSCEV(AllOnes, V);
3834 }
3835 
3836 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3837                                           SCEV::NoWrapFlags Flags,
3838                                           unsigned Depth) {
3839   // Fast path: X - X --> 0.
3840   if (LHS == RHS)
3841     return getZero(LHS->getType());
3842 
3843   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3844   // makes it so that we cannot make much use of NUW.
3845   auto AddFlags = SCEV::FlagAnyWrap;
3846   const bool RHSIsNotMinSigned =
3847       !getSignedRangeMin(RHS).isMinSignedValue();
3848   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3849     // Let M be the minimum representable signed value. Then (-1)*RHS
3850     // signed-wraps if and only if RHS is M. That can happen even for
3851     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3852     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3853     // (-1)*RHS, we need to prove that RHS != M.
3854     //
3855     // If LHS is non-negative and we know that LHS - RHS does not
3856     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3857     // either by proving that RHS > M or that LHS >= 0.
3858     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3859       AddFlags = SCEV::FlagNSW;
3860     }
3861   }
3862 
3863   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3864   // RHS is NSW and LHS >= 0.
3865   //
3866   // The difficulty here is that the NSW flag may have been proven
3867   // relative to a loop that is to be found in a recurrence in LHS and
3868   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3869   // larger scope than intended.
3870   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3871 
3872   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3873 }
3874 
3875 const SCEV *
3876 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3877   Type *SrcTy = V->getType();
3878   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3879          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3880          "Cannot truncate or zero extend with non-integer arguments!");
3881   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3882     return V;  // No conversion
3883   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3884     return getTruncateExpr(V, Ty);
3885   return getZeroExtendExpr(V, Ty);
3886 }
3887 
3888 const SCEV *
3889 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3890                                          Type *Ty) {
3891   Type *SrcTy = V->getType();
3892   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3893          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3894          "Cannot truncate or zero extend with non-integer arguments!");
3895   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3896     return V;  // No conversion
3897   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3898     return getTruncateExpr(V, Ty);
3899   return getSignExtendExpr(V, Ty);
3900 }
3901 
3902 const SCEV *
3903 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3904   Type *SrcTy = V->getType();
3905   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3906          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3907          "Cannot noop or zero extend with non-integer arguments!");
3908   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3909          "getNoopOrZeroExtend cannot truncate!");
3910   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3911     return V;  // No conversion
3912   return getZeroExtendExpr(V, Ty);
3913 }
3914 
3915 const SCEV *
3916 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3917   Type *SrcTy = V->getType();
3918   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3919          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3920          "Cannot noop or sign extend with non-integer arguments!");
3921   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3922          "getNoopOrSignExtend cannot truncate!");
3923   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3924     return V;  // No conversion
3925   return getSignExtendExpr(V, Ty);
3926 }
3927 
3928 const SCEV *
3929 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3930   Type *SrcTy = V->getType();
3931   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3932          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3933          "Cannot noop or any extend with non-integer arguments!");
3934   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3935          "getNoopOrAnyExtend cannot truncate!");
3936   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3937     return V;  // No conversion
3938   return getAnyExtendExpr(V, Ty);
3939 }
3940 
3941 const SCEV *
3942 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3943   Type *SrcTy = V->getType();
3944   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3945          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3946          "Cannot truncate or noop with non-integer arguments!");
3947   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3948          "getTruncateOrNoop cannot extend!");
3949   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3950     return V;  // No conversion
3951   return getTruncateExpr(V, Ty);
3952 }
3953 
3954 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3955                                                         const SCEV *RHS) {
3956   const SCEV *PromotedLHS = LHS;
3957   const SCEV *PromotedRHS = RHS;
3958 
3959   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3960     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3961   else
3962     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3963 
3964   return getUMaxExpr(PromotedLHS, PromotedRHS);
3965 }
3966 
3967 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3968                                                         const SCEV *RHS) {
3969   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3970   return getUMinFromMismatchedTypes(Ops);
3971 }
3972 
3973 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
3974     SmallVectorImpl<const SCEV *> &Ops) {
3975   assert(!Ops.empty() && "At least one operand must be!");
3976   // Trivial case.
3977   if (Ops.size() == 1)
3978     return Ops[0];
3979 
3980   // Find the max type first.
3981   Type *MaxType = nullptr;
3982   for (auto *S : Ops)
3983     if (MaxType)
3984       MaxType = getWiderType(MaxType, S->getType());
3985     else
3986       MaxType = S->getType();
3987 
3988   // Extend all ops to max type.
3989   SmallVector<const SCEV *, 2> PromotedOps;
3990   for (auto *S : Ops)
3991     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
3992 
3993   // Generate umin.
3994   return getUMinExpr(PromotedOps);
3995 }
3996 
3997 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3998   // A pointer operand may evaluate to a nonpointer expression, such as null.
3999   if (!V->getType()->isPointerTy())
4000     return V;
4001 
4002   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4003     return getPointerBase(Cast->getOperand());
4004   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4005     const SCEV *PtrOp = nullptr;
4006     for (const SCEV *NAryOp : NAry->operands()) {
4007       if (NAryOp->getType()->isPointerTy()) {
4008         // Cannot find the base of an expression with multiple pointer operands.
4009         if (PtrOp)
4010           return V;
4011         PtrOp = NAryOp;
4012       }
4013     }
4014     if (!PtrOp)
4015       return V;
4016     return getPointerBase(PtrOp);
4017   }
4018   return V;
4019 }
4020 
4021 /// Push users of the given Instruction onto the given Worklist.
4022 static void
4023 PushDefUseChildren(Instruction *I,
4024                    SmallVectorImpl<Instruction *> &Worklist) {
4025   // Push the def-use children onto the Worklist stack.
4026   for (User *U : I->users())
4027     Worklist.push_back(cast<Instruction>(U));
4028 }
4029 
4030 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4031   SmallVector<Instruction *, 16> Worklist;
4032   PushDefUseChildren(PN, Worklist);
4033 
4034   SmallPtrSet<Instruction *, 8> Visited;
4035   Visited.insert(PN);
4036   while (!Worklist.empty()) {
4037     Instruction *I = Worklist.pop_back_val();
4038     if (!Visited.insert(I).second)
4039       continue;
4040 
4041     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4042     if (It != ValueExprMap.end()) {
4043       const SCEV *Old = It->second;
4044 
4045       // Short-circuit the def-use traversal if the symbolic name
4046       // ceases to appear in expressions.
4047       if (Old != SymName && !hasOperand(Old, SymName))
4048         continue;
4049 
4050       // SCEVUnknown for a PHI either means that it has an unrecognized
4051       // structure, it's a PHI that's in the progress of being computed
4052       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4053       // additional loop trip count information isn't going to change anything.
4054       // In the second case, createNodeForPHI will perform the necessary
4055       // updates on its own when it gets to that point. In the third, we do
4056       // want to forget the SCEVUnknown.
4057       if (!isa<PHINode>(I) ||
4058           !isa<SCEVUnknown>(Old) ||
4059           (I != PN && Old == SymName)) {
4060         eraseValueFromMap(It->first);
4061         forgetMemoizedResults(Old);
4062       }
4063     }
4064 
4065     PushDefUseChildren(I, Worklist);
4066   }
4067 }
4068 
4069 namespace {
4070 
4071 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4072 /// expression in case its Loop is L. If it is not L then
4073 /// if IgnoreOtherLoops is true then use AddRec itself
4074 /// otherwise rewrite cannot be done.
4075 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4076 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4077 public:
4078   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4079                              bool IgnoreOtherLoops = true) {
4080     SCEVInitRewriter Rewriter(L, SE);
4081     const SCEV *Result = Rewriter.visit(S);
4082     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4083       return SE.getCouldNotCompute();
4084     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4085                ? SE.getCouldNotCompute()
4086                : Result;
4087   }
4088 
4089   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4090     if (!SE.isLoopInvariant(Expr, L))
4091       SeenLoopVariantSCEVUnknown = true;
4092     return Expr;
4093   }
4094 
4095   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4096     // Only re-write AddRecExprs for this loop.
4097     if (Expr->getLoop() == L)
4098       return Expr->getStart();
4099     SeenOtherLoops = true;
4100     return Expr;
4101   }
4102 
4103   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4104 
4105   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4106 
4107 private:
4108   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4109       : SCEVRewriteVisitor(SE), L(L) {}
4110 
4111   const Loop *L;
4112   bool SeenLoopVariantSCEVUnknown = false;
4113   bool SeenOtherLoops = false;
4114 };
4115 
4116 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4117 /// increment expression in case its Loop is L. If it is not L then
4118 /// use AddRec itself.
4119 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4120 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4121 public:
4122   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4123     SCEVPostIncRewriter Rewriter(L, SE);
4124     const SCEV *Result = Rewriter.visit(S);
4125     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4126         ? SE.getCouldNotCompute()
4127         : Result;
4128   }
4129 
4130   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4131     if (!SE.isLoopInvariant(Expr, L))
4132       SeenLoopVariantSCEVUnknown = true;
4133     return Expr;
4134   }
4135 
4136   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4137     // Only re-write AddRecExprs for this loop.
4138     if (Expr->getLoop() == L)
4139       return Expr->getPostIncExpr(SE);
4140     SeenOtherLoops = true;
4141     return Expr;
4142   }
4143 
4144   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4145 
4146   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4147 
4148 private:
4149   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4150       : SCEVRewriteVisitor(SE), L(L) {}
4151 
4152   const Loop *L;
4153   bool SeenLoopVariantSCEVUnknown = false;
4154   bool SeenOtherLoops = false;
4155 };
4156 
4157 /// This class evaluates the compare condition by matching it against the
4158 /// condition of loop latch. If there is a match we assume a true value
4159 /// for the condition while building SCEV nodes.
4160 class SCEVBackedgeConditionFolder
4161     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4162 public:
4163   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4164                              ScalarEvolution &SE) {
4165     bool IsPosBECond = false;
4166     Value *BECond = nullptr;
4167     if (BasicBlock *Latch = L->getLoopLatch()) {
4168       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4169       if (BI && BI->isConditional()) {
4170         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4171                "Both outgoing branches should not target same header!");
4172         BECond = BI->getCondition();
4173         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4174       } else {
4175         return S;
4176       }
4177     }
4178     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4179     return Rewriter.visit(S);
4180   }
4181 
4182   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4183     const SCEV *Result = Expr;
4184     bool InvariantF = SE.isLoopInvariant(Expr, L);
4185 
4186     if (!InvariantF) {
4187       Instruction *I = cast<Instruction>(Expr->getValue());
4188       switch (I->getOpcode()) {
4189       case Instruction::Select: {
4190         SelectInst *SI = cast<SelectInst>(I);
4191         Optional<const SCEV *> Res =
4192             compareWithBackedgeCondition(SI->getCondition());
4193         if (Res.hasValue()) {
4194           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4195           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4196         }
4197         break;
4198       }
4199       default: {
4200         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4201         if (Res.hasValue())
4202           Result = Res.getValue();
4203         break;
4204       }
4205       }
4206     }
4207     return Result;
4208   }
4209 
4210 private:
4211   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4212                                        bool IsPosBECond, ScalarEvolution &SE)
4213       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4214         IsPositiveBECond(IsPosBECond) {}
4215 
4216   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4217 
4218   const Loop *L;
4219   /// Loop back condition.
4220   Value *BackedgeCond = nullptr;
4221   /// Set to true if loop back is on positive branch condition.
4222   bool IsPositiveBECond;
4223 };
4224 
4225 Optional<const SCEV *>
4226 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4227 
4228   // If value matches the backedge condition for loop latch,
4229   // then return a constant evolution node based on loopback
4230   // branch taken.
4231   if (BackedgeCond == IC)
4232     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4233                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4234   return None;
4235 }
4236 
4237 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4238 public:
4239   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4240                              ScalarEvolution &SE) {
4241     SCEVShiftRewriter Rewriter(L, SE);
4242     const SCEV *Result = Rewriter.visit(S);
4243     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4244   }
4245 
4246   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4247     // Only allow AddRecExprs for this loop.
4248     if (!SE.isLoopInvariant(Expr, L))
4249       Valid = false;
4250     return Expr;
4251   }
4252 
4253   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4254     if (Expr->getLoop() == L && Expr->isAffine())
4255       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4256     Valid = false;
4257     return Expr;
4258   }
4259 
4260   bool isValid() { return Valid; }
4261 
4262 private:
4263   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4264       : SCEVRewriteVisitor(SE), L(L) {}
4265 
4266   const Loop *L;
4267   bool Valid = true;
4268 };
4269 
4270 } // end anonymous namespace
4271 
4272 SCEV::NoWrapFlags
4273 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4274   if (!AR->isAffine())
4275     return SCEV::FlagAnyWrap;
4276 
4277   using OBO = OverflowingBinaryOperator;
4278 
4279   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4280 
4281   if (!AR->hasNoSignedWrap()) {
4282     ConstantRange AddRecRange = getSignedRange(AR);
4283     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4284 
4285     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4286         Instruction::Add, IncRange, OBO::NoSignedWrap);
4287     if (NSWRegion.contains(AddRecRange))
4288       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4289   }
4290 
4291   if (!AR->hasNoUnsignedWrap()) {
4292     ConstantRange AddRecRange = getUnsignedRange(AR);
4293     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4294 
4295     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4296         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4297     if (NUWRegion.contains(AddRecRange))
4298       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4299   }
4300 
4301   return Result;
4302 }
4303 
4304 namespace {
4305 
4306 /// Represents an abstract binary operation.  This may exist as a
4307 /// normal instruction or constant expression, or may have been
4308 /// derived from an expression tree.
4309 struct BinaryOp {
4310   unsigned Opcode;
4311   Value *LHS;
4312   Value *RHS;
4313   bool IsNSW = false;
4314   bool IsNUW = false;
4315 
4316   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4317   /// constant expression.
4318   Operator *Op = nullptr;
4319 
4320   explicit BinaryOp(Operator *Op)
4321       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4322         Op(Op) {
4323     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4324       IsNSW = OBO->hasNoSignedWrap();
4325       IsNUW = OBO->hasNoUnsignedWrap();
4326     }
4327   }
4328 
4329   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4330                     bool IsNUW = false)
4331       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4332 };
4333 
4334 } // end anonymous namespace
4335 
4336 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4337 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4338   auto *Op = dyn_cast<Operator>(V);
4339   if (!Op)
4340     return None;
4341 
4342   // Implementation detail: all the cleverness here should happen without
4343   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4344   // SCEV expressions when possible, and we should not break that.
4345 
4346   switch (Op->getOpcode()) {
4347   case Instruction::Add:
4348   case Instruction::Sub:
4349   case Instruction::Mul:
4350   case Instruction::UDiv:
4351   case Instruction::URem:
4352   case Instruction::And:
4353   case Instruction::Or:
4354   case Instruction::AShr:
4355   case Instruction::Shl:
4356     return BinaryOp(Op);
4357 
4358   case Instruction::Xor:
4359     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4360       // If the RHS of the xor is a signmask, then this is just an add.
4361       // Instcombine turns add of signmask into xor as a strength reduction step.
4362       if (RHSC->getValue().isSignMask())
4363         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4364     return BinaryOp(Op);
4365 
4366   case Instruction::LShr:
4367     // Turn logical shift right of a constant into a unsigned divide.
4368     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4369       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4370 
4371       // If the shift count is not less than the bitwidth, the result of
4372       // the shift is undefined. Don't try to analyze it, because the
4373       // resolution chosen here may differ from the resolution chosen in
4374       // other parts of the compiler.
4375       if (SA->getValue().ult(BitWidth)) {
4376         Constant *X =
4377             ConstantInt::get(SA->getContext(),
4378                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4379         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4380       }
4381     }
4382     return BinaryOp(Op);
4383 
4384   case Instruction::ExtractValue: {
4385     auto *EVI = cast<ExtractValueInst>(Op);
4386     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4387       break;
4388 
4389     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4390     if (!CI)
4391       break;
4392 
4393     if (auto *F = CI->getCalledFunction())
4394       switch (F->getIntrinsicID()) {
4395       case Intrinsic::sadd_with_overflow:
4396       case Intrinsic::uadd_with_overflow:
4397         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4398           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4399                           CI->getArgOperand(1));
4400 
4401         // Now that we know that all uses of the arithmetic-result component of
4402         // CI are guarded by the overflow check, we can go ahead and pretend
4403         // that the arithmetic is non-overflowing.
4404         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4405           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4406                           CI->getArgOperand(1), /* IsNSW = */ true,
4407                           /* IsNUW = */ false);
4408         else
4409           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4410                           CI->getArgOperand(1), /* IsNSW = */ false,
4411                           /* IsNUW*/ true);
4412       case Intrinsic::ssub_with_overflow:
4413       case Intrinsic::usub_with_overflow:
4414         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4415           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4416                           CI->getArgOperand(1));
4417 
4418         // The same reasoning as sadd/uadd above.
4419         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4420           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4421                           CI->getArgOperand(1), /* IsNSW = */ true,
4422                           /* IsNUW = */ false);
4423         else
4424           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4425                           CI->getArgOperand(1), /* IsNSW = */ false,
4426                           /* IsNUW = */ true);
4427       case Intrinsic::smul_with_overflow:
4428       case Intrinsic::umul_with_overflow:
4429         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4430                         CI->getArgOperand(1));
4431       default:
4432         break;
4433       }
4434     break;
4435   }
4436 
4437   default:
4438     break;
4439   }
4440 
4441   return None;
4442 }
4443 
4444 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4445 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4446 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4447 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4448 /// follows one of the following patterns:
4449 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4450 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4451 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4452 /// we return the type of the truncation operation, and indicate whether the
4453 /// truncated type should be treated as signed/unsigned by setting
4454 /// \p Signed to true/false, respectively.
4455 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4456                                bool &Signed, ScalarEvolution &SE) {
4457   // The case where Op == SymbolicPHI (that is, with no type conversions on
4458   // the way) is handled by the regular add recurrence creating logic and
4459   // would have already been triggered in createAddRecForPHI. Reaching it here
4460   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4461   // because one of the other operands of the SCEVAddExpr updating this PHI is
4462   // not invariant).
4463   //
4464   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4465   // this case predicates that allow us to prove that Op == SymbolicPHI will
4466   // be added.
4467   if (Op == SymbolicPHI)
4468     return nullptr;
4469 
4470   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4471   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4472   if (SourceBits != NewBits)
4473     return nullptr;
4474 
4475   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4476   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4477   if (!SExt && !ZExt)
4478     return nullptr;
4479   const SCEVTruncateExpr *Trunc =
4480       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4481            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4482   if (!Trunc)
4483     return nullptr;
4484   const SCEV *X = Trunc->getOperand();
4485   if (X != SymbolicPHI)
4486     return nullptr;
4487   Signed = SExt != nullptr;
4488   return Trunc->getType();
4489 }
4490 
4491 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4492   if (!PN->getType()->isIntegerTy())
4493     return nullptr;
4494   const Loop *L = LI.getLoopFor(PN->getParent());
4495   if (!L || L->getHeader() != PN->getParent())
4496     return nullptr;
4497   return L;
4498 }
4499 
4500 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4501 // computation that updates the phi follows the following pattern:
4502 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4503 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4504 // If so, try to see if it can be rewritten as an AddRecExpr under some
4505 // Predicates. If successful, return them as a pair. Also cache the results
4506 // of the analysis.
4507 //
4508 // Example usage scenario:
4509 //    Say the Rewriter is called for the following SCEV:
4510 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4511 //    where:
4512 //         %X = phi i64 (%Start, %BEValue)
4513 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4514 //    and call this function with %SymbolicPHI = %X.
4515 //
4516 //    The analysis will find that the value coming around the backedge has
4517 //    the following SCEV:
4518 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4519 //    Upon concluding that this matches the desired pattern, the function
4520 //    will return the pair {NewAddRec, SmallPredsVec} where:
4521 //         NewAddRec = {%Start,+,%Step}
4522 //         SmallPredsVec = {P1, P2, P3} as follows:
4523 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4524 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4525 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4526 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4527 //    under the predicates {P1,P2,P3}.
4528 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4529 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4530 //
4531 // TODO's:
4532 //
4533 // 1) Extend the Induction descriptor to also support inductions that involve
4534 //    casts: When needed (namely, when we are called in the context of the
4535 //    vectorizer induction analysis), a Set of cast instructions will be
4536 //    populated by this method, and provided back to isInductionPHI. This is
4537 //    needed to allow the vectorizer to properly record them to be ignored by
4538 //    the cost model and to avoid vectorizing them (otherwise these casts,
4539 //    which are redundant under the runtime overflow checks, will be
4540 //    vectorized, which can be costly).
4541 //
4542 // 2) Support additional induction/PHISCEV patterns: We also want to support
4543 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4544 //    after the induction update operation (the induction increment):
4545 //
4546 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4547 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4548 //
4549 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4550 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4551 //
4552 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4553 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4554 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4555   SmallVector<const SCEVPredicate *, 3> Predicates;
4556 
4557   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4558   // return an AddRec expression under some predicate.
4559 
4560   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4561   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4562   assert(L && "Expecting an integer loop header phi");
4563 
4564   // The loop may have multiple entrances or multiple exits; we can analyze
4565   // this phi as an addrec if it has a unique entry value and a unique
4566   // backedge value.
4567   Value *BEValueV = nullptr, *StartValueV = nullptr;
4568   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4569     Value *V = PN->getIncomingValue(i);
4570     if (L->contains(PN->getIncomingBlock(i))) {
4571       if (!BEValueV) {
4572         BEValueV = V;
4573       } else if (BEValueV != V) {
4574         BEValueV = nullptr;
4575         break;
4576       }
4577     } else if (!StartValueV) {
4578       StartValueV = V;
4579     } else if (StartValueV != V) {
4580       StartValueV = nullptr;
4581       break;
4582     }
4583   }
4584   if (!BEValueV || !StartValueV)
4585     return None;
4586 
4587   const SCEV *BEValue = getSCEV(BEValueV);
4588 
4589   // If the value coming around the backedge is an add with the symbolic
4590   // value we just inserted, possibly with casts that we can ignore under
4591   // an appropriate runtime guard, then we found a simple induction variable!
4592   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4593   if (!Add)
4594     return None;
4595 
4596   // If there is a single occurrence of the symbolic value, possibly
4597   // casted, replace it with a recurrence.
4598   unsigned FoundIndex = Add->getNumOperands();
4599   Type *TruncTy = nullptr;
4600   bool Signed;
4601   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4602     if ((TruncTy =
4603              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4604       if (FoundIndex == e) {
4605         FoundIndex = i;
4606         break;
4607       }
4608 
4609   if (FoundIndex == Add->getNumOperands())
4610     return None;
4611 
4612   // Create an add with everything but the specified operand.
4613   SmallVector<const SCEV *, 8> Ops;
4614   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4615     if (i != FoundIndex)
4616       Ops.push_back(Add->getOperand(i));
4617   const SCEV *Accum = getAddExpr(Ops);
4618 
4619   // The runtime checks will not be valid if the step amount is
4620   // varying inside the loop.
4621   if (!isLoopInvariant(Accum, L))
4622     return None;
4623 
4624   // *** Part2: Create the predicates
4625 
4626   // Analysis was successful: we have a phi-with-cast pattern for which we
4627   // can return an AddRec expression under the following predicates:
4628   //
4629   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4630   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4631   // P2: An Equal predicate that guarantees that
4632   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4633   // P3: An Equal predicate that guarantees that
4634   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4635   //
4636   // As we next prove, the above predicates guarantee that:
4637   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4638   //
4639   //
4640   // More formally, we want to prove that:
4641   //     Expr(i+1) = Start + (i+1) * Accum
4642   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4643   //
4644   // Given that:
4645   // 1) Expr(0) = Start
4646   // 2) Expr(1) = Start + Accum
4647   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4648   // 3) Induction hypothesis (step i):
4649   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4650   //
4651   // Proof:
4652   //  Expr(i+1) =
4653   //   = Start + (i+1)*Accum
4654   //   = (Start + i*Accum) + Accum
4655   //   = Expr(i) + Accum
4656   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4657   //                                                             :: from step i
4658   //
4659   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4660   //
4661   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4662   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4663   //     + Accum                                                     :: from P3
4664   //
4665   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4666   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4667   //
4668   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4669   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4670   //
4671   // By induction, the same applies to all iterations 1<=i<n:
4672   //
4673 
4674   // Create a truncated addrec for which we will add a no overflow check (P1).
4675   const SCEV *StartVal = getSCEV(StartValueV);
4676   const SCEV *PHISCEV =
4677       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4678                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4679 
4680   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4681   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4682   // will be constant.
4683   //
4684   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4685   // add P1.
4686   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4687     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4688         Signed ? SCEVWrapPredicate::IncrementNSSW
4689                : SCEVWrapPredicate::IncrementNUSW;
4690     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4691     Predicates.push_back(AddRecPred);
4692   }
4693 
4694   // Create the Equal Predicates P2,P3:
4695 
4696   // It is possible that the predicates P2 and/or P3 are computable at
4697   // compile time due to StartVal and/or Accum being constants.
4698   // If either one is, then we can check that now and escape if either P2
4699   // or P3 is false.
4700 
4701   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4702   // for each of StartVal and Accum
4703   auto getExtendedExpr = [&](const SCEV *Expr,
4704                              bool CreateSignExtend) -> const SCEV * {
4705     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4706     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4707     const SCEV *ExtendedExpr =
4708         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4709                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4710     return ExtendedExpr;
4711   };
4712 
4713   // Given:
4714   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4715   //               = getExtendedExpr(Expr)
4716   // Determine whether the predicate P: Expr == ExtendedExpr
4717   // is known to be false at compile time
4718   auto PredIsKnownFalse = [&](const SCEV *Expr,
4719                               const SCEV *ExtendedExpr) -> bool {
4720     return Expr != ExtendedExpr &&
4721            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4722   };
4723 
4724   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4725   if (PredIsKnownFalse(StartVal, StartExtended)) {
4726     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4727     return None;
4728   }
4729 
4730   // The Step is always Signed (because the overflow checks are either
4731   // NSSW or NUSW)
4732   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4733   if (PredIsKnownFalse(Accum, AccumExtended)) {
4734     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4735     return None;
4736   }
4737 
4738   auto AppendPredicate = [&](const SCEV *Expr,
4739                              const SCEV *ExtendedExpr) -> void {
4740     if (Expr != ExtendedExpr &&
4741         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4742       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4743       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4744       Predicates.push_back(Pred);
4745     }
4746   };
4747 
4748   AppendPredicate(StartVal, StartExtended);
4749   AppendPredicate(Accum, AccumExtended);
4750 
4751   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4752   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4753   // into NewAR if it will also add the runtime overflow checks specified in
4754   // Predicates.
4755   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4756 
4757   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4758       std::make_pair(NewAR, Predicates);
4759   // Remember the result of the analysis for this SCEV at this locayyytion.
4760   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4761   return PredRewrite;
4762 }
4763 
4764 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4765 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4766   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4767   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4768   if (!L)
4769     return None;
4770 
4771   // Check to see if we already analyzed this PHI.
4772   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4773   if (I != PredicatedSCEVRewrites.end()) {
4774     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4775         I->second;
4776     // Analysis was done before and failed to create an AddRec:
4777     if (Rewrite.first == SymbolicPHI)
4778       return None;
4779     // Analysis was done before and succeeded to create an AddRec under
4780     // a predicate:
4781     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4782     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4783     return Rewrite;
4784   }
4785 
4786   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4787     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4788 
4789   // Record in the cache that the analysis failed
4790   if (!Rewrite) {
4791     SmallVector<const SCEVPredicate *, 3> Predicates;
4792     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4793     return None;
4794   }
4795 
4796   return Rewrite;
4797 }
4798 
4799 // FIXME: This utility is currently required because the Rewriter currently
4800 // does not rewrite this expression:
4801 // {0, +, (sext ix (trunc iy to ix) to iy)}
4802 // into {0, +, %step},
4803 // even when the following Equal predicate exists:
4804 // "%step == (sext ix (trunc iy to ix) to iy)".
4805 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4806     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4807   if (AR1 == AR2)
4808     return true;
4809 
4810   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4811     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4812         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4813       return false;
4814     return true;
4815   };
4816 
4817   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4818       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4819     return false;
4820   return true;
4821 }
4822 
4823 /// A helper function for createAddRecFromPHI to handle simple cases.
4824 ///
4825 /// This function tries to find an AddRec expression for the simplest (yet most
4826 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4827 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4828 /// technique for finding the AddRec expression.
4829 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4830                                                       Value *BEValueV,
4831                                                       Value *StartValueV) {
4832   const Loop *L = LI.getLoopFor(PN->getParent());
4833   assert(L && L->getHeader() == PN->getParent());
4834   assert(BEValueV && StartValueV);
4835 
4836   auto BO = MatchBinaryOp(BEValueV, DT);
4837   if (!BO)
4838     return nullptr;
4839 
4840   if (BO->Opcode != Instruction::Add)
4841     return nullptr;
4842 
4843   const SCEV *Accum = nullptr;
4844   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4845     Accum = getSCEV(BO->RHS);
4846   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4847     Accum = getSCEV(BO->LHS);
4848 
4849   if (!Accum)
4850     return nullptr;
4851 
4852   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4853   if (BO->IsNUW)
4854     Flags = setFlags(Flags, SCEV::FlagNUW);
4855   if (BO->IsNSW)
4856     Flags = setFlags(Flags, SCEV::FlagNSW);
4857 
4858   const SCEV *StartVal = getSCEV(StartValueV);
4859   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4860 
4861   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4862 
4863   // We can add Flags to the post-inc expression only if we
4864   // know that it is *undefined behavior* for BEValueV to
4865   // overflow.
4866   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4867     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4868       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4869 
4870   return PHISCEV;
4871 }
4872 
4873 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4874   const Loop *L = LI.getLoopFor(PN->getParent());
4875   if (!L || L->getHeader() != PN->getParent())
4876     return nullptr;
4877 
4878   // The loop may have multiple entrances or multiple exits; we can analyze
4879   // this phi as an addrec if it has a unique entry value and a unique
4880   // backedge value.
4881   Value *BEValueV = nullptr, *StartValueV = nullptr;
4882   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4883     Value *V = PN->getIncomingValue(i);
4884     if (L->contains(PN->getIncomingBlock(i))) {
4885       if (!BEValueV) {
4886         BEValueV = V;
4887       } else if (BEValueV != V) {
4888         BEValueV = nullptr;
4889         break;
4890       }
4891     } else if (!StartValueV) {
4892       StartValueV = V;
4893     } else if (StartValueV != V) {
4894       StartValueV = nullptr;
4895       break;
4896     }
4897   }
4898   if (!BEValueV || !StartValueV)
4899     return nullptr;
4900 
4901   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4902          "PHI node already processed?");
4903 
4904   // First, try to find AddRec expression without creating a fictituos symbolic
4905   // value for PN.
4906   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4907     return S;
4908 
4909   // Handle PHI node value symbolically.
4910   const SCEV *SymbolicName = getUnknown(PN);
4911   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4912 
4913   // Using this symbolic name for the PHI, analyze the value coming around
4914   // the back-edge.
4915   const SCEV *BEValue = getSCEV(BEValueV);
4916 
4917   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4918   // has a special value for the first iteration of the loop.
4919 
4920   // If the value coming around the backedge is an add with the symbolic
4921   // value we just inserted, then we found a simple induction variable!
4922   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4923     // If there is a single occurrence of the symbolic value, replace it
4924     // with a recurrence.
4925     unsigned FoundIndex = Add->getNumOperands();
4926     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4927       if (Add->getOperand(i) == SymbolicName)
4928         if (FoundIndex == e) {
4929           FoundIndex = i;
4930           break;
4931         }
4932 
4933     if (FoundIndex != Add->getNumOperands()) {
4934       // Create an add with everything but the specified operand.
4935       SmallVector<const SCEV *, 8> Ops;
4936       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4937         if (i != FoundIndex)
4938           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4939                                                              L, *this));
4940       const SCEV *Accum = getAddExpr(Ops);
4941 
4942       // This is not a valid addrec if the step amount is varying each
4943       // loop iteration, but is not itself an addrec in this loop.
4944       if (isLoopInvariant(Accum, L) ||
4945           (isa<SCEVAddRecExpr>(Accum) &&
4946            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4947         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4948 
4949         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4950           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4951             if (BO->IsNUW)
4952               Flags = setFlags(Flags, SCEV::FlagNUW);
4953             if (BO->IsNSW)
4954               Flags = setFlags(Flags, SCEV::FlagNSW);
4955           }
4956         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4957           // If the increment is an inbounds GEP, then we know the address
4958           // space cannot be wrapped around. We cannot make any guarantee
4959           // about signed or unsigned overflow because pointers are
4960           // unsigned but we may have a negative index from the base
4961           // pointer. We can guarantee that no unsigned wrap occurs if the
4962           // indices form a positive value.
4963           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4964             Flags = setFlags(Flags, SCEV::FlagNW);
4965 
4966             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4967             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4968               Flags = setFlags(Flags, SCEV::FlagNUW);
4969           }
4970 
4971           // We cannot transfer nuw and nsw flags from subtraction
4972           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4973           // for instance.
4974         }
4975 
4976         const SCEV *StartVal = getSCEV(StartValueV);
4977         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4978 
4979         // Okay, for the entire analysis of this edge we assumed the PHI
4980         // to be symbolic.  We now need to go back and purge all of the
4981         // entries for the scalars that use the symbolic expression.
4982         forgetSymbolicName(PN, SymbolicName);
4983         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4984 
4985         // We can add Flags to the post-inc expression only if we
4986         // know that it is *undefined behavior* for BEValueV to
4987         // overflow.
4988         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4989           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4990             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4991 
4992         return PHISCEV;
4993       }
4994     }
4995   } else {
4996     // Otherwise, this could be a loop like this:
4997     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4998     // In this case, j = {1,+,1}  and BEValue is j.
4999     // Because the other in-value of i (0) fits the evolution of BEValue
5000     // i really is an addrec evolution.
5001     //
5002     // We can generalize this saying that i is the shifted value of BEValue
5003     // by one iteration:
5004     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5005     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5006     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5007     if (Shifted != getCouldNotCompute() &&
5008         Start != getCouldNotCompute()) {
5009       const SCEV *StartVal = getSCEV(StartValueV);
5010       if (Start == StartVal) {
5011         // Okay, for the entire analysis of this edge we assumed the PHI
5012         // to be symbolic.  We now need to go back and purge all of the
5013         // entries for the scalars that use the symbolic expression.
5014         forgetSymbolicName(PN, SymbolicName);
5015         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5016         return Shifted;
5017       }
5018     }
5019   }
5020 
5021   // Remove the temporary PHI node SCEV that has been inserted while intending
5022   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5023   // as it will prevent later (possibly simpler) SCEV expressions to be added
5024   // to the ValueExprMap.
5025   eraseValueFromMap(PN);
5026 
5027   return nullptr;
5028 }
5029 
5030 // Checks if the SCEV S is available at BB.  S is considered available at BB
5031 // if S can be materialized at BB without introducing a fault.
5032 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5033                                BasicBlock *BB) {
5034   struct CheckAvailable {
5035     bool TraversalDone = false;
5036     bool Available = true;
5037 
5038     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5039     BasicBlock *BB = nullptr;
5040     DominatorTree &DT;
5041 
5042     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5043       : L(L), BB(BB), DT(DT) {}
5044 
5045     bool setUnavailable() {
5046       TraversalDone = true;
5047       Available = false;
5048       return false;
5049     }
5050 
5051     bool follow(const SCEV *S) {
5052       switch (S->getSCEVType()) {
5053       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5054       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5055         // These expressions are available if their operand(s) is/are.
5056         return true;
5057 
5058       case scAddRecExpr: {
5059         // We allow add recurrences that are on the loop BB is in, or some
5060         // outer loop.  This guarantees availability because the value of the
5061         // add recurrence at BB is simply the "current" value of the induction
5062         // variable.  We can relax this in the future; for instance an add
5063         // recurrence on a sibling dominating loop is also available at BB.
5064         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5065         if (L && (ARLoop == L || ARLoop->contains(L)))
5066           return true;
5067 
5068         return setUnavailable();
5069       }
5070 
5071       case scUnknown: {
5072         // For SCEVUnknown, we check for simple dominance.
5073         const auto *SU = cast<SCEVUnknown>(S);
5074         Value *V = SU->getValue();
5075 
5076         if (isa<Argument>(V))
5077           return false;
5078 
5079         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5080           return false;
5081 
5082         return setUnavailable();
5083       }
5084 
5085       case scUDivExpr:
5086       case scCouldNotCompute:
5087         // We do not try to smart about these at all.
5088         return setUnavailable();
5089       }
5090       llvm_unreachable("switch should be fully covered!");
5091     }
5092 
5093     bool isDone() { return TraversalDone; }
5094   };
5095 
5096   CheckAvailable CA(L, BB, DT);
5097   SCEVTraversal<CheckAvailable> ST(CA);
5098 
5099   ST.visitAll(S);
5100   return CA.Available;
5101 }
5102 
5103 // Try to match a control flow sequence that branches out at BI and merges back
5104 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5105 // match.
5106 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5107                           Value *&C, Value *&LHS, Value *&RHS) {
5108   C = BI->getCondition();
5109 
5110   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5111   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5112 
5113   if (!LeftEdge.isSingleEdge())
5114     return false;
5115 
5116   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5117 
5118   Use &LeftUse = Merge->getOperandUse(0);
5119   Use &RightUse = Merge->getOperandUse(1);
5120 
5121   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5122     LHS = LeftUse;
5123     RHS = RightUse;
5124     return true;
5125   }
5126 
5127   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5128     LHS = RightUse;
5129     RHS = LeftUse;
5130     return true;
5131   }
5132 
5133   return false;
5134 }
5135 
5136 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5137   auto IsReachable =
5138       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5139   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5140     const Loop *L = LI.getLoopFor(PN->getParent());
5141 
5142     // We don't want to break LCSSA, even in a SCEV expression tree.
5143     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5144       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5145         return nullptr;
5146 
5147     // Try to match
5148     //
5149     //  br %cond, label %left, label %right
5150     // left:
5151     //  br label %merge
5152     // right:
5153     //  br label %merge
5154     // merge:
5155     //  V = phi [ %x, %left ], [ %y, %right ]
5156     //
5157     // as "select %cond, %x, %y"
5158 
5159     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5160     assert(IDom && "At least the entry block should dominate PN");
5161 
5162     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5163     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5164 
5165     if (BI && BI->isConditional() &&
5166         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5167         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5168         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5169       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5170   }
5171 
5172   return nullptr;
5173 }
5174 
5175 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5176   if (const SCEV *S = createAddRecFromPHI(PN))
5177     return S;
5178 
5179   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5180     return S;
5181 
5182   // If the PHI has a single incoming value, follow that value, unless the
5183   // PHI's incoming blocks are in a different loop, in which case doing so
5184   // risks breaking LCSSA form. Instcombine would normally zap these, but
5185   // it doesn't have DominatorTree information, so it may miss cases.
5186   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5187     if (LI.replacementPreservesLCSSAForm(PN, V))
5188       return getSCEV(V);
5189 
5190   // If it's not a loop phi, we can't handle it yet.
5191   return getUnknown(PN);
5192 }
5193 
5194 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5195                                                       Value *Cond,
5196                                                       Value *TrueVal,
5197                                                       Value *FalseVal) {
5198   // Handle "constant" branch or select. This can occur for instance when a
5199   // loop pass transforms an inner loop and moves on to process the outer loop.
5200   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5201     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5202 
5203   // Try to match some simple smax or umax patterns.
5204   auto *ICI = dyn_cast<ICmpInst>(Cond);
5205   if (!ICI)
5206     return getUnknown(I);
5207 
5208   Value *LHS = ICI->getOperand(0);
5209   Value *RHS = ICI->getOperand(1);
5210 
5211   switch (ICI->getPredicate()) {
5212   case ICmpInst::ICMP_SLT:
5213   case ICmpInst::ICMP_SLE:
5214     std::swap(LHS, RHS);
5215     LLVM_FALLTHROUGH;
5216   case ICmpInst::ICMP_SGT:
5217   case ICmpInst::ICMP_SGE:
5218     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5219     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5220     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5221       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5222       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5223       const SCEV *LA = getSCEV(TrueVal);
5224       const SCEV *RA = getSCEV(FalseVal);
5225       const SCEV *LDiff = getMinusSCEV(LA, LS);
5226       const SCEV *RDiff = getMinusSCEV(RA, RS);
5227       if (LDiff == RDiff)
5228         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5229       LDiff = getMinusSCEV(LA, RS);
5230       RDiff = getMinusSCEV(RA, LS);
5231       if (LDiff == RDiff)
5232         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5233     }
5234     break;
5235   case ICmpInst::ICMP_ULT:
5236   case ICmpInst::ICMP_ULE:
5237     std::swap(LHS, RHS);
5238     LLVM_FALLTHROUGH;
5239   case ICmpInst::ICMP_UGT:
5240   case ICmpInst::ICMP_UGE:
5241     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5242     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5243     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5244       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5245       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5246       const SCEV *LA = getSCEV(TrueVal);
5247       const SCEV *RA = getSCEV(FalseVal);
5248       const SCEV *LDiff = getMinusSCEV(LA, LS);
5249       const SCEV *RDiff = getMinusSCEV(RA, RS);
5250       if (LDiff == RDiff)
5251         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5252       LDiff = getMinusSCEV(LA, RS);
5253       RDiff = getMinusSCEV(RA, LS);
5254       if (LDiff == RDiff)
5255         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5256     }
5257     break;
5258   case ICmpInst::ICMP_NE:
5259     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5260     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5261         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5262       const SCEV *One = getOne(I->getType());
5263       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5264       const SCEV *LA = getSCEV(TrueVal);
5265       const SCEV *RA = getSCEV(FalseVal);
5266       const SCEV *LDiff = getMinusSCEV(LA, LS);
5267       const SCEV *RDiff = getMinusSCEV(RA, One);
5268       if (LDiff == RDiff)
5269         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5270     }
5271     break;
5272   case ICmpInst::ICMP_EQ:
5273     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5274     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5275         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5276       const SCEV *One = getOne(I->getType());
5277       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5278       const SCEV *LA = getSCEV(TrueVal);
5279       const SCEV *RA = getSCEV(FalseVal);
5280       const SCEV *LDiff = getMinusSCEV(LA, One);
5281       const SCEV *RDiff = getMinusSCEV(RA, LS);
5282       if (LDiff == RDiff)
5283         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5284     }
5285     break;
5286   default:
5287     break;
5288   }
5289 
5290   return getUnknown(I);
5291 }
5292 
5293 /// Expand GEP instructions into add and multiply operations. This allows them
5294 /// to be analyzed by regular SCEV code.
5295 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5296   // Don't attempt to analyze GEPs over unsized objects.
5297   if (!GEP->getSourceElementType()->isSized())
5298     return getUnknown(GEP);
5299 
5300   SmallVector<const SCEV *, 4> IndexExprs;
5301   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5302     IndexExprs.push_back(getSCEV(*Index));
5303   return getGEPExpr(GEP, IndexExprs);
5304 }
5305 
5306 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5307   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5308     return C->getAPInt().countTrailingZeros();
5309 
5310   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5311     return std::min(GetMinTrailingZeros(T->getOperand()),
5312                     (uint32_t)getTypeSizeInBits(T->getType()));
5313 
5314   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5315     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5316     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5317                ? getTypeSizeInBits(E->getType())
5318                : OpRes;
5319   }
5320 
5321   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5322     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5323     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5324                ? getTypeSizeInBits(E->getType())
5325                : OpRes;
5326   }
5327 
5328   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5329     // The result is the min of all operands results.
5330     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5331     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5332       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5333     return MinOpRes;
5334   }
5335 
5336   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5337     // The result is the sum of all operands results.
5338     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5339     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5340     for (unsigned i = 1, e = M->getNumOperands();
5341          SumOpRes != BitWidth && i != e; ++i)
5342       SumOpRes =
5343           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5344     return SumOpRes;
5345   }
5346 
5347   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5348     // The result is the min of all operands results.
5349     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5350     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5351       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5352     return MinOpRes;
5353   }
5354 
5355   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5356     // The result is the min of all operands results.
5357     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5358     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5359       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5360     return MinOpRes;
5361   }
5362 
5363   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5364     // The result is the min of all operands results.
5365     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5366     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5367       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5368     return MinOpRes;
5369   }
5370 
5371   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5372     // For a SCEVUnknown, ask ValueTracking.
5373     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5374     return Known.countMinTrailingZeros();
5375   }
5376 
5377   // SCEVUDivExpr
5378   return 0;
5379 }
5380 
5381 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5382   auto I = MinTrailingZerosCache.find(S);
5383   if (I != MinTrailingZerosCache.end())
5384     return I->second;
5385 
5386   uint32_t Result = GetMinTrailingZerosImpl(S);
5387   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5388   assert(InsertPair.second && "Should insert a new key");
5389   return InsertPair.first->second;
5390 }
5391 
5392 /// Helper method to assign a range to V from metadata present in the IR.
5393 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5394   if (Instruction *I = dyn_cast<Instruction>(V))
5395     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5396       return getConstantRangeFromMetadata(*MD);
5397 
5398   return None;
5399 }
5400 
5401 /// Determine the range for a particular SCEV.  If SignHint is
5402 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5403 /// with a "cleaner" unsigned (resp. signed) representation.
5404 const ConstantRange &
5405 ScalarEvolution::getRangeRef(const SCEV *S,
5406                              ScalarEvolution::RangeSignHint SignHint) {
5407   DenseMap<const SCEV *, ConstantRange> &Cache =
5408       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5409                                                        : SignedRanges;
5410 
5411   // See if we've computed this range already.
5412   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5413   if (I != Cache.end())
5414     return I->second;
5415 
5416   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5417     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5418 
5419   unsigned BitWidth = getTypeSizeInBits(S->getType());
5420   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5421 
5422   // If the value has known zeros, the maximum value will have those known zeros
5423   // as well.
5424   uint32_t TZ = GetMinTrailingZeros(S);
5425   if (TZ != 0) {
5426     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5427       ConservativeResult =
5428           ConstantRange(APInt::getMinValue(BitWidth),
5429                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5430     else
5431       ConservativeResult = ConstantRange(
5432           APInt::getSignedMinValue(BitWidth),
5433           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5434   }
5435 
5436   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5437     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5438     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5439       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5440     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5441   }
5442 
5443   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5444     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5445     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5446       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5447     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5448   }
5449 
5450   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5451     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5452     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5453       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5454     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5455   }
5456 
5457   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5458     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5459     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5460       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5461     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5462   }
5463 
5464   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5465     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5466     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5467     return setRange(UDiv, SignHint,
5468                     ConservativeResult.intersectWith(X.udiv(Y)));
5469   }
5470 
5471   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5472     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5473     return setRange(ZExt, SignHint,
5474                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5475   }
5476 
5477   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5478     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5479     return setRange(SExt, SignHint,
5480                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5481   }
5482 
5483   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5484     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5485     return setRange(Trunc, SignHint,
5486                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5487   }
5488 
5489   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5490     // If there's no unsigned wrap, the value will never be less than its
5491     // initial value.
5492     if (AddRec->hasNoUnsignedWrap())
5493       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5494         if (!C->getValue()->isZero())
5495           ConservativeResult = ConservativeResult.intersectWith(
5496               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5497 
5498     // If there's no signed wrap, and all the operands have the same sign or
5499     // zero, the value won't ever change sign.
5500     if (AddRec->hasNoSignedWrap()) {
5501       bool AllNonNeg = true;
5502       bool AllNonPos = true;
5503       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5504         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5505         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5506       }
5507       if (AllNonNeg)
5508         ConservativeResult = ConservativeResult.intersectWith(
5509           ConstantRange(APInt(BitWidth, 0),
5510                         APInt::getSignedMinValue(BitWidth)));
5511       else if (AllNonPos)
5512         ConservativeResult = ConservativeResult.intersectWith(
5513           ConstantRange(APInt::getSignedMinValue(BitWidth),
5514                         APInt(BitWidth, 1)));
5515     }
5516 
5517     // TODO: non-affine addrec
5518     if (AddRec->isAffine()) {
5519       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5520       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5521           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5522         auto RangeFromAffine = getRangeForAffineAR(
5523             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5524             BitWidth);
5525         if (!RangeFromAffine.isFullSet())
5526           ConservativeResult =
5527               ConservativeResult.intersectWith(RangeFromAffine);
5528 
5529         auto RangeFromFactoring = getRangeViaFactoring(
5530             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5531             BitWidth);
5532         if (!RangeFromFactoring.isFullSet())
5533           ConservativeResult =
5534               ConservativeResult.intersectWith(RangeFromFactoring);
5535       }
5536     }
5537 
5538     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5539   }
5540 
5541   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5542     // Check if the IR explicitly contains !range metadata.
5543     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5544     if (MDRange.hasValue())
5545       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5546 
5547     // Split here to avoid paying the compile-time cost of calling both
5548     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5549     // if needed.
5550     const DataLayout &DL = getDataLayout();
5551     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5552       // For a SCEVUnknown, ask ValueTracking.
5553       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5554       if (Known.One != ~Known.Zero + 1)
5555         ConservativeResult =
5556             ConservativeResult.intersectWith(ConstantRange(Known.One,
5557                                                            ~Known.Zero + 1));
5558     } else {
5559       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5560              "generalize as needed!");
5561       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5562       if (NS > 1)
5563         ConservativeResult = ConservativeResult.intersectWith(
5564             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5565                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5566     }
5567 
5568     // A range of Phi is a subset of union of all ranges of its input.
5569     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5570       // Make sure that we do not run over cycled Phis.
5571       if (PendingPhiRanges.insert(Phi).second) {
5572         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5573         for (auto &Op : Phi->operands()) {
5574           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5575           RangeFromOps = RangeFromOps.unionWith(OpRange);
5576           // No point to continue if we already have a full set.
5577           if (RangeFromOps.isFullSet())
5578             break;
5579         }
5580         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5581         bool Erased = PendingPhiRanges.erase(Phi);
5582         assert(Erased && "Failed to erase Phi properly?");
5583         (void) Erased;
5584       }
5585     }
5586 
5587     return setRange(U, SignHint, std::move(ConservativeResult));
5588   }
5589 
5590   return setRange(S, SignHint, std::move(ConservativeResult));
5591 }
5592 
5593 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5594 // values that the expression can take. Initially, the expression has a value
5595 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5596 // argument defines if we treat Step as signed or unsigned.
5597 static ConstantRange getRangeForAffineARHelper(APInt Step,
5598                                                const ConstantRange &StartRange,
5599                                                const APInt &MaxBECount,
5600                                                unsigned BitWidth, bool Signed) {
5601   // If either Step or MaxBECount is 0, then the expression won't change, and we
5602   // just need to return the initial range.
5603   if (Step == 0 || MaxBECount == 0)
5604     return StartRange;
5605 
5606   // If we don't know anything about the initial value (i.e. StartRange is
5607   // FullRange), then we don't know anything about the final range either.
5608   // Return FullRange.
5609   if (StartRange.isFullSet())
5610     return ConstantRange(BitWidth, /* isFullSet = */ true);
5611 
5612   // If Step is signed and negative, then we use its absolute value, but we also
5613   // note that we're moving in the opposite direction.
5614   bool Descending = Signed && Step.isNegative();
5615 
5616   if (Signed)
5617     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5618     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5619     // This equations hold true due to the well-defined wrap-around behavior of
5620     // APInt.
5621     Step = Step.abs();
5622 
5623   // Check if Offset is more than full span of BitWidth. If it is, the
5624   // expression is guaranteed to overflow.
5625   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5626     return ConstantRange(BitWidth, /* isFullSet = */ true);
5627 
5628   // Offset is by how much the expression can change. Checks above guarantee no
5629   // overflow here.
5630   APInt Offset = Step * MaxBECount;
5631 
5632   // Minimum value of the final range will match the minimal value of StartRange
5633   // if the expression is increasing and will be decreased by Offset otherwise.
5634   // Maximum value of the final range will match the maximal value of StartRange
5635   // if the expression is decreasing and will be increased by Offset otherwise.
5636   APInt StartLower = StartRange.getLower();
5637   APInt StartUpper = StartRange.getUpper() - 1;
5638   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5639                                    : (StartUpper + std::move(Offset));
5640 
5641   // It's possible that the new minimum/maximum value will fall into the initial
5642   // range (due to wrap around). This means that the expression can take any
5643   // value in this bitwidth, and we have to return full range.
5644   if (StartRange.contains(MovedBoundary))
5645     return ConstantRange(BitWidth, /* isFullSet = */ true);
5646 
5647   APInt NewLower =
5648       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5649   APInt NewUpper =
5650       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5651   NewUpper += 1;
5652 
5653   // If we end up with full range, return a proper full range.
5654   if (NewLower == NewUpper)
5655     return ConstantRange(BitWidth, /* isFullSet = */ true);
5656 
5657   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5658   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5659 }
5660 
5661 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5662                                                    const SCEV *Step,
5663                                                    const SCEV *MaxBECount,
5664                                                    unsigned BitWidth) {
5665   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5666          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5667          "Precondition!");
5668 
5669   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5670   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5671 
5672   // First, consider step signed.
5673   ConstantRange StartSRange = getSignedRange(Start);
5674   ConstantRange StepSRange = getSignedRange(Step);
5675 
5676   // If Step can be both positive and negative, we need to find ranges for the
5677   // maximum absolute step values in both directions and union them.
5678   ConstantRange SR =
5679       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5680                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5681   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5682                                               StartSRange, MaxBECountValue,
5683                                               BitWidth, /* Signed = */ true));
5684 
5685   // Next, consider step unsigned.
5686   ConstantRange UR = getRangeForAffineARHelper(
5687       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5688       MaxBECountValue, BitWidth, /* Signed = */ false);
5689 
5690   // Finally, intersect signed and unsigned ranges.
5691   return SR.intersectWith(UR);
5692 }
5693 
5694 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5695                                                     const SCEV *Step,
5696                                                     const SCEV *MaxBECount,
5697                                                     unsigned BitWidth) {
5698   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5699   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5700 
5701   struct SelectPattern {
5702     Value *Condition = nullptr;
5703     APInt TrueValue;
5704     APInt FalseValue;
5705 
5706     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5707                            const SCEV *S) {
5708       Optional<unsigned> CastOp;
5709       APInt Offset(BitWidth, 0);
5710 
5711       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5712              "Should be!");
5713 
5714       // Peel off a constant offset:
5715       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5716         // In the future we could consider being smarter here and handle
5717         // {Start+Step,+,Step} too.
5718         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5719           return;
5720 
5721         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5722         S = SA->getOperand(1);
5723       }
5724 
5725       // Peel off a cast operation
5726       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5727         CastOp = SCast->getSCEVType();
5728         S = SCast->getOperand();
5729       }
5730 
5731       using namespace llvm::PatternMatch;
5732 
5733       auto *SU = dyn_cast<SCEVUnknown>(S);
5734       const APInt *TrueVal, *FalseVal;
5735       if (!SU ||
5736           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5737                                           m_APInt(FalseVal)))) {
5738         Condition = nullptr;
5739         return;
5740       }
5741 
5742       TrueValue = *TrueVal;
5743       FalseValue = *FalseVal;
5744 
5745       // Re-apply the cast we peeled off earlier
5746       if (CastOp.hasValue())
5747         switch (*CastOp) {
5748         default:
5749           llvm_unreachable("Unknown SCEV cast type!");
5750 
5751         case scTruncate:
5752           TrueValue = TrueValue.trunc(BitWidth);
5753           FalseValue = FalseValue.trunc(BitWidth);
5754           break;
5755         case scZeroExtend:
5756           TrueValue = TrueValue.zext(BitWidth);
5757           FalseValue = FalseValue.zext(BitWidth);
5758           break;
5759         case scSignExtend:
5760           TrueValue = TrueValue.sext(BitWidth);
5761           FalseValue = FalseValue.sext(BitWidth);
5762           break;
5763         }
5764 
5765       // Re-apply the constant offset we peeled off earlier
5766       TrueValue += Offset;
5767       FalseValue += Offset;
5768     }
5769 
5770     bool isRecognized() { return Condition != nullptr; }
5771   };
5772 
5773   SelectPattern StartPattern(*this, BitWidth, Start);
5774   if (!StartPattern.isRecognized())
5775     return ConstantRange(BitWidth, /* isFullSet = */ true);
5776 
5777   SelectPattern StepPattern(*this, BitWidth, Step);
5778   if (!StepPattern.isRecognized())
5779     return ConstantRange(BitWidth, /* isFullSet = */ true);
5780 
5781   if (StartPattern.Condition != StepPattern.Condition) {
5782     // We don't handle this case today; but we could, by considering four
5783     // possibilities below instead of two. I'm not sure if there are cases where
5784     // that will help over what getRange already does, though.
5785     return ConstantRange(BitWidth, /* isFullSet = */ true);
5786   }
5787 
5788   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5789   // construct arbitrary general SCEV expressions here.  This function is called
5790   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5791   // say) can end up caching a suboptimal value.
5792 
5793   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5794   // C2352 and C2512 (otherwise it isn't needed).
5795 
5796   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5797   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5798   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5799   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5800 
5801   ConstantRange TrueRange =
5802       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5803   ConstantRange FalseRange =
5804       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5805 
5806   return TrueRange.unionWith(FalseRange);
5807 }
5808 
5809 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5810   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5811   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5812 
5813   // Return early if there are no flags to propagate to the SCEV.
5814   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5815   if (BinOp->hasNoUnsignedWrap())
5816     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5817   if (BinOp->hasNoSignedWrap())
5818     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5819   if (Flags == SCEV::FlagAnyWrap)
5820     return SCEV::FlagAnyWrap;
5821 
5822   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5823 }
5824 
5825 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5826   // Here we check that I is in the header of the innermost loop containing I,
5827   // since we only deal with instructions in the loop header. The actual loop we
5828   // need to check later will come from an add recurrence, but getting that
5829   // requires computing the SCEV of the operands, which can be expensive. This
5830   // check we can do cheaply to rule out some cases early.
5831   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5832   if (InnermostContainingLoop == nullptr ||
5833       InnermostContainingLoop->getHeader() != I->getParent())
5834     return false;
5835 
5836   // Only proceed if we can prove that I does not yield poison.
5837   if (!programUndefinedIfFullPoison(I))
5838     return false;
5839 
5840   // At this point we know that if I is executed, then it does not wrap
5841   // according to at least one of NSW or NUW. If I is not executed, then we do
5842   // not know if the calculation that I represents would wrap. Multiple
5843   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5844   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5845   // derived from other instructions that map to the same SCEV. We cannot make
5846   // that guarantee for cases where I is not executed. So we need to find the
5847   // loop that I is considered in relation to and prove that I is executed for
5848   // every iteration of that loop. That implies that the value that I
5849   // calculates does not wrap anywhere in the loop, so then we can apply the
5850   // flags to the SCEV.
5851   //
5852   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5853   // from different loops, so that we know which loop to prove that I is
5854   // executed in.
5855   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5856     // I could be an extractvalue from a call to an overflow intrinsic.
5857     // TODO: We can do better here in some cases.
5858     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5859       return false;
5860     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5861     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5862       bool AllOtherOpsLoopInvariant = true;
5863       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5864            ++OtherOpIndex) {
5865         if (OtherOpIndex != OpIndex) {
5866           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5867           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5868             AllOtherOpsLoopInvariant = false;
5869             break;
5870           }
5871         }
5872       }
5873       if (AllOtherOpsLoopInvariant &&
5874           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5875         return true;
5876     }
5877   }
5878   return false;
5879 }
5880 
5881 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5882   // If we know that \c I can never be poison period, then that's enough.
5883   if (isSCEVExprNeverPoison(I))
5884     return true;
5885 
5886   // For an add recurrence specifically, we assume that infinite loops without
5887   // side effects are undefined behavior, and then reason as follows:
5888   //
5889   // If the add recurrence is poison in any iteration, it is poison on all
5890   // future iterations (since incrementing poison yields poison). If the result
5891   // of the add recurrence is fed into the loop latch condition and the loop
5892   // does not contain any throws or exiting blocks other than the latch, we now
5893   // have the ability to "choose" whether the backedge is taken or not (by
5894   // choosing a sufficiently evil value for the poison feeding into the branch)
5895   // for every iteration including and after the one in which \p I first became
5896   // poison.  There are two possibilities (let's call the iteration in which \p
5897   // I first became poison as K):
5898   //
5899   //  1. In the set of iterations including and after K, the loop body executes
5900   //     no side effects.  In this case executing the backege an infinte number
5901   //     of times will yield undefined behavior.
5902   //
5903   //  2. In the set of iterations including and after K, the loop body executes
5904   //     at least one side effect.  In this case, that specific instance of side
5905   //     effect is control dependent on poison, which also yields undefined
5906   //     behavior.
5907 
5908   auto *ExitingBB = L->getExitingBlock();
5909   auto *LatchBB = L->getLoopLatch();
5910   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5911     return false;
5912 
5913   SmallPtrSet<const Instruction *, 16> Pushed;
5914   SmallVector<const Instruction *, 8> PoisonStack;
5915 
5916   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5917   // things that are known to be fully poison under that assumption go on the
5918   // PoisonStack.
5919   Pushed.insert(I);
5920   PoisonStack.push_back(I);
5921 
5922   bool LatchControlDependentOnPoison = false;
5923   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5924     const Instruction *Poison = PoisonStack.pop_back_val();
5925 
5926     for (auto *PoisonUser : Poison->users()) {
5927       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5928         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5929           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5930       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5931         assert(BI->isConditional() && "Only possibility!");
5932         if (BI->getParent() == LatchBB) {
5933           LatchControlDependentOnPoison = true;
5934           break;
5935         }
5936       }
5937     }
5938   }
5939 
5940   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5941 }
5942 
5943 ScalarEvolution::LoopProperties
5944 ScalarEvolution::getLoopProperties(const Loop *L) {
5945   using LoopProperties = ScalarEvolution::LoopProperties;
5946 
5947   auto Itr = LoopPropertiesCache.find(L);
5948   if (Itr == LoopPropertiesCache.end()) {
5949     auto HasSideEffects = [](Instruction *I) {
5950       if (auto *SI = dyn_cast<StoreInst>(I))
5951         return !SI->isSimple();
5952 
5953       return I->mayHaveSideEffects();
5954     };
5955 
5956     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5957                          /*HasNoSideEffects*/ true};
5958 
5959     for (auto *BB : L->getBlocks())
5960       for (auto &I : *BB) {
5961         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5962           LP.HasNoAbnormalExits = false;
5963         if (HasSideEffects(&I))
5964           LP.HasNoSideEffects = false;
5965         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5966           break; // We're already as pessimistic as we can get.
5967       }
5968 
5969     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5970     assert(InsertPair.second && "We just checked!");
5971     Itr = InsertPair.first;
5972   }
5973 
5974   return Itr->second;
5975 }
5976 
5977 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5978   if (!isSCEVable(V->getType()))
5979     return getUnknown(V);
5980 
5981   if (Instruction *I = dyn_cast<Instruction>(V)) {
5982     // Don't attempt to analyze instructions in blocks that aren't
5983     // reachable. Such instructions don't matter, and they aren't required
5984     // to obey basic rules for definitions dominating uses which this
5985     // analysis depends on.
5986     if (!DT.isReachableFromEntry(I->getParent()))
5987       return getUnknown(V);
5988   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5989     return getConstant(CI);
5990   else if (isa<ConstantPointerNull>(V))
5991     return getZero(V->getType());
5992   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5993     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5994   else if (!isa<ConstantExpr>(V))
5995     return getUnknown(V);
5996 
5997   Operator *U = cast<Operator>(V);
5998   if (auto BO = MatchBinaryOp(U, DT)) {
5999     switch (BO->Opcode) {
6000     case Instruction::Add: {
6001       // The simple thing to do would be to just call getSCEV on both operands
6002       // and call getAddExpr with the result. However if we're looking at a
6003       // bunch of things all added together, this can be quite inefficient,
6004       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6005       // Instead, gather up all the operands and make a single getAddExpr call.
6006       // LLVM IR canonical form means we need only traverse the left operands.
6007       SmallVector<const SCEV *, 4> AddOps;
6008       do {
6009         if (BO->Op) {
6010           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6011             AddOps.push_back(OpSCEV);
6012             break;
6013           }
6014 
6015           // If a NUW or NSW flag can be applied to the SCEV for this
6016           // addition, then compute the SCEV for this addition by itself
6017           // with a separate call to getAddExpr. We need to do that
6018           // instead of pushing the operands of the addition onto AddOps,
6019           // since the flags are only known to apply to this particular
6020           // addition - they may not apply to other additions that can be
6021           // formed with operands from AddOps.
6022           const SCEV *RHS = getSCEV(BO->RHS);
6023           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6024           if (Flags != SCEV::FlagAnyWrap) {
6025             const SCEV *LHS = getSCEV(BO->LHS);
6026             if (BO->Opcode == Instruction::Sub)
6027               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6028             else
6029               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6030             break;
6031           }
6032         }
6033 
6034         if (BO->Opcode == Instruction::Sub)
6035           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6036         else
6037           AddOps.push_back(getSCEV(BO->RHS));
6038 
6039         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6040         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6041                        NewBO->Opcode != Instruction::Sub)) {
6042           AddOps.push_back(getSCEV(BO->LHS));
6043           break;
6044         }
6045         BO = NewBO;
6046       } while (true);
6047 
6048       return getAddExpr(AddOps);
6049     }
6050 
6051     case Instruction::Mul: {
6052       SmallVector<const SCEV *, 4> MulOps;
6053       do {
6054         if (BO->Op) {
6055           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6056             MulOps.push_back(OpSCEV);
6057             break;
6058           }
6059 
6060           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6061           if (Flags != SCEV::FlagAnyWrap) {
6062             MulOps.push_back(
6063                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6064             break;
6065           }
6066         }
6067 
6068         MulOps.push_back(getSCEV(BO->RHS));
6069         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6070         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6071           MulOps.push_back(getSCEV(BO->LHS));
6072           break;
6073         }
6074         BO = NewBO;
6075       } while (true);
6076 
6077       return getMulExpr(MulOps);
6078     }
6079     case Instruction::UDiv:
6080       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6081     case Instruction::URem:
6082       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6083     case Instruction::Sub: {
6084       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6085       if (BO->Op)
6086         Flags = getNoWrapFlagsFromUB(BO->Op);
6087       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6088     }
6089     case Instruction::And:
6090       // For an expression like x&255 that merely masks off the high bits,
6091       // use zext(trunc(x)) as the SCEV expression.
6092       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6093         if (CI->isZero())
6094           return getSCEV(BO->RHS);
6095         if (CI->isMinusOne())
6096           return getSCEV(BO->LHS);
6097         const APInt &A = CI->getValue();
6098 
6099         // Instcombine's ShrinkDemandedConstant may strip bits out of
6100         // constants, obscuring what would otherwise be a low-bits mask.
6101         // Use computeKnownBits to compute what ShrinkDemandedConstant
6102         // knew about to reconstruct a low-bits mask value.
6103         unsigned LZ = A.countLeadingZeros();
6104         unsigned TZ = A.countTrailingZeros();
6105         unsigned BitWidth = A.getBitWidth();
6106         KnownBits Known(BitWidth);
6107         computeKnownBits(BO->LHS, Known, getDataLayout(),
6108                          0, &AC, nullptr, &DT);
6109 
6110         APInt EffectiveMask =
6111             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6112         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6113           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6114           const SCEV *LHS = getSCEV(BO->LHS);
6115           const SCEV *ShiftedLHS = nullptr;
6116           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6117             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6118               // For an expression like (x * 8) & 8, simplify the multiply.
6119               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6120               unsigned GCD = std::min(MulZeros, TZ);
6121               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6122               SmallVector<const SCEV*, 4> MulOps;
6123               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6124               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6125               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6126               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6127             }
6128           }
6129           if (!ShiftedLHS)
6130             ShiftedLHS = getUDivExpr(LHS, MulCount);
6131           return getMulExpr(
6132               getZeroExtendExpr(
6133                   getTruncateExpr(ShiftedLHS,
6134                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6135                   BO->LHS->getType()),
6136               MulCount);
6137         }
6138       }
6139       break;
6140 
6141     case Instruction::Or:
6142       // If the RHS of the Or is a constant, we may have something like:
6143       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6144       // optimizations will transparently handle this case.
6145       //
6146       // In order for this transformation to be safe, the LHS must be of the
6147       // form X*(2^n) and the Or constant must be less than 2^n.
6148       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6149         const SCEV *LHS = getSCEV(BO->LHS);
6150         const APInt &CIVal = CI->getValue();
6151         if (GetMinTrailingZeros(LHS) >=
6152             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6153           // Build a plain add SCEV.
6154           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6155           // If the LHS of the add was an addrec and it has no-wrap flags,
6156           // transfer the no-wrap flags, since an or won't introduce a wrap.
6157           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6158             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6159             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6160                 OldAR->getNoWrapFlags());
6161           }
6162           return S;
6163         }
6164       }
6165       break;
6166 
6167     case Instruction::Xor:
6168       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6169         // If the RHS of xor is -1, then this is a not operation.
6170         if (CI->isMinusOne())
6171           return getNotSCEV(getSCEV(BO->LHS));
6172 
6173         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6174         // This is a variant of the check for xor with -1, and it handles
6175         // the case where instcombine has trimmed non-demanded bits out
6176         // of an xor with -1.
6177         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6178           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6179             if (LBO->getOpcode() == Instruction::And &&
6180                 LCI->getValue() == CI->getValue())
6181               if (const SCEVZeroExtendExpr *Z =
6182                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6183                 Type *UTy = BO->LHS->getType();
6184                 const SCEV *Z0 = Z->getOperand();
6185                 Type *Z0Ty = Z0->getType();
6186                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6187 
6188                 // If C is a low-bits mask, the zero extend is serving to
6189                 // mask off the high bits. Complement the operand and
6190                 // re-apply the zext.
6191                 if (CI->getValue().isMask(Z0TySize))
6192                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6193 
6194                 // If C is a single bit, it may be in the sign-bit position
6195                 // before the zero-extend. In this case, represent the xor
6196                 // using an add, which is equivalent, and re-apply the zext.
6197                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6198                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6199                     Trunc.isSignMask())
6200                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6201                                            UTy);
6202               }
6203       }
6204       break;
6205 
6206   case Instruction::Shl:
6207     // Turn shift left of a constant amount into a multiply.
6208     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6209       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6210 
6211       // If the shift count is not less than the bitwidth, the result of
6212       // the shift is undefined. Don't try to analyze it, because the
6213       // resolution chosen here may differ from the resolution chosen in
6214       // other parts of the compiler.
6215       if (SA->getValue().uge(BitWidth))
6216         break;
6217 
6218       // It is currently not resolved how to interpret NSW for left
6219       // shift by BitWidth - 1, so we avoid applying flags in that
6220       // case. Remove this check (or this comment) once the situation
6221       // is resolved. See
6222       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6223       // and http://reviews.llvm.org/D8890 .
6224       auto Flags = SCEV::FlagAnyWrap;
6225       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6226         Flags = getNoWrapFlagsFromUB(BO->Op);
6227 
6228       Constant *X = ConstantInt::get(getContext(),
6229         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6230       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6231     }
6232     break;
6233 
6234     case Instruction::AShr: {
6235       // AShr X, C, where C is a constant.
6236       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6237       if (!CI)
6238         break;
6239 
6240       Type *OuterTy = BO->LHS->getType();
6241       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6242       // If the shift count is not less than the bitwidth, the result of
6243       // the shift is undefined. Don't try to analyze it, because the
6244       // resolution chosen here may differ from the resolution chosen in
6245       // other parts of the compiler.
6246       if (CI->getValue().uge(BitWidth))
6247         break;
6248 
6249       if (CI->isZero())
6250         return getSCEV(BO->LHS); // shift by zero --> noop
6251 
6252       uint64_t AShrAmt = CI->getZExtValue();
6253       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6254 
6255       Operator *L = dyn_cast<Operator>(BO->LHS);
6256       if (L && L->getOpcode() == Instruction::Shl) {
6257         // X = Shl A, n
6258         // Y = AShr X, m
6259         // Both n and m are constant.
6260 
6261         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6262         if (L->getOperand(1) == BO->RHS)
6263           // For a two-shift sext-inreg, i.e. n = m,
6264           // use sext(trunc(x)) as the SCEV expression.
6265           return getSignExtendExpr(
6266               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6267 
6268         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6269         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6270           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6271           if (ShlAmt > AShrAmt) {
6272             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6273             // expression. We already checked that ShlAmt < BitWidth, so
6274             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6275             // ShlAmt - AShrAmt < Amt.
6276             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6277                                             ShlAmt - AShrAmt);
6278             return getSignExtendExpr(
6279                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6280                 getConstant(Mul)), OuterTy);
6281           }
6282         }
6283       }
6284       break;
6285     }
6286     }
6287   }
6288 
6289   switch (U->getOpcode()) {
6290   case Instruction::Trunc:
6291     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6292 
6293   case Instruction::ZExt:
6294     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6295 
6296   case Instruction::SExt:
6297     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6298       // The NSW flag of a subtract does not always survive the conversion to
6299       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6300       // more likely to preserve NSW and allow later AddRec optimisations.
6301       //
6302       // NOTE: This is effectively duplicating this logic from getSignExtend:
6303       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6304       // but by that point the NSW information has potentially been lost.
6305       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6306         Type *Ty = U->getType();
6307         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6308         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6309         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6310       }
6311     }
6312     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6313 
6314   case Instruction::BitCast:
6315     // BitCasts are no-op casts so we just eliminate the cast.
6316     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6317       return getSCEV(U->getOperand(0));
6318     break;
6319 
6320   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6321   // lead to pointer expressions which cannot safely be expanded to GEPs,
6322   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6323   // simplifying integer expressions.
6324 
6325   case Instruction::GetElementPtr:
6326     return createNodeForGEP(cast<GEPOperator>(U));
6327 
6328   case Instruction::PHI:
6329     return createNodeForPHI(cast<PHINode>(U));
6330 
6331   case Instruction::Select:
6332     // U can also be a select constant expr, which let fall through.  Since
6333     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6334     // constant expressions cannot have instructions as operands, we'd have
6335     // returned getUnknown for a select constant expressions anyway.
6336     if (isa<Instruction>(U))
6337       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6338                                       U->getOperand(1), U->getOperand(2));
6339     break;
6340 
6341   case Instruction::Call:
6342   case Instruction::Invoke:
6343     if (Value *RV = CallSite(U).getReturnedArgOperand())
6344       return getSCEV(RV);
6345     break;
6346   }
6347 
6348   return getUnknown(V);
6349 }
6350 
6351 //===----------------------------------------------------------------------===//
6352 //                   Iteration Count Computation Code
6353 //
6354 
6355 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6356   if (!ExitCount)
6357     return 0;
6358 
6359   ConstantInt *ExitConst = ExitCount->getValue();
6360 
6361   // Guard against huge trip counts.
6362   if (ExitConst->getValue().getActiveBits() > 32)
6363     return 0;
6364 
6365   // In case of integer overflow, this returns 0, which is correct.
6366   return ((unsigned)ExitConst->getZExtValue()) + 1;
6367 }
6368 
6369 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6370   if (BasicBlock *ExitingBB = L->getExitingBlock())
6371     return getSmallConstantTripCount(L, ExitingBB);
6372 
6373   // No trip count information for multiple exits.
6374   return 0;
6375 }
6376 
6377 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6378                                                     BasicBlock *ExitingBlock) {
6379   assert(ExitingBlock && "Must pass a non-null exiting block!");
6380   assert(L->isLoopExiting(ExitingBlock) &&
6381          "Exiting block must actually branch out of the loop!");
6382   const SCEVConstant *ExitCount =
6383       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6384   return getConstantTripCount(ExitCount);
6385 }
6386 
6387 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6388   const auto *MaxExitCount =
6389       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6390   return getConstantTripCount(MaxExitCount);
6391 }
6392 
6393 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6394   if (BasicBlock *ExitingBB = L->getExitingBlock())
6395     return getSmallConstantTripMultiple(L, ExitingBB);
6396 
6397   // No trip multiple information for multiple exits.
6398   return 0;
6399 }
6400 
6401 /// Returns the largest constant divisor of the trip count of this loop as a
6402 /// normal unsigned value, if possible. This means that the actual trip count is
6403 /// always a multiple of the returned value (don't forget the trip count could
6404 /// very well be zero as well!).
6405 ///
6406 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6407 /// multiple of a constant (which is also the case if the trip count is simply
6408 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6409 /// if the trip count is very large (>= 2^32).
6410 ///
6411 /// As explained in the comments for getSmallConstantTripCount, this assumes
6412 /// that control exits the loop via ExitingBlock.
6413 unsigned
6414 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6415                                               BasicBlock *ExitingBlock) {
6416   assert(ExitingBlock && "Must pass a non-null exiting block!");
6417   assert(L->isLoopExiting(ExitingBlock) &&
6418          "Exiting block must actually branch out of the loop!");
6419   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6420   if (ExitCount == getCouldNotCompute())
6421     return 1;
6422 
6423   // Get the trip count from the BE count by adding 1.
6424   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6425 
6426   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6427   if (!TC)
6428     // Attempt to factor more general cases. Returns the greatest power of
6429     // two divisor. If overflow happens, the trip count expression is still
6430     // divisible by the greatest power of 2 divisor returned.
6431     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6432 
6433   ConstantInt *Result = TC->getValue();
6434 
6435   // Guard against huge trip counts (this requires checking
6436   // for zero to handle the case where the trip count == -1 and the
6437   // addition wraps).
6438   if (!Result || Result->getValue().getActiveBits() > 32 ||
6439       Result->getValue().getActiveBits() == 0)
6440     return 1;
6441 
6442   return (unsigned)Result->getZExtValue();
6443 }
6444 
6445 /// Get the expression for the number of loop iterations for which this loop is
6446 /// guaranteed not to exit via ExitingBlock. Otherwise return
6447 /// SCEVCouldNotCompute.
6448 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6449                                           BasicBlock *ExitingBlock) {
6450   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6451 }
6452 
6453 const SCEV *
6454 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6455                                                  SCEVUnionPredicate &Preds) {
6456   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6457 }
6458 
6459 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6460   return getBackedgeTakenInfo(L).getExact(L, this);
6461 }
6462 
6463 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6464 /// known never to be less than the actual backedge taken count.
6465 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6466   return getBackedgeTakenInfo(L).getMax(this);
6467 }
6468 
6469 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6470   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6471 }
6472 
6473 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6474 static void
6475 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6476   BasicBlock *Header = L->getHeader();
6477 
6478   // Push all Loop-header PHIs onto the Worklist stack.
6479   for (PHINode &PN : Header->phis())
6480     Worklist.push_back(&PN);
6481 }
6482 
6483 const ScalarEvolution::BackedgeTakenInfo &
6484 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6485   auto &BTI = getBackedgeTakenInfo(L);
6486   if (BTI.hasFullInfo())
6487     return BTI;
6488 
6489   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6490 
6491   if (!Pair.second)
6492     return Pair.first->second;
6493 
6494   BackedgeTakenInfo Result =
6495       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6496 
6497   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6498 }
6499 
6500 const ScalarEvolution::BackedgeTakenInfo &
6501 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6502   // Initially insert an invalid entry for this loop. If the insertion
6503   // succeeds, proceed to actually compute a backedge-taken count and
6504   // update the value. The temporary CouldNotCompute value tells SCEV
6505   // code elsewhere that it shouldn't attempt to request a new
6506   // backedge-taken count, which could result in infinite recursion.
6507   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6508       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6509   if (!Pair.second)
6510     return Pair.first->second;
6511 
6512   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6513   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6514   // must be cleared in this scope.
6515   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6516 
6517   // In product build, there are no usage of statistic.
6518   (void)NumTripCountsComputed;
6519   (void)NumTripCountsNotComputed;
6520 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6521   const SCEV *BEExact = Result.getExact(L, this);
6522   if (BEExact != getCouldNotCompute()) {
6523     assert(isLoopInvariant(BEExact, L) &&
6524            isLoopInvariant(Result.getMax(this), L) &&
6525            "Computed backedge-taken count isn't loop invariant for loop!");
6526     ++NumTripCountsComputed;
6527   }
6528   else if (Result.getMax(this) == getCouldNotCompute() &&
6529            isa<PHINode>(L->getHeader()->begin())) {
6530     // Only count loops that have phi nodes as not being computable.
6531     ++NumTripCountsNotComputed;
6532   }
6533 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6534 
6535   // Now that we know more about the trip count for this loop, forget any
6536   // existing SCEV values for PHI nodes in this loop since they are only
6537   // conservative estimates made without the benefit of trip count
6538   // information. This is similar to the code in forgetLoop, except that
6539   // it handles SCEVUnknown PHI nodes specially.
6540   if (Result.hasAnyInfo()) {
6541     SmallVector<Instruction *, 16> Worklist;
6542     PushLoopPHIs(L, Worklist);
6543 
6544     SmallPtrSet<Instruction *, 8> Discovered;
6545     while (!Worklist.empty()) {
6546       Instruction *I = Worklist.pop_back_val();
6547 
6548       ValueExprMapType::iterator It =
6549         ValueExprMap.find_as(static_cast<Value *>(I));
6550       if (It != ValueExprMap.end()) {
6551         const SCEV *Old = It->second;
6552 
6553         // SCEVUnknown for a PHI either means that it has an unrecognized
6554         // structure, or it's a PHI that's in the progress of being computed
6555         // by createNodeForPHI.  In the former case, additional loop trip
6556         // count information isn't going to change anything. In the later
6557         // case, createNodeForPHI will perform the necessary updates on its
6558         // own when it gets to that point.
6559         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6560           eraseValueFromMap(It->first);
6561           forgetMemoizedResults(Old);
6562         }
6563         if (PHINode *PN = dyn_cast<PHINode>(I))
6564           ConstantEvolutionLoopExitValue.erase(PN);
6565       }
6566 
6567       // Since we don't need to invalidate anything for correctness and we're
6568       // only invalidating to make SCEV's results more precise, we get to stop
6569       // early to avoid invalidating too much.  This is especially important in
6570       // cases like:
6571       //
6572       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6573       // loop0:
6574       //   %pn0 = phi
6575       //   ...
6576       // loop1:
6577       //   %pn1 = phi
6578       //   ...
6579       //
6580       // where both loop0 and loop1's backedge taken count uses the SCEV
6581       // expression for %v.  If we don't have the early stop below then in cases
6582       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6583       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6584       // count for loop1, effectively nullifying SCEV's trip count cache.
6585       for (auto *U : I->users())
6586         if (auto *I = dyn_cast<Instruction>(U)) {
6587           auto *LoopForUser = LI.getLoopFor(I->getParent());
6588           if (LoopForUser && L->contains(LoopForUser) &&
6589               Discovered.insert(I).second)
6590             Worklist.push_back(I);
6591         }
6592     }
6593   }
6594 
6595   // Re-lookup the insert position, since the call to
6596   // computeBackedgeTakenCount above could result in a
6597   // recusive call to getBackedgeTakenInfo (on a different
6598   // loop), which would invalidate the iterator computed
6599   // earlier.
6600   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6601 }
6602 
6603 void ScalarEvolution::forgetLoop(const Loop *L) {
6604   // Drop any stored trip count value.
6605   auto RemoveLoopFromBackedgeMap =
6606       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6607         auto BTCPos = Map.find(L);
6608         if (BTCPos != Map.end()) {
6609           BTCPos->second.clear();
6610           Map.erase(BTCPos);
6611         }
6612       };
6613 
6614   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6615   SmallVector<Instruction *, 32> Worklist;
6616   SmallPtrSet<Instruction *, 16> Visited;
6617 
6618   // Iterate over all the loops and sub-loops to drop SCEV information.
6619   while (!LoopWorklist.empty()) {
6620     auto *CurrL = LoopWorklist.pop_back_val();
6621 
6622     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6623     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6624 
6625     // Drop information about predicated SCEV rewrites for this loop.
6626     for (auto I = PredicatedSCEVRewrites.begin();
6627          I != PredicatedSCEVRewrites.end();) {
6628       std::pair<const SCEV *, const Loop *> Entry = I->first;
6629       if (Entry.second == CurrL)
6630         PredicatedSCEVRewrites.erase(I++);
6631       else
6632         ++I;
6633     }
6634 
6635     auto LoopUsersItr = LoopUsers.find(CurrL);
6636     if (LoopUsersItr != LoopUsers.end()) {
6637       for (auto *S : LoopUsersItr->second)
6638         forgetMemoizedResults(S);
6639       LoopUsers.erase(LoopUsersItr);
6640     }
6641 
6642     // Drop information about expressions based on loop-header PHIs.
6643     PushLoopPHIs(CurrL, Worklist);
6644 
6645     while (!Worklist.empty()) {
6646       Instruction *I = Worklist.pop_back_val();
6647       if (!Visited.insert(I).second)
6648         continue;
6649 
6650       ValueExprMapType::iterator It =
6651           ValueExprMap.find_as(static_cast<Value *>(I));
6652       if (It != ValueExprMap.end()) {
6653         eraseValueFromMap(It->first);
6654         forgetMemoizedResults(It->second);
6655         if (PHINode *PN = dyn_cast<PHINode>(I))
6656           ConstantEvolutionLoopExitValue.erase(PN);
6657       }
6658 
6659       PushDefUseChildren(I, Worklist);
6660     }
6661 
6662     LoopPropertiesCache.erase(CurrL);
6663     // Forget all contained loops too, to avoid dangling entries in the
6664     // ValuesAtScopes map.
6665     LoopWorklist.append(CurrL->begin(), CurrL->end());
6666   }
6667 }
6668 
6669 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6670   while (Loop *Parent = L->getParentLoop())
6671     L = Parent;
6672   forgetLoop(L);
6673 }
6674 
6675 void ScalarEvolution::forgetValue(Value *V) {
6676   Instruction *I = dyn_cast<Instruction>(V);
6677   if (!I) return;
6678 
6679   // Drop information about expressions based on loop-header PHIs.
6680   SmallVector<Instruction *, 16> Worklist;
6681   Worklist.push_back(I);
6682 
6683   SmallPtrSet<Instruction *, 8> Visited;
6684   while (!Worklist.empty()) {
6685     I = Worklist.pop_back_val();
6686     if (!Visited.insert(I).second)
6687       continue;
6688 
6689     ValueExprMapType::iterator It =
6690       ValueExprMap.find_as(static_cast<Value *>(I));
6691     if (It != ValueExprMap.end()) {
6692       eraseValueFromMap(It->first);
6693       forgetMemoizedResults(It->second);
6694       if (PHINode *PN = dyn_cast<PHINode>(I))
6695         ConstantEvolutionLoopExitValue.erase(PN);
6696     }
6697 
6698     PushDefUseChildren(I, Worklist);
6699   }
6700 }
6701 
6702 /// Get the exact loop backedge taken count considering all loop exits. A
6703 /// computable result can only be returned for loops with all exiting blocks
6704 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6705 /// is never skipped. This is a valid assumption as long as the loop exits via
6706 /// that test. For precise results, it is the caller's responsibility to specify
6707 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6708 const SCEV *
6709 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6710                                              SCEVUnionPredicate *Preds) const {
6711   // If any exits were not computable, the loop is not computable.
6712   if (!isComplete() || ExitNotTaken.empty())
6713     return SE->getCouldNotCompute();
6714 
6715   const BasicBlock *Latch = L->getLoopLatch();
6716   // All exiting blocks we have collected must dominate the only backedge.
6717   if (!Latch)
6718     return SE->getCouldNotCompute();
6719 
6720   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6721   // count is simply a minimum out of all these calculated exit counts.
6722   SmallVector<const SCEV *, 2> Ops;
6723   for (auto &ENT : ExitNotTaken) {
6724     const SCEV *BECount = ENT.ExactNotTaken;
6725     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6726     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6727            "We should only have known counts for exiting blocks that dominate "
6728            "latch!");
6729 
6730     Ops.push_back(BECount);
6731 
6732     if (Preds && !ENT.hasAlwaysTruePredicate())
6733       Preds->add(ENT.Predicate.get());
6734 
6735     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6736            "Predicate should be always true!");
6737   }
6738 
6739   return SE->getUMinFromMismatchedTypes(Ops);
6740 }
6741 
6742 /// Get the exact not taken count for this loop exit.
6743 const SCEV *
6744 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6745                                              ScalarEvolution *SE) const {
6746   for (auto &ENT : ExitNotTaken)
6747     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6748       return ENT.ExactNotTaken;
6749 
6750   return SE->getCouldNotCompute();
6751 }
6752 
6753 /// getMax - Get the max backedge taken count for the loop.
6754 const SCEV *
6755 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6756   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6757     return !ENT.hasAlwaysTruePredicate();
6758   };
6759 
6760   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6761     return SE->getCouldNotCompute();
6762 
6763   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6764          "No point in having a non-constant max backedge taken count!");
6765   return getMax();
6766 }
6767 
6768 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6769   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6770     return !ENT.hasAlwaysTruePredicate();
6771   };
6772   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6773 }
6774 
6775 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6776                                                     ScalarEvolution *SE) const {
6777   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6778       SE->hasOperand(getMax(), S))
6779     return true;
6780 
6781   for (auto &ENT : ExitNotTaken)
6782     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6783         SE->hasOperand(ENT.ExactNotTaken, S))
6784       return true;
6785 
6786   return false;
6787 }
6788 
6789 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6790     : ExactNotTaken(E), MaxNotTaken(E) {
6791   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6792           isa<SCEVConstant>(MaxNotTaken)) &&
6793          "No point in having a non-constant max backedge taken count!");
6794 }
6795 
6796 ScalarEvolution::ExitLimit::ExitLimit(
6797     const SCEV *E, const SCEV *M, bool MaxOrZero,
6798     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6799     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6800   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6801           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6802          "Exact is not allowed to be less precise than Max");
6803   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6804           isa<SCEVConstant>(MaxNotTaken)) &&
6805          "No point in having a non-constant max backedge taken count!");
6806   for (auto *PredSet : PredSetList)
6807     for (auto *P : *PredSet)
6808       addPredicate(P);
6809 }
6810 
6811 ScalarEvolution::ExitLimit::ExitLimit(
6812     const SCEV *E, const SCEV *M, bool MaxOrZero,
6813     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6814     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6815   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6816           isa<SCEVConstant>(MaxNotTaken)) &&
6817          "No point in having a non-constant max backedge taken count!");
6818 }
6819 
6820 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6821                                       bool MaxOrZero)
6822     : ExitLimit(E, M, MaxOrZero, None) {
6823   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6824           isa<SCEVConstant>(MaxNotTaken)) &&
6825          "No point in having a non-constant max backedge taken count!");
6826 }
6827 
6828 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6829 /// computable exit into a persistent ExitNotTakenInfo array.
6830 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6831     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6832         &&ExitCounts,
6833     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6834     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6835   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6836 
6837   ExitNotTaken.reserve(ExitCounts.size());
6838   std::transform(
6839       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6840       [&](const EdgeExitInfo &EEI) {
6841         BasicBlock *ExitBB = EEI.first;
6842         const ExitLimit &EL = EEI.second;
6843         if (EL.Predicates.empty())
6844           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6845 
6846         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6847         for (auto *Pred : EL.Predicates)
6848           Predicate->add(Pred);
6849 
6850         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6851       });
6852   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6853          "No point in having a non-constant max backedge taken count!");
6854 }
6855 
6856 /// Invalidate this result and free the ExitNotTakenInfo array.
6857 void ScalarEvolution::BackedgeTakenInfo::clear() {
6858   ExitNotTaken.clear();
6859 }
6860 
6861 /// Compute the number of times the backedge of the specified loop will execute.
6862 ScalarEvolution::BackedgeTakenInfo
6863 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6864                                            bool AllowPredicates) {
6865   SmallVector<BasicBlock *, 8> ExitingBlocks;
6866   L->getExitingBlocks(ExitingBlocks);
6867 
6868   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6869 
6870   SmallVector<EdgeExitInfo, 4> ExitCounts;
6871   bool CouldComputeBECount = true;
6872   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6873   const SCEV *MustExitMaxBECount = nullptr;
6874   const SCEV *MayExitMaxBECount = nullptr;
6875   bool MustExitMaxOrZero = false;
6876 
6877   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6878   // and compute maxBECount.
6879   // Do a union of all the predicates here.
6880   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6881     BasicBlock *ExitBB = ExitingBlocks[i];
6882     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6883 
6884     assert((AllowPredicates || EL.Predicates.empty()) &&
6885            "Predicated exit limit when predicates are not allowed!");
6886 
6887     // 1. For each exit that can be computed, add an entry to ExitCounts.
6888     // CouldComputeBECount is true only if all exits can be computed.
6889     if (EL.ExactNotTaken == getCouldNotCompute())
6890       // We couldn't compute an exact value for this exit, so
6891       // we won't be able to compute an exact value for the loop.
6892       CouldComputeBECount = false;
6893     else
6894       ExitCounts.emplace_back(ExitBB, EL);
6895 
6896     // 2. Derive the loop's MaxBECount from each exit's max number of
6897     // non-exiting iterations. Partition the loop exits into two kinds:
6898     // LoopMustExits and LoopMayExits.
6899     //
6900     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6901     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6902     // MaxBECount is the minimum EL.MaxNotTaken of computable
6903     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6904     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6905     // computable EL.MaxNotTaken.
6906     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6907         DT.dominates(ExitBB, Latch)) {
6908       if (!MustExitMaxBECount) {
6909         MustExitMaxBECount = EL.MaxNotTaken;
6910         MustExitMaxOrZero = EL.MaxOrZero;
6911       } else {
6912         MustExitMaxBECount =
6913             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6914       }
6915     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6916       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6917         MayExitMaxBECount = EL.MaxNotTaken;
6918       else {
6919         MayExitMaxBECount =
6920             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6921       }
6922     }
6923   }
6924   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6925     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6926   // The loop backedge will be taken the maximum or zero times if there's
6927   // a single exit that must be taken the maximum or zero times.
6928   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6929   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6930                            MaxBECount, MaxOrZero);
6931 }
6932 
6933 ScalarEvolution::ExitLimit
6934 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6935                                       bool AllowPredicates) {
6936   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
6937   // If our exiting block does not dominate the latch, then its connection with
6938   // loop's exit limit may be far from trivial.
6939   const BasicBlock *Latch = L->getLoopLatch();
6940   if (!Latch || !DT.dominates(ExitingBlock, Latch))
6941     return getCouldNotCompute();
6942 
6943   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6944   TerminatorInst *Term = ExitingBlock->getTerminator();
6945   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6946     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6947     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
6948     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
6949            "It should have one successor in loop and one exit block!");
6950     // Proceed to the next level to examine the exit condition expression.
6951     return computeExitLimitFromCond(
6952         L, BI->getCondition(), ExitIfTrue,
6953         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6954   }
6955 
6956   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
6957     // For switch, make sure that there is a single exit from the loop.
6958     BasicBlock *Exit = nullptr;
6959     for (auto *SBB : successors(ExitingBlock))
6960       if (!L->contains(SBB)) {
6961         if (Exit) // Multiple exit successors.
6962           return getCouldNotCompute();
6963         Exit = SBB;
6964       }
6965     assert(Exit && "Exiting block must have at least one exit");
6966     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6967                                                 /*ControlsExit=*/IsOnlyExit);
6968   }
6969 
6970   return getCouldNotCompute();
6971 }
6972 
6973 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6974     const Loop *L, Value *ExitCond, bool ExitIfTrue,
6975     bool ControlsExit, bool AllowPredicates) {
6976   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
6977   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
6978                                         ControlsExit, AllowPredicates);
6979 }
6980 
6981 Optional<ScalarEvolution::ExitLimit>
6982 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6983                                       bool ExitIfTrue, bool ControlsExit,
6984                                       bool AllowPredicates) {
6985   (void)this->L;
6986   (void)this->ExitIfTrue;
6987   (void)this->AllowPredicates;
6988 
6989   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
6990          this->AllowPredicates == AllowPredicates &&
6991          "Variance in assumed invariant key components!");
6992   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6993   if (Itr == TripCountMap.end())
6994     return None;
6995   return Itr->second;
6996 }
6997 
6998 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6999                                              bool ExitIfTrue,
7000                                              bool ControlsExit,
7001                                              bool AllowPredicates,
7002                                              const ExitLimit &EL) {
7003   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7004          this->AllowPredicates == AllowPredicates &&
7005          "Variance in assumed invariant key components!");
7006 
7007   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7008   assert(InsertResult.second && "Expected successful insertion!");
7009   (void)InsertResult;
7010   (void)ExitIfTrue;
7011 }
7012 
7013 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7014     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7015     bool ControlsExit, bool AllowPredicates) {
7016 
7017   if (auto MaybeEL =
7018           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7019     return *MaybeEL;
7020 
7021   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7022                                               ControlsExit, AllowPredicates);
7023   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7024   return EL;
7025 }
7026 
7027 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7028     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7029     bool ControlsExit, bool AllowPredicates) {
7030   // Check if the controlling expression for this loop is an And or Or.
7031   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7032     if (BO->getOpcode() == Instruction::And) {
7033       // Recurse on the operands of the and.
7034       bool EitherMayExit = !ExitIfTrue;
7035       ExitLimit EL0 = computeExitLimitFromCondCached(
7036           Cache, L, BO->getOperand(0), ExitIfTrue,
7037           ControlsExit && !EitherMayExit, AllowPredicates);
7038       ExitLimit EL1 = computeExitLimitFromCondCached(
7039           Cache, L, BO->getOperand(1), ExitIfTrue,
7040           ControlsExit && !EitherMayExit, AllowPredicates);
7041       const SCEV *BECount = getCouldNotCompute();
7042       const SCEV *MaxBECount = getCouldNotCompute();
7043       if (EitherMayExit) {
7044         // Both conditions must be true for the loop to continue executing.
7045         // Choose the less conservative count.
7046         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7047             EL1.ExactNotTaken == getCouldNotCompute())
7048           BECount = getCouldNotCompute();
7049         else
7050           BECount =
7051               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7052         if (EL0.MaxNotTaken == getCouldNotCompute())
7053           MaxBECount = EL1.MaxNotTaken;
7054         else if (EL1.MaxNotTaken == getCouldNotCompute())
7055           MaxBECount = EL0.MaxNotTaken;
7056         else
7057           MaxBECount =
7058               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7059       } else {
7060         // Both conditions must be true at the same time for the loop to exit.
7061         // For now, be conservative.
7062         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7063           MaxBECount = EL0.MaxNotTaken;
7064         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7065           BECount = EL0.ExactNotTaken;
7066       }
7067 
7068       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7069       // to be more aggressive when computing BECount than when computing
7070       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7071       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7072       // to not.
7073       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7074           !isa<SCEVCouldNotCompute>(BECount))
7075         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7076 
7077       return ExitLimit(BECount, MaxBECount, false,
7078                        {&EL0.Predicates, &EL1.Predicates});
7079     }
7080     if (BO->getOpcode() == Instruction::Or) {
7081       // Recurse on the operands of the or.
7082       bool EitherMayExit = ExitIfTrue;
7083       ExitLimit EL0 = computeExitLimitFromCondCached(
7084           Cache, L, BO->getOperand(0), ExitIfTrue,
7085           ControlsExit && !EitherMayExit, AllowPredicates);
7086       ExitLimit EL1 = computeExitLimitFromCondCached(
7087           Cache, L, BO->getOperand(1), ExitIfTrue,
7088           ControlsExit && !EitherMayExit, AllowPredicates);
7089       const SCEV *BECount = getCouldNotCompute();
7090       const SCEV *MaxBECount = getCouldNotCompute();
7091       if (EitherMayExit) {
7092         // Both conditions must be false for the loop to continue executing.
7093         // Choose the less conservative count.
7094         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7095             EL1.ExactNotTaken == getCouldNotCompute())
7096           BECount = getCouldNotCompute();
7097         else
7098           BECount =
7099               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7100         if (EL0.MaxNotTaken == getCouldNotCompute())
7101           MaxBECount = EL1.MaxNotTaken;
7102         else if (EL1.MaxNotTaken == getCouldNotCompute())
7103           MaxBECount = EL0.MaxNotTaken;
7104         else
7105           MaxBECount =
7106               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7107       } else {
7108         // Both conditions must be false at the same time for the loop to exit.
7109         // For now, be conservative.
7110         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7111           MaxBECount = EL0.MaxNotTaken;
7112         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7113           BECount = EL0.ExactNotTaken;
7114       }
7115 
7116       return ExitLimit(BECount, MaxBECount, false,
7117                        {&EL0.Predicates, &EL1.Predicates});
7118     }
7119   }
7120 
7121   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7122   // Proceed to the next level to examine the icmp.
7123   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7124     ExitLimit EL =
7125         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7126     if (EL.hasFullInfo() || !AllowPredicates)
7127       return EL;
7128 
7129     // Try again, but use SCEV predicates this time.
7130     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7131                                     /*AllowPredicates=*/true);
7132   }
7133 
7134   // Check for a constant condition. These are normally stripped out by
7135   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7136   // preserve the CFG and is temporarily leaving constant conditions
7137   // in place.
7138   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7139     if (ExitIfTrue == !CI->getZExtValue())
7140       // The backedge is always taken.
7141       return getCouldNotCompute();
7142     else
7143       // The backedge is never taken.
7144       return getZero(CI->getType());
7145   }
7146 
7147   // If it's not an integer or pointer comparison then compute it the hard way.
7148   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7149 }
7150 
7151 ScalarEvolution::ExitLimit
7152 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7153                                           ICmpInst *ExitCond,
7154                                           bool ExitIfTrue,
7155                                           bool ControlsExit,
7156                                           bool AllowPredicates) {
7157   // If the condition was exit on true, convert the condition to exit on false
7158   ICmpInst::Predicate Pred;
7159   if (!ExitIfTrue)
7160     Pred = ExitCond->getPredicate();
7161   else
7162     Pred = ExitCond->getInversePredicate();
7163   const ICmpInst::Predicate OriginalPred = Pred;
7164 
7165   // Handle common loops like: for (X = "string"; *X; ++X)
7166   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7167     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7168       ExitLimit ItCnt =
7169         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7170       if (ItCnt.hasAnyInfo())
7171         return ItCnt;
7172     }
7173 
7174   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7175   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7176 
7177   // Try to evaluate any dependencies out of the loop.
7178   LHS = getSCEVAtScope(LHS, L);
7179   RHS = getSCEVAtScope(RHS, L);
7180 
7181   // At this point, we would like to compute how many iterations of the
7182   // loop the predicate will return true for these inputs.
7183   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7184     // If there is a loop-invariant, force it into the RHS.
7185     std::swap(LHS, RHS);
7186     Pred = ICmpInst::getSwappedPredicate(Pred);
7187   }
7188 
7189   // Simplify the operands before analyzing them.
7190   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7191 
7192   // If we have a comparison of a chrec against a constant, try to use value
7193   // ranges to answer this query.
7194   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7195     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7196       if (AddRec->getLoop() == L) {
7197         // Form the constant range.
7198         ConstantRange CompRange =
7199             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7200 
7201         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7202         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7203       }
7204 
7205   switch (Pred) {
7206   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7207     // Convert to: while (X-Y != 0)
7208     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7209                                 AllowPredicates);
7210     if (EL.hasAnyInfo()) return EL;
7211     break;
7212   }
7213   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7214     // Convert to: while (X-Y == 0)
7215     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7216     if (EL.hasAnyInfo()) return EL;
7217     break;
7218   }
7219   case ICmpInst::ICMP_SLT:
7220   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7221     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7222     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7223                                     AllowPredicates);
7224     if (EL.hasAnyInfo()) return EL;
7225     break;
7226   }
7227   case ICmpInst::ICMP_SGT:
7228   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7229     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7230     ExitLimit EL =
7231         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7232                             AllowPredicates);
7233     if (EL.hasAnyInfo()) return EL;
7234     break;
7235   }
7236   default:
7237     break;
7238   }
7239 
7240   auto *ExhaustiveCount =
7241       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7242 
7243   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7244     return ExhaustiveCount;
7245 
7246   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7247                                       ExitCond->getOperand(1), L, OriginalPred);
7248 }
7249 
7250 ScalarEvolution::ExitLimit
7251 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7252                                                       SwitchInst *Switch,
7253                                                       BasicBlock *ExitingBlock,
7254                                                       bool ControlsExit) {
7255   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7256 
7257   // Give up if the exit is the default dest of a switch.
7258   if (Switch->getDefaultDest() == ExitingBlock)
7259     return getCouldNotCompute();
7260 
7261   assert(L->contains(Switch->getDefaultDest()) &&
7262          "Default case must not exit the loop!");
7263   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7264   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7265 
7266   // while (X != Y) --> while (X-Y != 0)
7267   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7268   if (EL.hasAnyInfo())
7269     return EL;
7270 
7271   return getCouldNotCompute();
7272 }
7273 
7274 static ConstantInt *
7275 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7276                                 ScalarEvolution &SE) {
7277   const SCEV *InVal = SE.getConstant(C);
7278   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7279   assert(isa<SCEVConstant>(Val) &&
7280          "Evaluation of SCEV at constant didn't fold correctly?");
7281   return cast<SCEVConstant>(Val)->getValue();
7282 }
7283 
7284 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7285 /// compute the backedge execution count.
7286 ScalarEvolution::ExitLimit
7287 ScalarEvolution::computeLoadConstantCompareExitLimit(
7288   LoadInst *LI,
7289   Constant *RHS,
7290   const Loop *L,
7291   ICmpInst::Predicate predicate) {
7292   if (LI->isVolatile()) return getCouldNotCompute();
7293 
7294   // Check to see if the loaded pointer is a getelementptr of a global.
7295   // TODO: Use SCEV instead of manually grubbing with GEPs.
7296   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7297   if (!GEP) return getCouldNotCompute();
7298 
7299   // Make sure that it is really a constant global we are gepping, with an
7300   // initializer, and make sure the first IDX is really 0.
7301   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7302   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7303       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7304       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7305     return getCouldNotCompute();
7306 
7307   // Okay, we allow one non-constant index into the GEP instruction.
7308   Value *VarIdx = nullptr;
7309   std::vector<Constant*> Indexes;
7310   unsigned VarIdxNum = 0;
7311   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7312     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7313       Indexes.push_back(CI);
7314     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7315       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7316       VarIdx = GEP->getOperand(i);
7317       VarIdxNum = i-2;
7318       Indexes.push_back(nullptr);
7319     }
7320 
7321   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7322   if (!VarIdx)
7323     return getCouldNotCompute();
7324 
7325   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7326   // Check to see if X is a loop variant variable value now.
7327   const SCEV *Idx = getSCEV(VarIdx);
7328   Idx = getSCEVAtScope(Idx, L);
7329 
7330   // We can only recognize very limited forms of loop index expressions, in
7331   // particular, only affine AddRec's like {C1,+,C2}.
7332   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7333   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7334       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7335       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7336     return getCouldNotCompute();
7337 
7338   unsigned MaxSteps = MaxBruteForceIterations;
7339   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7340     ConstantInt *ItCst = ConstantInt::get(
7341                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7342     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7343 
7344     // Form the GEP offset.
7345     Indexes[VarIdxNum] = Val;
7346 
7347     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7348                                                          Indexes);
7349     if (!Result) break;  // Cannot compute!
7350 
7351     // Evaluate the condition for this iteration.
7352     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7353     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7354     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7355       ++NumArrayLenItCounts;
7356       return getConstant(ItCst);   // Found terminating iteration!
7357     }
7358   }
7359   return getCouldNotCompute();
7360 }
7361 
7362 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7363     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7364   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7365   if (!RHS)
7366     return getCouldNotCompute();
7367 
7368   const BasicBlock *Latch = L->getLoopLatch();
7369   if (!Latch)
7370     return getCouldNotCompute();
7371 
7372   const BasicBlock *Predecessor = L->getLoopPredecessor();
7373   if (!Predecessor)
7374     return getCouldNotCompute();
7375 
7376   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7377   // Return LHS in OutLHS and shift_opt in OutOpCode.
7378   auto MatchPositiveShift =
7379       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7380 
7381     using namespace PatternMatch;
7382 
7383     ConstantInt *ShiftAmt;
7384     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7385       OutOpCode = Instruction::LShr;
7386     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7387       OutOpCode = Instruction::AShr;
7388     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7389       OutOpCode = Instruction::Shl;
7390     else
7391       return false;
7392 
7393     return ShiftAmt->getValue().isStrictlyPositive();
7394   };
7395 
7396   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7397   //
7398   // loop:
7399   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7400   //   %iv.shifted = lshr i32 %iv, <positive constant>
7401   //
7402   // Return true on a successful match.  Return the corresponding PHI node (%iv
7403   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7404   auto MatchShiftRecurrence =
7405       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7406     Optional<Instruction::BinaryOps> PostShiftOpCode;
7407 
7408     {
7409       Instruction::BinaryOps OpC;
7410       Value *V;
7411 
7412       // If we encounter a shift instruction, "peel off" the shift operation,
7413       // and remember that we did so.  Later when we inspect %iv's backedge
7414       // value, we will make sure that the backedge value uses the same
7415       // operation.
7416       //
7417       // Note: the peeled shift operation does not have to be the same
7418       // instruction as the one feeding into the PHI's backedge value.  We only
7419       // really care about it being the same *kind* of shift instruction --
7420       // that's all that is required for our later inferences to hold.
7421       if (MatchPositiveShift(LHS, V, OpC)) {
7422         PostShiftOpCode = OpC;
7423         LHS = V;
7424       }
7425     }
7426 
7427     PNOut = dyn_cast<PHINode>(LHS);
7428     if (!PNOut || PNOut->getParent() != L->getHeader())
7429       return false;
7430 
7431     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7432     Value *OpLHS;
7433 
7434     return
7435         // The backedge value for the PHI node must be a shift by a positive
7436         // amount
7437         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7438 
7439         // of the PHI node itself
7440         OpLHS == PNOut &&
7441 
7442         // and the kind of shift should be match the kind of shift we peeled
7443         // off, if any.
7444         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7445   };
7446 
7447   PHINode *PN;
7448   Instruction::BinaryOps OpCode;
7449   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7450     return getCouldNotCompute();
7451 
7452   const DataLayout &DL = getDataLayout();
7453 
7454   // The key rationale for this optimization is that for some kinds of shift
7455   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7456   // within a finite number of iterations.  If the condition guarding the
7457   // backedge (in the sense that the backedge is taken if the condition is true)
7458   // is false for the value the shift recurrence stabilizes to, then we know
7459   // that the backedge is taken only a finite number of times.
7460 
7461   ConstantInt *StableValue = nullptr;
7462   switch (OpCode) {
7463   default:
7464     llvm_unreachable("Impossible case!");
7465 
7466   case Instruction::AShr: {
7467     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7468     // bitwidth(K) iterations.
7469     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7470     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7471                                        Predecessor->getTerminator(), &DT);
7472     auto *Ty = cast<IntegerType>(RHS->getType());
7473     if (Known.isNonNegative())
7474       StableValue = ConstantInt::get(Ty, 0);
7475     else if (Known.isNegative())
7476       StableValue = ConstantInt::get(Ty, -1, true);
7477     else
7478       return getCouldNotCompute();
7479 
7480     break;
7481   }
7482   case Instruction::LShr:
7483   case Instruction::Shl:
7484     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7485     // stabilize to 0 in at most bitwidth(K) iterations.
7486     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7487     break;
7488   }
7489 
7490   auto *Result =
7491       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7492   assert(Result->getType()->isIntegerTy(1) &&
7493          "Otherwise cannot be an operand to a branch instruction");
7494 
7495   if (Result->isZeroValue()) {
7496     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7497     const SCEV *UpperBound =
7498         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7499     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7500   }
7501 
7502   return getCouldNotCompute();
7503 }
7504 
7505 /// Return true if we can constant fold an instruction of the specified type,
7506 /// assuming that all operands were constants.
7507 static bool CanConstantFold(const Instruction *I) {
7508   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7509       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7510       isa<LoadInst>(I))
7511     return true;
7512 
7513   if (const CallInst *CI = dyn_cast<CallInst>(I))
7514     if (const Function *F = CI->getCalledFunction())
7515       return canConstantFoldCallTo(CI, F);
7516   return false;
7517 }
7518 
7519 /// Determine whether this instruction can constant evolve within this loop
7520 /// assuming its operands can all constant evolve.
7521 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7522   // An instruction outside of the loop can't be derived from a loop PHI.
7523   if (!L->contains(I)) return false;
7524 
7525   if (isa<PHINode>(I)) {
7526     // We don't currently keep track of the control flow needed to evaluate
7527     // PHIs, so we cannot handle PHIs inside of loops.
7528     return L->getHeader() == I->getParent();
7529   }
7530 
7531   // If we won't be able to constant fold this expression even if the operands
7532   // are constants, bail early.
7533   return CanConstantFold(I);
7534 }
7535 
7536 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7537 /// recursing through each instruction operand until reaching a loop header phi.
7538 static PHINode *
7539 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7540                                DenseMap<Instruction *, PHINode *> &PHIMap,
7541                                unsigned Depth) {
7542   if (Depth > MaxConstantEvolvingDepth)
7543     return nullptr;
7544 
7545   // Otherwise, we can evaluate this instruction if all of its operands are
7546   // constant or derived from a PHI node themselves.
7547   PHINode *PHI = nullptr;
7548   for (Value *Op : UseInst->operands()) {
7549     if (isa<Constant>(Op)) continue;
7550 
7551     Instruction *OpInst = dyn_cast<Instruction>(Op);
7552     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7553 
7554     PHINode *P = dyn_cast<PHINode>(OpInst);
7555     if (!P)
7556       // If this operand is already visited, reuse the prior result.
7557       // We may have P != PHI if this is the deepest point at which the
7558       // inconsistent paths meet.
7559       P = PHIMap.lookup(OpInst);
7560     if (!P) {
7561       // Recurse and memoize the results, whether a phi is found or not.
7562       // This recursive call invalidates pointers into PHIMap.
7563       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7564       PHIMap[OpInst] = P;
7565     }
7566     if (!P)
7567       return nullptr;  // Not evolving from PHI
7568     if (PHI && PHI != P)
7569       return nullptr;  // Evolving from multiple different PHIs.
7570     PHI = P;
7571   }
7572   // This is a expression evolving from a constant PHI!
7573   return PHI;
7574 }
7575 
7576 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7577 /// in the loop that V is derived from.  We allow arbitrary operations along the
7578 /// way, but the operands of an operation must either be constants or a value
7579 /// derived from a constant PHI.  If this expression does not fit with these
7580 /// constraints, return null.
7581 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7582   Instruction *I = dyn_cast<Instruction>(V);
7583   if (!I || !canConstantEvolve(I, L)) return nullptr;
7584 
7585   if (PHINode *PN = dyn_cast<PHINode>(I))
7586     return PN;
7587 
7588   // Record non-constant instructions contained by the loop.
7589   DenseMap<Instruction *, PHINode *> PHIMap;
7590   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7591 }
7592 
7593 /// EvaluateExpression - Given an expression that passes the
7594 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7595 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7596 /// reason, return null.
7597 static Constant *EvaluateExpression(Value *V, const Loop *L,
7598                                     DenseMap<Instruction *, Constant *> &Vals,
7599                                     const DataLayout &DL,
7600                                     const TargetLibraryInfo *TLI) {
7601   // Convenient constant check, but redundant for recursive calls.
7602   if (Constant *C = dyn_cast<Constant>(V)) return C;
7603   Instruction *I = dyn_cast<Instruction>(V);
7604   if (!I) return nullptr;
7605 
7606   if (Constant *C = Vals.lookup(I)) return C;
7607 
7608   // An instruction inside the loop depends on a value outside the loop that we
7609   // weren't given a mapping for, or a value such as a call inside the loop.
7610   if (!canConstantEvolve(I, L)) return nullptr;
7611 
7612   // An unmapped PHI can be due to a branch or another loop inside this loop,
7613   // or due to this not being the initial iteration through a loop where we
7614   // couldn't compute the evolution of this particular PHI last time.
7615   if (isa<PHINode>(I)) return nullptr;
7616 
7617   std::vector<Constant*> Operands(I->getNumOperands());
7618 
7619   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7620     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7621     if (!Operand) {
7622       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7623       if (!Operands[i]) return nullptr;
7624       continue;
7625     }
7626     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7627     Vals[Operand] = C;
7628     if (!C) return nullptr;
7629     Operands[i] = C;
7630   }
7631 
7632   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7633     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7634                                            Operands[1], DL, TLI);
7635   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7636     if (!LI->isVolatile())
7637       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7638   }
7639   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7640 }
7641 
7642 
7643 // If every incoming value to PN except the one for BB is a specific Constant,
7644 // return that, else return nullptr.
7645 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7646   Constant *IncomingVal = nullptr;
7647 
7648   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7649     if (PN->getIncomingBlock(i) == BB)
7650       continue;
7651 
7652     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7653     if (!CurrentVal)
7654       return nullptr;
7655 
7656     if (IncomingVal != CurrentVal) {
7657       if (IncomingVal)
7658         return nullptr;
7659       IncomingVal = CurrentVal;
7660     }
7661   }
7662 
7663   return IncomingVal;
7664 }
7665 
7666 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7667 /// in the header of its containing loop, we know the loop executes a
7668 /// constant number of times, and the PHI node is just a recurrence
7669 /// involving constants, fold it.
7670 Constant *
7671 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7672                                                    const APInt &BEs,
7673                                                    const Loop *L) {
7674   auto I = ConstantEvolutionLoopExitValue.find(PN);
7675   if (I != ConstantEvolutionLoopExitValue.end())
7676     return I->second;
7677 
7678   if (BEs.ugt(MaxBruteForceIterations))
7679     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7680 
7681   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7682 
7683   DenseMap<Instruction *, Constant *> CurrentIterVals;
7684   BasicBlock *Header = L->getHeader();
7685   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7686 
7687   BasicBlock *Latch = L->getLoopLatch();
7688   if (!Latch)
7689     return nullptr;
7690 
7691   for (PHINode &PHI : Header->phis()) {
7692     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7693       CurrentIterVals[&PHI] = StartCST;
7694   }
7695   if (!CurrentIterVals.count(PN))
7696     return RetVal = nullptr;
7697 
7698   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7699 
7700   // Execute the loop symbolically to determine the exit value.
7701   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7702          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7703 
7704   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7705   unsigned IterationNum = 0;
7706   const DataLayout &DL = getDataLayout();
7707   for (; ; ++IterationNum) {
7708     if (IterationNum == NumIterations)
7709       return RetVal = CurrentIterVals[PN];  // Got exit value!
7710 
7711     // Compute the value of the PHIs for the next iteration.
7712     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7713     DenseMap<Instruction *, Constant *> NextIterVals;
7714     Constant *NextPHI =
7715         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7716     if (!NextPHI)
7717       return nullptr;        // Couldn't evaluate!
7718     NextIterVals[PN] = NextPHI;
7719 
7720     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7721 
7722     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7723     // cease to be able to evaluate one of them or if they stop evolving,
7724     // because that doesn't necessarily prevent us from computing PN.
7725     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7726     for (const auto &I : CurrentIterVals) {
7727       PHINode *PHI = dyn_cast<PHINode>(I.first);
7728       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7729       PHIsToCompute.emplace_back(PHI, I.second);
7730     }
7731     // We use two distinct loops because EvaluateExpression may invalidate any
7732     // iterators into CurrentIterVals.
7733     for (const auto &I : PHIsToCompute) {
7734       PHINode *PHI = I.first;
7735       Constant *&NextPHI = NextIterVals[PHI];
7736       if (!NextPHI) {   // Not already computed.
7737         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7738         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7739       }
7740       if (NextPHI != I.second)
7741         StoppedEvolving = false;
7742     }
7743 
7744     // If all entries in CurrentIterVals == NextIterVals then we can stop
7745     // iterating, the loop can't continue to change.
7746     if (StoppedEvolving)
7747       return RetVal = CurrentIterVals[PN];
7748 
7749     CurrentIterVals.swap(NextIterVals);
7750   }
7751 }
7752 
7753 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7754                                                           Value *Cond,
7755                                                           bool ExitWhen) {
7756   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7757   if (!PN) return getCouldNotCompute();
7758 
7759   // If the loop is canonicalized, the PHI will have exactly two entries.
7760   // That's the only form we support here.
7761   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7762 
7763   DenseMap<Instruction *, Constant *> CurrentIterVals;
7764   BasicBlock *Header = L->getHeader();
7765   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7766 
7767   BasicBlock *Latch = L->getLoopLatch();
7768   assert(Latch && "Should follow from NumIncomingValues == 2!");
7769 
7770   for (PHINode &PHI : Header->phis()) {
7771     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7772       CurrentIterVals[&PHI] = StartCST;
7773   }
7774   if (!CurrentIterVals.count(PN))
7775     return getCouldNotCompute();
7776 
7777   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7778   // the loop symbolically to determine when the condition gets a value of
7779   // "ExitWhen".
7780   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7781   const DataLayout &DL = getDataLayout();
7782   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7783     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7784         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7785 
7786     // Couldn't symbolically evaluate.
7787     if (!CondVal) return getCouldNotCompute();
7788 
7789     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7790       ++NumBruteForceTripCountsComputed;
7791       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7792     }
7793 
7794     // Update all the PHI nodes for the next iteration.
7795     DenseMap<Instruction *, Constant *> NextIterVals;
7796 
7797     // Create a list of which PHIs we need to compute. We want to do this before
7798     // calling EvaluateExpression on them because that may invalidate iterators
7799     // into CurrentIterVals.
7800     SmallVector<PHINode *, 8> PHIsToCompute;
7801     for (const auto &I : CurrentIterVals) {
7802       PHINode *PHI = dyn_cast<PHINode>(I.first);
7803       if (!PHI || PHI->getParent() != Header) continue;
7804       PHIsToCompute.push_back(PHI);
7805     }
7806     for (PHINode *PHI : PHIsToCompute) {
7807       Constant *&NextPHI = NextIterVals[PHI];
7808       if (NextPHI) continue;    // Already computed!
7809 
7810       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7811       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7812     }
7813     CurrentIterVals.swap(NextIterVals);
7814   }
7815 
7816   // Too many iterations were needed to evaluate.
7817   return getCouldNotCompute();
7818 }
7819 
7820 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7821   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7822       ValuesAtScopes[V];
7823   // Check to see if we've folded this expression at this loop before.
7824   for (auto &LS : Values)
7825     if (LS.first == L)
7826       return LS.second ? LS.second : V;
7827 
7828   Values.emplace_back(L, nullptr);
7829 
7830   // Otherwise compute it.
7831   const SCEV *C = computeSCEVAtScope(V, L);
7832   for (auto &LS : reverse(ValuesAtScopes[V]))
7833     if (LS.first == L) {
7834       LS.second = C;
7835       break;
7836     }
7837   return C;
7838 }
7839 
7840 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7841 /// will return Constants for objects which aren't represented by a
7842 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7843 /// Returns NULL if the SCEV isn't representable as a Constant.
7844 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7845   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7846     case scCouldNotCompute:
7847     case scAddRecExpr:
7848       break;
7849     case scConstant:
7850       return cast<SCEVConstant>(V)->getValue();
7851     case scUnknown:
7852       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7853     case scSignExtend: {
7854       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7855       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7856         return ConstantExpr::getSExt(CastOp, SS->getType());
7857       break;
7858     }
7859     case scZeroExtend: {
7860       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7861       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7862         return ConstantExpr::getZExt(CastOp, SZ->getType());
7863       break;
7864     }
7865     case scTruncate: {
7866       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7867       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7868         return ConstantExpr::getTrunc(CastOp, ST->getType());
7869       break;
7870     }
7871     case scAddExpr: {
7872       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7873       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7874         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7875           unsigned AS = PTy->getAddressSpace();
7876           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7877           C = ConstantExpr::getBitCast(C, DestPtrTy);
7878         }
7879         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7880           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7881           if (!C2) return nullptr;
7882 
7883           // First pointer!
7884           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7885             unsigned AS = C2->getType()->getPointerAddressSpace();
7886             std::swap(C, C2);
7887             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7888             // The offsets have been converted to bytes.  We can add bytes to an
7889             // i8* by GEP with the byte count in the first index.
7890             C = ConstantExpr::getBitCast(C, DestPtrTy);
7891           }
7892 
7893           // Don't bother trying to sum two pointers. We probably can't
7894           // statically compute a load that results from it anyway.
7895           if (C2->getType()->isPointerTy())
7896             return nullptr;
7897 
7898           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7899             if (PTy->getElementType()->isStructTy())
7900               C2 = ConstantExpr::getIntegerCast(
7901                   C2, Type::getInt32Ty(C->getContext()), true);
7902             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7903           } else
7904             C = ConstantExpr::getAdd(C, C2);
7905         }
7906         return C;
7907       }
7908       break;
7909     }
7910     case scMulExpr: {
7911       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7912       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7913         // Don't bother with pointers at all.
7914         if (C->getType()->isPointerTy()) return nullptr;
7915         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7916           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7917           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7918           C = ConstantExpr::getMul(C, C2);
7919         }
7920         return C;
7921       }
7922       break;
7923     }
7924     case scUDivExpr: {
7925       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7926       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7927         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7928           if (LHS->getType() == RHS->getType())
7929             return ConstantExpr::getUDiv(LHS, RHS);
7930       break;
7931     }
7932     case scSMaxExpr:
7933     case scUMaxExpr:
7934       break; // TODO: smax, umax.
7935   }
7936   return nullptr;
7937 }
7938 
7939 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7940   if (isa<SCEVConstant>(V)) return V;
7941 
7942   // If this instruction is evolved from a constant-evolving PHI, compute the
7943   // exit value from the loop without using SCEVs.
7944   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7945     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7946       const Loop *LI = this->LI[I->getParent()];
7947       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7948         if (PHINode *PN = dyn_cast<PHINode>(I))
7949           if (PN->getParent() == LI->getHeader()) {
7950             // Okay, there is no closed form solution for the PHI node.  Check
7951             // to see if the loop that contains it has a known backedge-taken
7952             // count.  If so, we may be able to force computation of the exit
7953             // value.
7954             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7955             if (const SCEVConstant *BTCC =
7956                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7957 
7958               // This trivial case can show up in some degenerate cases where
7959               // the incoming IR has not yet been fully simplified.
7960               if (BTCC->getValue()->isZero()) {
7961                 Value *InitValue = nullptr;
7962                 bool MultipleInitValues = false;
7963                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7964                   if (!LI->contains(PN->getIncomingBlock(i))) {
7965                     if (!InitValue)
7966                       InitValue = PN->getIncomingValue(i);
7967                     else if (InitValue != PN->getIncomingValue(i)) {
7968                       MultipleInitValues = true;
7969                       break;
7970                     }
7971                   }
7972                   if (!MultipleInitValues && InitValue)
7973                     return getSCEV(InitValue);
7974                 }
7975               }
7976               // Okay, we know how many times the containing loop executes.  If
7977               // this is a constant evolving PHI node, get the final value at
7978               // the specified iteration number.
7979               Constant *RV =
7980                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7981               if (RV) return getSCEV(RV);
7982             }
7983           }
7984 
7985       // Okay, this is an expression that we cannot symbolically evaluate
7986       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7987       // the arguments into constants, and if so, try to constant propagate the
7988       // result.  This is particularly useful for computing loop exit values.
7989       if (CanConstantFold(I)) {
7990         SmallVector<Constant *, 4> Operands;
7991         bool MadeImprovement = false;
7992         for (Value *Op : I->operands()) {
7993           if (Constant *C = dyn_cast<Constant>(Op)) {
7994             Operands.push_back(C);
7995             continue;
7996           }
7997 
7998           // If any of the operands is non-constant and if they are
7999           // non-integer and non-pointer, don't even try to analyze them
8000           // with scev techniques.
8001           if (!isSCEVable(Op->getType()))
8002             return V;
8003 
8004           const SCEV *OrigV = getSCEV(Op);
8005           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8006           MadeImprovement |= OrigV != OpV;
8007 
8008           Constant *C = BuildConstantFromSCEV(OpV);
8009           if (!C) return V;
8010           if (C->getType() != Op->getType())
8011             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8012                                                               Op->getType(),
8013                                                               false),
8014                                       C, Op->getType());
8015           Operands.push_back(C);
8016         }
8017 
8018         // Check to see if getSCEVAtScope actually made an improvement.
8019         if (MadeImprovement) {
8020           Constant *C = nullptr;
8021           const DataLayout &DL = getDataLayout();
8022           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8023             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8024                                                 Operands[1], DL, &TLI);
8025           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8026             if (!LI->isVolatile())
8027               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8028           } else
8029             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8030           if (!C) return V;
8031           return getSCEV(C);
8032         }
8033       }
8034     }
8035 
8036     // This is some other type of SCEVUnknown, just return it.
8037     return V;
8038   }
8039 
8040   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8041     // Avoid performing the look-up in the common case where the specified
8042     // expression has no loop-variant portions.
8043     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8044       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8045       if (OpAtScope != Comm->getOperand(i)) {
8046         // Okay, at least one of these operands is loop variant but might be
8047         // foldable.  Build a new instance of the folded commutative expression.
8048         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8049                                             Comm->op_begin()+i);
8050         NewOps.push_back(OpAtScope);
8051 
8052         for (++i; i != e; ++i) {
8053           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8054           NewOps.push_back(OpAtScope);
8055         }
8056         if (isa<SCEVAddExpr>(Comm))
8057           return getAddExpr(NewOps);
8058         if (isa<SCEVMulExpr>(Comm))
8059           return getMulExpr(NewOps);
8060         if (isa<SCEVSMaxExpr>(Comm))
8061           return getSMaxExpr(NewOps);
8062         if (isa<SCEVUMaxExpr>(Comm))
8063           return getUMaxExpr(NewOps);
8064         llvm_unreachable("Unknown commutative SCEV type!");
8065       }
8066     }
8067     // If we got here, all operands are loop invariant.
8068     return Comm;
8069   }
8070 
8071   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8072     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8073     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8074     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8075       return Div;   // must be loop invariant
8076     return getUDivExpr(LHS, RHS);
8077   }
8078 
8079   // If this is a loop recurrence for a loop that does not contain L, then we
8080   // are dealing with the final value computed by the loop.
8081   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8082     // First, attempt to evaluate each operand.
8083     // Avoid performing the look-up in the common case where the specified
8084     // expression has no loop-variant portions.
8085     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8086       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8087       if (OpAtScope == AddRec->getOperand(i))
8088         continue;
8089 
8090       // Okay, at least one of these operands is loop variant but might be
8091       // foldable.  Build a new instance of the folded commutative expression.
8092       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8093                                           AddRec->op_begin()+i);
8094       NewOps.push_back(OpAtScope);
8095       for (++i; i != e; ++i)
8096         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8097 
8098       const SCEV *FoldedRec =
8099         getAddRecExpr(NewOps, AddRec->getLoop(),
8100                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8101       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8102       // The addrec may be folded to a nonrecurrence, for example, if the
8103       // induction variable is multiplied by zero after constant folding. Go
8104       // ahead and return the folded value.
8105       if (!AddRec)
8106         return FoldedRec;
8107       break;
8108     }
8109 
8110     // If the scope is outside the addrec's loop, evaluate it by using the
8111     // loop exit value of the addrec.
8112     if (!AddRec->getLoop()->contains(L)) {
8113       // To evaluate this recurrence, we need to know how many times the AddRec
8114       // loop iterates.  Compute this now.
8115       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8116       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8117 
8118       // Then, evaluate the AddRec.
8119       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8120     }
8121 
8122     return AddRec;
8123   }
8124 
8125   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8126     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8127     if (Op == Cast->getOperand())
8128       return Cast;  // must be loop invariant
8129     return getZeroExtendExpr(Op, Cast->getType());
8130   }
8131 
8132   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8133     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8134     if (Op == Cast->getOperand())
8135       return Cast;  // must be loop invariant
8136     return getSignExtendExpr(Op, Cast->getType());
8137   }
8138 
8139   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8140     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8141     if (Op == Cast->getOperand())
8142       return Cast;  // must be loop invariant
8143     return getTruncateExpr(Op, Cast->getType());
8144   }
8145 
8146   llvm_unreachable("Unknown SCEV type!");
8147 }
8148 
8149 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8150   return getSCEVAtScope(getSCEV(V), L);
8151 }
8152 
8153 /// Finds the minimum unsigned root of the following equation:
8154 ///
8155 ///     A * X = B (mod N)
8156 ///
8157 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8158 /// A and B isn't important.
8159 ///
8160 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8161 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8162                                                ScalarEvolution &SE) {
8163   uint32_t BW = A.getBitWidth();
8164   assert(BW == SE.getTypeSizeInBits(B->getType()));
8165   assert(A != 0 && "A must be non-zero.");
8166 
8167   // 1. D = gcd(A, N)
8168   //
8169   // The gcd of A and N may have only one prime factor: 2. The number of
8170   // trailing zeros in A is its multiplicity
8171   uint32_t Mult2 = A.countTrailingZeros();
8172   // D = 2^Mult2
8173 
8174   // 2. Check if B is divisible by D.
8175   //
8176   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8177   // is not less than multiplicity of this prime factor for D.
8178   if (SE.GetMinTrailingZeros(B) < Mult2)
8179     return SE.getCouldNotCompute();
8180 
8181   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8182   // modulo (N / D).
8183   //
8184   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8185   // (N / D) in general. The inverse itself always fits into BW bits, though,
8186   // so we immediately truncate it.
8187   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8188   APInt Mod(BW + 1, 0);
8189   Mod.setBit(BW - Mult2);  // Mod = N / D
8190   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8191 
8192   // 4. Compute the minimum unsigned root of the equation:
8193   // I * (B / D) mod (N / D)
8194   // To simplify the computation, we factor out the divide by D:
8195   // (I * B mod N) / D
8196   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8197   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8198 }
8199 
8200 /// Find the roots of the quadratic equation for the given quadratic chrec
8201 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8202 /// two SCEVCouldNotCompute objects.
8203 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8204 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8205   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8206   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8207   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8208   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8209 
8210   // We currently can only solve this if the coefficients are constants.
8211   if (!LC || !MC || !NC)
8212     return None;
8213 
8214   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8215   const APInt &L = LC->getAPInt();
8216   const APInt &M = MC->getAPInt();
8217   const APInt &N = NC->getAPInt();
8218   APInt Two(BitWidth, 2);
8219 
8220   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8221 
8222   // The A coefficient is N/2
8223   APInt A = N.sdiv(Two);
8224 
8225   // The B coefficient is M-N/2
8226   APInt B = M;
8227   B -= A; // A is the same as N/2.
8228 
8229   // The C coefficient is L.
8230   const APInt& C = L;
8231 
8232   // Compute the B^2-4ac term.
8233   APInt SqrtTerm = B;
8234   SqrtTerm *= B;
8235   SqrtTerm -= 4 * (A * C);
8236 
8237   if (SqrtTerm.isNegative()) {
8238     // The loop is provably infinite.
8239     return None;
8240   }
8241 
8242   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8243   // integer value or else APInt::sqrt() will assert.
8244   APInt SqrtVal = SqrtTerm.sqrt();
8245 
8246   // Compute the two solutions for the quadratic formula.
8247   // The divisions must be performed as signed divisions.
8248   APInt NegB = -std::move(B);
8249   APInt TwoA = std::move(A);
8250   TwoA <<= 1;
8251   if (TwoA.isNullValue())
8252     return None;
8253 
8254   LLVMContext &Context = SE.getContext();
8255 
8256   ConstantInt *Solution1 =
8257     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8258   ConstantInt *Solution2 =
8259     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8260 
8261   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8262                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8263 }
8264 
8265 ScalarEvolution::ExitLimit
8266 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8267                               bool AllowPredicates) {
8268 
8269   // This is only used for loops with a "x != y" exit test. The exit condition
8270   // is now expressed as a single expression, V = x-y. So the exit test is
8271   // effectively V != 0.  We know and take advantage of the fact that this
8272   // expression only being used in a comparison by zero context.
8273 
8274   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8275   // If the value is a constant
8276   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8277     // If the value is already zero, the branch will execute zero times.
8278     if (C->getValue()->isZero()) return C;
8279     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8280   }
8281 
8282   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8283   if (!AddRec && AllowPredicates)
8284     // Try to make this an AddRec using runtime tests, in the first X
8285     // iterations of this loop, where X is the SCEV expression found by the
8286     // algorithm below.
8287     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8288 
8289   if (!AddRec || AddRec->getLoop() != L)
8290     return getCouldNotCompute();
8291 
8292   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8293   // the quadratic equation to solve it.
8294   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8295     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8296       const SCEVConstant *R1 = Roots->first;
8297       const SCEVConstant *R2 = Roots->second;
8298       // Pick the smallest positive root value.
8299       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8300               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8301         if (!CB->getZExtValue())
8302           std::swap(R1, R2); // R1 is the minimum root now.
8303 
8304         // We can only use this value if the chrec ends up with an exact zero
8305         // value at this index.  When solving for "X*X != 5", for example, we
8306         // should not accept a root of 2.
8307         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8308         if (Val->isZero())
8309           // We found a quadratic root!
8310           return ExitLimit(R1, R1, false, Predicates);
8311       }
8312     }
8313     return getCouldNotCompute();
8314   }
8315 
8316   // Otherwise we can only handle this if it is affine.
8317   if (!AddRec->isAffine())
8318     return getCouldNotCompute();
8319 
8320   // If this is an affine expression, the execution count of this branch is
8321   // the minimum unsigned root of the following equation:
8322   //
8323   //     Start + Step*N = 0 (mod 2^BW)
8324   //
8325   // equivalent to:
8326   //
8327   //             Step*N = -Start (mod 2^BW)
8328   //
8329   // where BW is the common bit width of Start and Step.
8330 
8331   // Get the initial value for the loop.
8332   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8333   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8334 
8335   // For now we handle only constant steps.
8336   //
8337   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8338   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8339   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8340   // We have not yet seen any such cases.
8341   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8342   if (!StepC || StepC->getValue()->isZero())
8343     return getCouldNotCompute();
8344 
8345   // For positive steps (counting up until unsigned overflow):
8346   //   N = -Start/Step (as unsigned)
8347   // For negative steps (counting down to zero):
8348   //   N = Start/-Step
8349   // First compute the unsigned distance from zero in the direction of Step.
8350   bool CountDown = StepC->getAPInt().isNegative();
8351   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8352 
8353   // Handle unitary steps, which cannot wraparound.
8354   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8355   //   N = Distance (as unsigned)
8356   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8357     APInt MaxBECount = getUnsignedRangeMax(Distance);
8358 
8359     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8360     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8361     // case, and see if we can improve the bound.
8362     //
8363     // Explicitly handling this here is necessary because getUnsignedRange
8364     // isn't context-sensitive; it doesn't know that we only care about the
8365     // range inside the loop.
8366     const SCEV *Zero = getZero(Distance->getType());
8367     const SCEV *One = getOne(Distance->getType());
8368     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8369     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8370       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8371       // as "unsigned_max(Distance + 1) - 1".
8372       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8373       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8374     }
8375     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8376   }
8377 
8378   // If the condition controls loop exit (the loop exits only if the expression
8379   // is true) and the addition is no-wrap we can use unsigned divide to
8380   // compute the backedge count.  In this case, the step may not divide the
8381   // distance, but we don't care because if the condition is "missed" the loop
8382   // will have undefined behavior due to wrapping.
8383   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8384       loopHasNoAbnormalExits(AddRec->getLoop())) {
8385     const SCEV *Exact =
8386         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8387     const SCEV *Max =
8388         Exact == getCouldNotCompute()
8389             ? Exact
8390             : getConstant(getUnsignedRangeMax(Exact));
8391     return ExitLimit(Exact, Max, false, Predicates);
8392   }
8393 
8394   // Solve the general equation.
8395   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8396                                                getNegativeSCEV(Start), *this);
8397   const SCEV *M = E == getCouldNotCompute()
8398                       ? E
8399                       : getConstant(getUnsignedRangeMax(E));
8400   return ExitLimit(E, M, false, Predicates);
8401 }
8402 
8403 ScalarEvolution::ExitLimit
8404 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8405   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8406   // handle them yet except for the trivial case.  This could be expanded in the
8407   // future as needed.
8408 
8409   // If the value is a constant, check to see if it is known to be non-zero
8410   // already.  If so, the backedge will execute zero times.
8411   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8412     if (!C->getValue()->isZero())
8413       return getZero(C->getType());
8414     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8415   }
8416 
8417   // We could implement others, but I really doubt anyone writes loops like
8418   // this, and if they did, they would already be constant folded.
8419   return getCouldNotCompute();
8420 }
8421 
8422 std::pair<BasicBlock *, BasicBlock *>
8423 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8424   // If the block has a unique predecessor, then there is no path from the
8425   // predecessor to the block that does not go through the direct edge
8426   // from the predecessor to the block.
8427   if (BasicBlock *Pred = BB->getSinglePredecessor())
8428     return {Pred, BB};
8429 
8430   // A loop's header is defined to be a block that dominates the loop.
8431   // If the header has a unique predecessor outside the loop, it must be
8432   // a block that has exactly one successor that can reach the loop.
8433   if (Loop *L = LI.getLoopFor(BB))
8434     return {L->getLoopPredecessor(), L->getHeader()};
8435 
8436   return {nullptr, nullptr};
8437 }
8438 
8439 /// SCEV structural equivalence is usually sufficient for testing whether two
8440 /// expressions are equal, however for the purposes of looking for a condition
8441 /// guarding a loop, it can be useful to be a little more general, since a
8442 /// front-end may have replicated the controlling expression.
8443 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8444   // Quick check to see if they are the same SCEV.
8445   if (A == B) return true;
8446 
8447   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8448     // Not all instructions that are "identical" compute the same value.  For
8449     // instance, two distinct alloca instructions allocating the same type are
8450     // identical and do not read memory; but compute distinct values.
8451     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8452   };
8453 
8454   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8455   // two different instructions with the same value. Check for this case.
8456   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8457     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8458       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8459         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8460           if (ComputesEqualValues(AI, BI))
8461             return true;
8462 
8463   // Otherwise assume they may have a different value.
8464   return false;
8465 }
8466 
8467 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8468                                            const SCEV *&LHS, const SCEV *&RHS,
8469                                            unsigned Depth) {
8470   bool Changed = false;
8471 
8472   // If we hit the max recursion limit bail out.
8473   if (Depth >= 3)
8474     return false;
8475 
8476   // Canonicalize a constant to the right side.
8477   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8478     // Check for both operands constant.
8479     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8480       if (ConstantExpr::getICmp(Pred,
8481                                 LHSC->getValue(),
8482                                 RHSC->getValue())->isNullValue())
8483         goto trivially_false;
8484       else
8485         goto trivially_true;
8486     }
8487     // Otherwise swap the operands to put the constant on the right.
8488     std::swap(LHS, RHS);
8489     Pred = ICmpInst::getSwappedPredicate(Pred);
8490     Changed = true;
8491   }
8492 
8493   // If we're comparing an addrec with a value which is loop-invariant in the
8494   // addrec's loop, put the addrec on the left. Also make a dominance check,
8495   // as both operands could be addrecs loop-invariant in each other's loop.
8496   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8497     const Loop *L = AR->getLoop();
8498     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8499       std::swap(LHS, RHS);
8500       Pred = ICmpInst::getSwappedPredicate(Pred);
8501       Changed = true;
8502     }
8503   }
8504 
8505   // If there's a constant operand, canonicalize comparisons with boundary
8506   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8507   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8508     const APInt &RA = RC->getAPInt();
8509 
8510     bool SimplifiedByConstantRange = false;
8511 
8512     if (!ICmpInst::isEquality(Pred)) {
8513       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8514       if (ExactCR.isFullSet())
8515         goto trivially_true;
8516       else if (ExactCR.isEmptySet())
8517         goto trivially_false;
8518 
8519       APInt NewRHS;
8520       CmpInst::Predicate NewPred;
8521       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8522           ICmpInst::isEquality(NewPred)) {
8523         // We were able to convert an inequality to an equality.
8524         Pred = NewPred;
8525         RHS = getConstant(NewRHS);
8526         Changed = SimplifiedByConstantRange = true;
8527       }
8528     }
8529 
8530     if (!SimplifiedByConstantRange) {
8531       switch (Pred) {
8532       default:
8533         break;
8534       case ICmpInst::ICMP_EQ:
8535       case ICmpInst::ICMP_NE:
8536         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8537         if (!RA)
8538           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8539             if (const SCEVMulExpr *ME =
8540                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8541               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8542                   ME->getOperand(0)->isAllOnesValue()) {
8543                 RHS = AE->getOperand(1);
8544                 LHS = ME->getOperand(1);
8545                 Changed = true;
8546               }
8547         break;
8548 
8549 
8550         // The "Should have been caught earlier!" messages refer to the fact
8551         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8552         // should have fired on the corresponding cases, and canonicalized the
8553         // check to trivially_true or trivially_false.
8554 
8555       case ICmpInst::ICMP_UGE:
8556         assert(!RA.isMinValue() && "Should have been caught earlier!");
8557         Pred = ICmpInst::ICMP_UGT;
8558         RHS = getConstant(RA - 1);
8559         Changed = true;
8560         break;
8561       case ICmpInst::ICMP_ULE:
8562         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8563         Pred = ICmpInst::ICMP_ULT;
8564         RHS = getConstant(RA + 1);
8565         Changed = true;
8566         break;
8567       case ICmpInst::ICMP_SGE:
8568         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8569         Pred = ICmpInst::ICMP_SGT;
8570         RHS = getConstant(RA - 1);
8571         Changed = true;
8572         break;
8573       case ICmpInst::ICMP_SLE:
8574         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8575         Pred = ICmpInst::ICMP_SLT;
8576         RHS = getConstant(RA + 1);
8577         Changed = true;
8578         break;
8579       }
8580     }
8581   }
8582 
8583   // Check for obvious equality.
8584   if (HasSameValue(LHS, RHS)) {
8585     if (ICmpInst::isTrueWhenEqual(Pred))
8586       goto trivially_true;
8587     if (ICmpInst::isFalseWhenEqual(Pred))
8588       goto trivially_false;
8589   }
8590 
8591   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8592   // adding or subtracting 1 from one of the operands.
8593   switch (Pred) {
8594   case ICmpInst::ICMP_SLE:
8595     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8596       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8597                        SCEV::FlagNSW);
8598       Pred = ICmpInst::ICMP_SLT;
8599       Changed = true;
8600     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8601       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8602                        SCEV::FlagNSW);
8603       Pred = ICmpInst::ICMP_SLT;
8604       Changed = true;
8605     }
8606     break;
8607   case ICmpInst::ICMP_SGE:
8608     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8609       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8610                        SCEV::FlagNSW);
8611       Pred = ICmpInst::ICMP_SGT;
8612       Changed = true;
8613     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8614       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8615                        SCEV::FlagNSW);
8616       Pred = ICmpInst::ICMP_SGT;
8617       Changed = true;
8618     }
8619     break;
8620   case ICmpInst::ICMP_ULE:
8621     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8622       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8623                        SCEV::FlagNUW);
8624       Pred = ICmpInst::ICMP_ULT;
8625       Changed = true;
8626     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8627       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8628       Pred = ICmpInst::ICMP_ULT;
8629       Changed = true;
8630     }
8631     break;
8632   case ICmpInst::ICMP_UGE:
8633     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8634       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8635       Pred = ICmpInst::ICMP_UGT;
8636       Changed = true;
8637     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8638       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8639                        SCEV::FlagNUW);
8640       Pred = ICmpInst::ICMP_UGT;
8641       Changed = true;
8642     }
8643     break;
8644   default:
8645     break;
8646   }
8647 
8648   // TODO: More simplifications are possible here.
8649 
8650   // Recursively simplify until we either hit a recursion limit or nothing
8651   // changes.
8652   if (Changed)
8653     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8654 
8655   return Changed;
8656 
8657 trivially_true:
8658   // Return 0 == 0.
8659   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8660   Pred = ICmpInst::ICMP_EQ;
8661   return true;
8662 
8663 trivially_false:
8664   // Return 0 != 0.
8665   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8666   Pred = ICmpInst::ICMP_NE;
8667   return true;
8668 }
8669 
8670 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8671   return getSignedRangeMax(S).isNegative();
8672 }
8673 
8674 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8675   return getSignedRangeMin(S).isStrictlyPositive();
8676 }
8677 
8678 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8679   return !getSignedRangeMin(S).isNegative();
8680 }
8681 
8682 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8683   return !getSignedRangeMax(S).isStrictlyPositive();
8684 }
8685 
8686 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8687   return isKnownNegative(S) || isKnownPositive(S);
8688 }
8689 
8690 std::pair<const SCEV *, const SCEV *>
8691 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
8692   // Compute SCEV on entry of loop L.
8693   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
8694   if (Start == getCouldNotCompute())
8695     return { Start, Start };
8696   // Compute post increment SCEV for loop L.
8697   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
8698   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
8699   return { Start, PostInc };
8700 }
8701 
8702 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
8703                                           const SCEV *LHS, const SCEV *RHS) {
8704   // First collect all loops.
8705   SmallPtrSet<const Loop *, 8> LoopsUsed;
8706   getUsedLoops(LHS, LoopsUsed);
8707   getUsedLoops(RHS, LoopsUsed);
8708 
8709   if (LoopsUsed.empty())
8710     return false;
8711 
8712   // Domination relationship must be a linear order on collected loops.
8713 #ifndef NDEBUG
8714   for (auto *L1 : LoopsUsed)
8715     for (auto *L2 : LoopsUsed)
8716       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
8717               DT.dominates(L2->getHeader(), L1->getHeader())) &&
8718              "Domination relationship is not a linear order");
8719 #endif
8720 
8721   const Loop *MDL =
8722       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
8723                         [&](const Loop *L1, const Loop *L2) {
8724          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
8725        });
8726 
8727   // Get init and post increment value for LHS.
8728   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
8729   // if LHS contains unknown non-invariant SCEV then bail out.
8730   if (SplitLHS.first == getCouldNotCompute())
8731     return false;
8732   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
8733   // Get init and post increment value for RHS.
8734   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
8735   // if RHS contains unknown non-invariant SCEV then bail out.
8736   if (SplitRHS.first == getCouldNotCompute())
8737     return false;
8738   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
8739   // It is possible that init SCEV contains an invariant load but it does
8740   // not dominate MDL and is not available at MDL loop entry, so we should
8741   // check it here.
8742   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
8743       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
8744     return false;
8745 
8746   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
8747          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
8748                                      SplitRHS.second);
8749 }
8750 
8751 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8752                                        const SCEV *LHS, const SCEV *RHS) {
8753   // Canonicalize the inputs first.
8754   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8755 
8756   if (isKnownViaInduction(Pred, LHS, RHS))
8757     return true;
8758 
8759   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8760     return true;
8761 
8762   // Otherwise see what can be done with some simple reasoning.
8763   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
8764 }
8765 
8766 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
8767                                               const SCEVAddRecExpr *LHS,
8768                                               const SCEV *RHS) {
8769   const Loop *L = LHS->getLoop();
8770   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
8771          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
8772 }
8773 
8774 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8775                                            ICmpInst::Predicate Pred,
8776                                            bool &Increasing) {
8777   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8778 
8779 #ifndef NDEBUG
8780   // Verify an invariant: inverting the predicate should turn a monotonically
8781   // increasing change to a monotonically decreasing one, and vice versa.
8782   bool IncreasingSwapped;
8783   bool ResultSwapped = isMonotonicPredicateImpl(
8784       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8785 
8786   assert(Result == ResultSwapped && "should be able to analyze both!");
8787   if (ResultSwapped)
8788     assert(Increasing == !IncreasingSwapped &&
8789            "monotonicity should flip as we flip the predicate");
8790 #endif
8791 
8792   return Result;
8793 }
8794 
8795 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8796                                                ICmpInst::Predicate Pred,
8797                                                bool &Increasing) {
8798 
8799   // A zero step value for LHS means the induction variable is essentially a
8800   // loop invariant value. We don't really depend on the predicate actually
8801   // flipping from false to true (for increasing predicates, and the other way
8802   // around for decreasing predicates), all we care about is that *if* the
8803   // predicate changes then it only changes from false to true.
8804   //
8805   // A zero step value in itself is not very useful, but there may be places
8806   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8807   // as general as possible.
8808 
8809   switch (Pred) {
8810   default:
8811     return false; // Conservative answer
8812 
8813   case ICmpInst::ICMP_UGT:
8814   case ICmpInst::ICMP_UGE:
8815   case ICmpInst::ICMP_ULT:
8816   case ICmpInst::ICMP_ULE:
8817     if (!LHS->hasNoUnsignedWrap())
8818       return false;
8819 
8820     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8821     return true;
8822 
8823   case ICmpInst::ICMP_SGT:
8824   case ICmpInst::ICMP_SGE:
8825   case ICmpInst::ICMP_SLT:
8826   case ICmpInst::ICMP_SLE: {
8827     if (!LHS->hasNoSignedWrap())
8828       return false;
8829 
8830     const SCEV *Step = LHS->getStepRecurrence(*this);
8831 
8832     if (isKnownNonNegative(Step)) {
8833       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8834       return true;
8835     }
8836 
8837     if (isKnownNonPositive(Step)) {
8838       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8839       return true;
8840     }
8841 
8842     return false;
8843   }
8844 
8845   }
8846 
8847   llvm_unreachable("switch has default clause!");
8848 }
8849 
8850 bool ScalarEvolution::isLoopInvariantPredicate(
8851     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8852     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8853     const SCEV *&InvariantRHS) {
8854 
8855   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8856   if (!isLoopInvariant(RHS, L)) {
8857     if (!isLoopInvariant(LHS, L))
8858       return false;
8859 
8860     std::swap(LHS, RHS);
8861     Pred = ICmpInst::getSwappedPredicate(Pred);
8862   }
8863 
8864   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8865   if (!ArLHS || ArLHS->getLoop() != L)
8866     return false;
8867 
8868   bool Increasing;
8869   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8870     return false;
8871 
8872   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8873   // true as the loop iterates, and the backedge is control dependent on
8874   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8875   //
8876   //   * if the predicate was false in the first iteration then the predicate
8877   //     is never evaluated again, since the loop exits without taking the
8878   //     backedge.
8879   //   * if the predicate was true in the first iteration then it will
8880   //     continue to be true for all future iterations since it is
8881   //     monotonically increasing.
8882   //
8883   // For both the above possibilities, we can replace the loop varying
8884   // predicate with its value on the first iteration of the loop (which is
8885   // loop invariant).
8886   //
8887   // A similar reasoning applies for a monotonically decreasing predicate, by
8888   // replacing true with false and false with true in the above two bullets.
8889 
8890   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8891 
8892   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8893     return false;
8894 
8895   InvariantPred = Pred;
8896   InvariantLHS = ArLHS->getStart();
8897   InvariantRHS = RHS;
8898   return true;
8899 }
8900 
8901 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8902     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8903   if (HasSameValue(LHS, RHS))
8904     return ICmpInst::isTrueWhenEqual(Pred);
8905 
8906   // This code is split out from isKnownPredicate because it is called from
8907   // within isLoopEntryGuardedByCond.
8908 
8909   auto CheckRanges =
8910       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8911     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8912         .contains(RangeLHS);
8913   };
8914 
8915   // The check at the top of the function catches the case where the values are
8916   // known to be equal.
8917   if (Pred == CmpInst::ICMP_EQ)
8918     return false;
8919 
8920   if (Pred == CmpInst::ICMP_NE)
8921     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8922            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8923            isKnownNonZero(getMinusSCEV(LHS, RHS));
8924 
8925   if (CmpInst::isSigned(Pred))
8926     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8927 
8928   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8929 }
8930 
8931 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8932                                                     const SCEV *LHS,
8933                                                     const SCEV *RHS) {
8934   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8935   // Return Y via OutY.
8936   auto MatchBinaryAddToConst =
8937       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8938              SCEV::NoWrapFlags ExpectedFlags) {
8939     const SCEV *NonConstOp, *ConstOp;
8940     SCEV::NoWrapFlags FlagsPresent;
8941 
8942     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8943         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8944       return false;
8945 
8946     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8947     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8948   };
8949 
8950   APInt C;
8951 
8952   switch (Pred) {
8953   default:
8954     break;
8955 
8956   case ICmpInst::ICMP_SGE:
8957     std::swap(LHS, RHS);
8958     LLVM_FALLTHROUGH;
8959   case ICmpInst::ICMP_SLE:
8960     // X s<= (X + C)<nsw> if C >= 0
8961     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8962       return true;
8963 
8964     // (X + C)<nsw> s<= X if C <= 0
8965     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8966         !C.isStrictlyPositive())
8967       return true;
8968     break;
8969 
8970   case ICmpInst::ICMP_SGT:
8971     std::swap(LHS, RHS);
8972     LLVM_FALLTHROUGH;
8973   case ICmpInst::ICMP_SLT:
8974     // X s< (X + C)<nsw> if C > 0
8975     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8976         C.isStrictlyPositive())
8977       return true;
8978 
8979     // (X + C)<nsw> s< X if C < 0
8980     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8981       return true;
8982     break;
8983   }
8984 
8985   return false;
8986 }
8987 
8988 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8989                                                    const SCEV *LHS,
8990                                                    const SCEV *RHS) {
8991   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8992     return false;
8993 
8994   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8995   // the stack can result in exponential time complexity.
8996   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8997 
8998   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8999   //
9000   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9001   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9002   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9003   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9004   // use isKnownPredicate later if needed.
9005   return isKnownNonNegative(RHS) &&
9006          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9007          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9008 }
9009 
9010 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9011                                         ICmpInst::Predicate Pred,
9012                                         const SCEV *LHS, const SCEV *RHS) {
9013   // No need to even try if we know the module has no guards.
9014   if (!HasGuards)
9015     return false;
9016 
9017   return any_of(*BB, [&](Instruction &I) {
9018     using namespace llvm::PatternMatch;
9019 
9020     Value *Condition;
9021     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9022                          m_Value(Condition))) &&
9023            isImpliedCond(Pred, LHS, RHS, Condition, false);
9024   });
9025 }
9026 
9027 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9028 /// protected by a conditional between LHS and RHS.  This is used to
9029 /// to eliminate casts.
9030 bool
9031 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9032                                              ICmpInst::Predicate Pred,
9033                                              const SCEV *LHS, const SCEV *RHS) {
9034   // Interpret a null as meaning no loop, where there is obviously no guard
9035   // (interprocedural conditions notwithstanding).
9036   if (!L) return true;
9037 
9038   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9039     return true;
9040 
9041   BasicBlock *Latch = L->getLoopLatch();
9042   if (!Latch)
9043     return false;
9044 
9045   BranchInst *LoopContinuePredicate =
9046     dyn_cast<BranchInst>(Latch->getTerminator());
9047   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9048       isImpliedCond(Pred, LHS, RHS,
9049                     LoopContinuePredicate->getCondition(),
9050                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9051     return true;
9052 
9053   // We don't want more than one activation of the following loops on the stack
9054   // -- that can lead to O(n!) time complexity.
9055   if (WalkingBEDominatingConds)
9056     return false;
9057 
9058   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9059 
9060   // See if we can exploit a trip count to prove the predicate.
9061   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9062   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9063   if (LatchBECount != getCouldNotCompute()) {
9064     // We know that Latch branches back to the loop header exactly
9065     // LatchBECount times.  This means the backdege condition at Latch is
9066     // equivalent to  "{0,+,1} u< LatchBECount".
9067     Type *Ty = LatchBECount->getType();
9068     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9069     const SCEV *LoopCounter =
9070       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9071     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9072                       LatchBECount))
9073       return true;
9074   }
9075 
9076   // Check conditions due to any @llvm.assume intrinsics.
9077   for (auto &AssumeVH : AC.assumptions()) {
9078     if (!AssumeVH)
9079       continue;
9080     auto *CI = cast<CallInst>(AssumeVH);
9081     if (!DT.dominates(CI, Latch->getTerminator()))
9082       continue;
9083 
9084     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9085       return true;
9086   }
9087 
9088   // If the loop is not reachable from the entry block, we risk running into an
9089   // infinite loop as we walk up into the dom tree.  These loops do not matter
9090   // anyway, so we just return a conservative answer when we see them.
9091   if (!DT.isReachableFromEntry(L->getHeader()))
9092     return false;
9093 
9094   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9095     return true;
9096 
9097   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9098        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9099     assert(DTN && "should reach the loop header before reaching the root!");
9100 
9101     BasicBlock *BB = DTN->getBlock();
9102     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9103       return true;
9104 
9105     BasicBlock *PBB = BB->getSinglePredecessor();
9106     if (!PBB)
9107       continue;
9108 
9109     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9110     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9111       continue;
9112 
9113     Value *Condition = ContinuePredicate->getCondition();
9114 
9115     // If we have an edge `E` within the loop body that dominates the only
9116     // latch, the condition guarding `E` also guards the backedge.  This
9117     // reasoning works only for loops with a single latch.
9118 
9119     BasicBlockEdge DominatingEdge(PBB, BB);
9120     if (DominatingEdge.isSingleEdge()) {
9121       // We're constructively (and conservatively) enumerating edges within the
9122       // loop body that dominate the latch.  The dominator tree better agree
9123       // with us on this:
9124       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9125 
9126       if (isImpliedCond(Pred, LHS, RHS, Condition,
9127                         BB != ContinuePredicate->getSuccessor(0)))
9128         return true;
9129     }
9130   }
9131 
9132   return false;
9133 }
9134 
9135 bool
9136 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9137                                           ICmpInst::Predicate Pred,
9138                                           const SCEV *LHS, const SCEV *RHS) {
9139   // Interpret a null as meaning no loop, where there is obviously no guard
9140   // (interprocedural conditions notwithstanding).
9141   if (!L) return false;
9142 
9143   // Both LHS and RHS must be available at loop entry.
9144   assert(isAvailableAtLoopEntry(LHS, L) &&
9145          "LHS is not available at Loop Entry");
9146   assert(isAvailableAtLoopEntry(RHS, L) &&
9147          "RHS is not available at Loop Entry");
9148 
9149   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9150     return true;
9151 
9152   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9153   // the facts (a >= b && a != b) separately. A typical situation is when the
9154   // non-strict comparison is known from ranges and non-equality is known from
9155   // dominating predicates. If we are proving strict comparison, we always try
9156   // to prove non-equality and non-strict comparison separately.
9157   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9158   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9159   bool ProvedNonStrictComparison = false;
9160   bool ProvedNonEquality = false;
9161 
9162   if (ProvingStrictComparison) {
9163     ProvedNonStrictComparison =
9164         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9165     ProvedNonEquality =
9166         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9167     if (ProvedNonStrictComparison && ProvedNonEquality)
9168       return true;
9169   }
9170 
9171   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9172   auto ProveViaGuard = [&](BasicBlock *Block) {
9173     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9174       return true;
9175     if (ProvingStrictComparison) {
9176       if (!ProvedNonStrictComparison)
9177         ProvedNonStrictComparison =
9178             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9179       if (!ProvedNonEquality)
9180         ProvedNonEquality =
9181             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9182       if (ProvedNonStrictComparison && ProvedNonEquality)
9183         return true;
9184     }
9185     return false;
9186   };
9187 
9188   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9189   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9190     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9191       return true;
9192     if (ProvingStrictComparison) {
9193       if (!ProvedNonStrictComparison)
9194         ProvedNonStrictComparison =
9195             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9196       if (!ProvedNonEquality)
9197         ProvedNonEquality =
9198             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9199       if (ProvedNonStrictComparison && ProvedNonEquality)
9200         return true;
9201     }
9202     return false;
9203   };
9204 
9205   // Starting at the loop predecessor, climb up the predecessor chain, as long
9206   // as there are predecessors that can be found that have unique successors
9207   // leading to the original header.
9208   for (std::pair<BasicBlock *, BasicBlock *>
9209          Pair(L->getLoopPredecessor(), L->getHeader());
9210        Pair.first;
9211        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9212 
9213     if (ProveViaGuard(Pair.first))
9214       return true;
9215 
9216     BranchInst *LoopEntryPredicate =
9217       dyn_cast<BranchInst>(Pair.first->getTerminator());
9218     if (!LoopEntryPredicate ||
9219         LoopEntryPredicate->isUnconditional())
9220       continue;
9221 
9222     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9223                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9224       return true;
9225   }
9226 
9227   // Check conditions due to any @llvm.assume intrinsics.
9228   for (auto &AssumeVH : AC.assumptions()) {
9229     if (!AssumeVH)
9230       continue;
9231     auto *CI = cast<CallInst>(AssumeVH);
9232     if (!DT.dominates(CI, L->getHeader()))
9233       continue;
9234 
9235     if (ProveViaCond(CI->getArgOperand(0), false))
9236       return true;
9237   }
9238 
9239   return false;
9240 }
9241 
9242 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9243                                     const SCEV *LHS, const SCEV *RHS,
9244                                     Value *FoundCondValue,
9245                                     bool Inverse) {
9246   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9247     return false;
9248 
9249   auto ClearOnExit =
9250       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9251 
9252   // Recursively handle And and Or conditions.
9253   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9254     if (BO->getOpcode() == Instruction::And) {
9255       if (!Inverse)
9256         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9257                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9258     } else if (BO->getOpcode() == Instruction::Or) {
9259       if (Inverse)
9260         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9261                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9262     }
9263   }
9264 
9265   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9266   if (!ICI) return false;
9267 
9268   // Now that we found a conditional branch that dominates the loop or controls
9269   // the loop latch. Check to see if it is the comparison we are looking for.
9270   ICmpInst::Predicate FoundPred;
9271   if (Inverse)
9272     FoundPred = ICI->getInversePredicate();
9273   else
9274     FoundPred = ICI->getPredicate();
9275 
9276   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9277   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9278 
9279   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9280 }
9281 
9282 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9283                                     const SCEV *RHS,
9284                                     ICmpInst::Predicate FoundPred,
9285                                     const SCEV *FoundLHS,
9286                                     const SCEV *FoundRHS) {
9287   // Balance the types.
9288   if (getTypeSizeInBits(LHS->getType()) <
9289       getTypeSizeInBits(FoundLHS->getType())) {
9290     if (CmpInst::isSigned(Pred)) {
9291       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9292       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9293     } else {
9294       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9295       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9296     }
9297   } else if (getTypeSizeInBits(LHS->getType()) >
9298       getTypeSizeInBits(FoundLHS->getType())) {
9299     if (CmpInst::isSigned(FoundPred)) {
9300       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9301       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9302     } else {
9303       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9304       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9305     }
9306   }
9307 
9308   // Canonicalize the query to match the way instcombine will have
9309   // canonicalized the comparison.
9310   if (SimplifyICmpOperands(Pred, LHS, RHS))
9311     if (LHS == RHS)
9312       return CmpInst::isTrueWhenEqual(Pred);
9313   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9314     if (FoundLHS == FoundRHS)
9315       return CmpInst::isFalseWhenEqual(FoundPred);
9316 
9317   // Check to see if we can make the LHS or RHS match.
9318   if (LHS == FoundRHS || RHS == FoundLHS) {
9319     if (isa<SCEVConstant>(RHS)) {
9320       std::swap(FoundLHS, FoundRHS);
9321       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9322     } else {
9323       std::swap(LHS, RHS);
9324       Pred = ICmpInst::getSwappedPredicate(Pred);
9325     }
9326   }
9327 
9328   // Check whether the found predicate is the same as the desired predicate.
9329   if (FoundPred == Pred)
9330     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9331 
9332   // Check whether swapping the found predicate makes it the same as the
9333   // desired predicate.
9334   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9335     if (isa<SCEVConstant>(RHS))
9336       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9337     else
9338       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9339                                    RHS, LHS, FoundLHS, FoundRHS);
9340   }
9341 
9342   // Unsigned comparison is the same as signed comparison when both the operands
9343   // are non-negative.
9344   if (CmpInst::isUnsigned(FoundPred) &&
9345       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9346       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9347     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9348 
9349   // Check if we can make progress by sharpening ranges.
9350   if (FoundPred == ICmpInst::ICMP_NE &&
9351       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9352 
9353     const SCEVConstant *C = nullptr;
9354     const SCEV *V = nullptr;
9355 
9356     if (isa<SCEVConstant>(FoundLHS)) {
9357       C = cast<SCEVConstant>(FoundLHS);
9358       V = FoundRHS;
9359     } else {
9360       C = cast<SCEVConstant>(FoundRHS);
9361       V = FoundLHS;
9362     }
9363 
9364     // The guarding predicate tells us that C != V. If the known range
9365     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9366     // range we consider has to correspond to same signedness as the
9367     // predicate we're interested in folding.
9368 
9369     APInt Min = ICmpInst::isSigned(Pred) ?
9370         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9371 
9372     if (Min == C->getAPInt()) {
9373       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9374       // This is true even if (Min + 1) wraps around -- in case of
9375       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9376 
9377       APInt SharperMin = Min + 1;
9378 
9379       switch (Pred) {
9380         case ICmpInst::ICMP_SGE:
9381         case ICmpInst::ICMP_UGE:
9382           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9383           // RHS, we're done.
9384           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9385                                     getConstant(SharperMin)))
9386             return true;
9387           LLVM_FALLTHROUGH;
9388 
9389         case ICmpInst::ICMP_SGT:
9390         case ICmpInst::ICMP_UGT:
9391           // We know from the range information that (V `Pred` Min ||
9392           // V == Min).  We know from the guarding condition that !(V
9393           // == Min).  This gives us
9394           //
9395           //       V `Pred` Min || V == Min && !(V == Min)
9396           //   =>  V `Pred` Min
9397           //
9398           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9399 
9400           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9401             return true;
9402           LLVM_FALLTHROUGH;
9403 
9404         default:
9405           // No change
9406           break;
9407       }
9408     }
9409   }
9410 
9411   // Check whether the actual condition is beyond sufficient.
9412   if (FoundPred == ICmpInst::ICMP_EQ)
9413     if (ICmpInst::isTrueWhenEqual(Pred))
9414       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9415         return true;
9416   if (Pred == ICmpInst::ICMP_NE)
9417     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9418       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9419         return true;
9420 
9421   // Otherwise assume the worst.
9422   return false;
9423 }
9424 
9425 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9426                                      const SCEV *&L, const SCEV *&R,
9427                                      SCEV::NoWrapFlags &Flags) {
9428   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9429   if (!AE || AE->getNumOperands() != 2)
9430     return false;
9431 
9432   L = AE->getOperand(0);
9433   R = AE->getOperand(1);
9434   Flags = AE->getNoWrapFlags();
9435   return true;
9436 }
9437 
9438 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9439                                                            const SCEV *Less) {
9440   // We avoid subtracting expressions here because this function is usually
9441   // fairly deep in the call stack (i.e. is called many times).
9442 
9443   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9444     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9445     const auto *MAR = cast<SCEVAddRecExpr>(More);
9446 
9447     if (LAR->getLoop() != MAR->getLoop())
9448       return None;
9449 
9450     // We look at affine expressions only; not for correctness but to keep
9451     // getStepRecurrence cheap.
9452     if (!LAR->isAffine() || !MAR->isAffine())
9453       return None;
9454 
9455     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9456       return None;
9457 
9458     Less = LAR->getStart();
9459     More = MAR->getStart();
9460 
9461     // fall through
9462   }
9463 
9464   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9465     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9466     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9467     return M - L;
9468   }
9469 
9470   SCEV::NoWrapFlags Flags;
9471   const SCEV *LLess = nullptr, *RLess = nullptr;
9472   const SCEV *LMore = nullptr, *RMore = nullptr;
9473   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9474   // Compare (X + C1) vs X.
9475   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9476     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9477       if (RLess == More)
9478         return -(C1->getAPInt());
9479 
9480   // Compare X vs (X + C2).
9481   if (splitBinaryAdd(More, LMore, RMore, Flags))
9482     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9483       if (RMore == Less)
9484         return C2->getAPInt();
9485 
9486   // Compare (X + C1) vs (X + C2).
9487   if (C1 && C2 && RLess == RMore)
9488     return C2->getAPInt() - C1->getAPInt();
9489 
9490   return None;
9491 }
9492 
9493 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9494     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9495     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9496   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9497     return false;
9498 
9499   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9500   if (!AddRecLHS)
9501     return false;
9502 
9503   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9504   if (!AddRecFoundLHS)
9505     return false;
9506 
9507   // We'd like to let SCEV reason about control dependencies, so we constrain
9508   // both the inequalities to be about add recurrences on the same loop.  This
9509   // way we can use isLoopEntryGuardedByCond later.
9510 
9511   const Loop *L = AddRecFoundLHS->getLoop();
9512   if (L != AddRecLHS->getLoop())
9513     return false;
9514 
9515   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9516   //
9517   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9518   //                                                                  ... (2)
9519   //
9520   // Informal proof for (2), assuming (1) [*]:
9521   //
9522   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9523   //
9524   // Then
9525   //
9526   //       FoundLHS s< FoundRHS s< INT_MIN - C
9527   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9528   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9529   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9530   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9531   // <=>  FoundLHS + C s< FoundRHS + C
9532   //
9533   // [*]: (1) can be proved by ruling out overflow.
9534   //
9535   // [**]: This can be proved by analyzing all the four possibilities:
9536   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9537   //    (A s>= 0, B s>= 0).
9538   //
9539   // Note:
9540   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9541   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9542   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9543   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9544   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9545   // C)".
9546 
9547   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9548   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9549   if (!LDiff || !RDiff || *LDiff != *RDiff)
9550     return false;
9551 
9552   if (LDiff->isMinValue())
9553     return true;
9554 
9555   APInt FoundRHSLimit;
9556 
9557   if (Pred == CmpInst::ICMP_ULT) {
9558     FoundRHSLimit = -(*RDiff);
9559   } else {
9560     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9561     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9562   }
9563 
9564   // Try to prove (1) or (2), as needed.
9565   return isAvailableAtLoopEntry(FoundRHS, L) &&
9566          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9567                                   getConstant(FoundRHSLimit));
9568 }
9569 
9570 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9571                                         const SCEV *LHS, const SCEV *RHS,
9572                                         const SCEV *FoundLHS,
9573                                         const SCEV *FoundRHS, unsigned Depth) {
9574   const PHINode *LPhi = nullptr, *RPhi = nullptr;
9575 
9576   auto ClearOnExit = make_scope_exit([&]() {
9577     if (LPhi) {
9578       bool Erased = PendingMerges.erase(LPhi);
9579       assert(Erased && "Failed to erase LPhi!");
9580       (void)Erased;
9581     }
9582     if (RPhi) {
9583       bool Erased = PendingMerges.erase(RPhi);
9584       assert(Erased && "Failed to erase RPhi!");
9585       (void)Erased;
9586     }
9587   });
9588 
9589   // Find respective Phis and check that they are not being pending.
9590   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9591     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9592       if (!PendingMerges.insert(Phi).second)
9593         return false;
9594       LPhi = Phi;
9595     }
9596   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9597     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9598       // If we detect a loop of Phi nodes being processed by this method, for
9599       // example:
9600       //
9601       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9602       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9603       //
9604       // we don't want to deal with a case that complex, so return conservative
9605       // answer false.
9606       if (!PendingMerges.insert(Phi).second)
9607         return false;
9608       RPhi = Phi;
9609     }
9610 
9611   // If none of LHS, RHS is a Phi, nothing to do here.
9612   if (!LPhi && !RPhi)
9613     return false;
9614 
9615   // If there is a SCEVUnknown Phi we are interested in, make it left.
9616   if (!LPhi) {
9617     std::swap(LHS, RHS);
9618     std::swap(FoundLHS, FoundRHS);
9619     std::swap(LPhi, RPhi);
9620     Pred = ICmpInst::getSwappedPredicate(Pred);
9621   }
9622 
9623   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
9624   const BasicBlock *LBB = LPhi->getParent();
9625   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9626 
9627   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
9628     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
9629            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
9630            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
9631   };
9632 
9633   if (RPhi && RPhi->getParent() == LBB) {
9634     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
9635     // If we compare two Phis from the same block, and for each entry block
9636     // the predicate is true for incoming values from this block, then the
9637     // predicate is also true for the Phis.
9638     for (const BasicBlock *IncBB : predecessors(LBB)) {
9639       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9640       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
9641       if (!ProvedEasily(L, R))
9642         return false;
9643     }
9644   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
9645     // Case two: RHS is also a Phi from the same basic block, and it is an
9646     // AddRec. It means that there is a loop which has both AddRec and Unknown
9647     // PHIs, for it we can compare incoming values of AddRec from above the loop
9648     // and latch with their respective incoming values of LPhi.
9649     assert(LPhi->getNumIncomingValues() == 2 &&
9650            "Phi node standing in loop header does not have exactly 2 inputs?");
9651     auto *RLoop = RAR->getLoop();
9652     auto *Predecessor = RLoop->getLoopPredecessor();
9653     assert(Predecessor && "Loop with AddRec with no predecessor?");
9654     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
9655     if (!ProvedEasily(L1, RAR->getStart()))
9656       return false;
9657     auto *Latch = RLoop->getLoopLatch();
9658     assert(Latch && "Loop with AddRec with no latch?");
9659     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
9660     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
9661       return false;
9662   } else {
9663     // In all other cases go over inputs of LHS and compare each of them to RHS,
9664     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
9665     // At this point RHS is either a non-Phi, or it is a Phi from some block
9666     // different from LBB.
9667     for (const BasicBlock *IncBB : predecessors(LBB)) {
9668       // Check that RHS is available in this block.
9669       if (!dominates(RHS, IncBB))
9670         return false;
9671       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9672       if (!ProvedEasily(L, RHS))
9673         return false;
9674     }
9675   }
9676   return true;
9677 }
9678 
9679 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9680                                             const SCEV *LHS, const SCEV *RHS,
9681                                             const SCEV *FoundLHS,
9682                                             const SCEV *FoundRHS) {
9683   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9684     return true;
9685 
9686   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9687     return true;
9688 
9689   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9690                                      FoundLHS, FoundRHS) ||
9691          // ~x < ~y --> x > y
9692          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9693                                      getNotSCEV(FoundRHS),
9694                                      getNotSCEV(FoundLHS));
9695 }
9696 
9697 /// If Expr computes ~A, return A else return nullptr
9698 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9699   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9700   if (!Add || Add->getNumOperands() != 2 ||
9701       !Add->getOperand(0)->isAllOnesValue())
9702     return nullptr;
9703 
9704   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9705   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9706       !AddRHS->getOperand(0)->isAllOnesValue())
9707     return nullptr;
9708 
9709   return AddRHS->getOperand(1);
9710 }
9711 
9712 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9713 template<typename MaxExprType>
9714 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9715                               const SCEV *Candidate) {
9716   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9717   if (!MaxExpr) return false;
9718 
9719   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9720 }
9721 
9722 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9723 template<typename MaxExprType>
9724 static bool IsMinConsistingOf(ScalarEvolution &SE,
9725                               const SCEV *MaybeMinExpr,
9726                               const SCEV *Candidate) {
9727   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9728   if (!MaybeMaxExpr)
9729     return false;
9730 
9731   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9732 }
9733 
9734 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9735                                            ICmpInst::Predicate Pred,
9736                                            const SCEV *LHS, const SCEV *RHS) {
9737   // If both sides are affine addrecs for the same loop, with equal
9738   // steps, and we know the recurrences don't wrap, then we only
9739   // need to check the predicate on the starting values.
9740 
9741   if (!ICmpInst::isRelational(Pred))
9742     return false;
9743 
9744   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9745   if (!LAR)
9746     return false;
9747   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9748   if (!RAR)
9749     return false;
9750   if (LAR->getLoop() != RAR->getLoop())
9751     return false;
9752   if (!LAR->isAffine() || !RAR->isAffine())
9753     return false;
9754 
9755   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9756     return false;
9757 
9758   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9759                          SCEV::FlagNSW : SCEV::FlagNUW;
9760   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9761     return false;
9762 
9763   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9764 }
9765 
9766 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9767 /// expression?
9768 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9769                                         ICmpInst::Predicate Pred,
9770                                         const SCEV *LHS, const SCEV *RHS) {
9771   switch (Pred) {
9772   default:
9773     return false;
9774 
9775   case ICmpInst::ICMP_SGE:
9776     std::swap(LHS, RHS);
9777     LLVM_FALLTHROUGH;
9778   case ICmpInst::ICMP_SLE:
9779     return
9780       // min(A, ...) <= A
9781       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9782       // A <= max(A, ...)
9783       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9784 
9785   case ICmpInst::ICMP_UGE:
9786     std::swap(LHS, RHS);
9787     LLVM_FALLTHROUGH;
9788   case ICmpInst::ICMP_ULE:
9789     return
9790       // min(A, ...) <= A
9791       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9792       // A <= max(A, ...)
9793       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9794   }
9795 
9796   llvm_unreachable("covered switch fell through?!");
9797 }
9798 
9799 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9800                                              const SCEV *LHS, const SCEV *RHS,
9801                                              const SCEV *FoundLHS,
9802                                              const SCEV *FoundRHS,
9803                                              unsigned Depth) {
9804   assert(getTypeSizeInBits(LHS->getType()) ==
9805              getTypeSizeInBits(RHS->getType()) &&
9806          "LHS and RHS have different sizes?");
9807   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9808              getTypeSizeInBits(FoundRHS->getType()) &&
9809          "FoundLHS and FoundRHS have different sizes?");
9810   // We want to avoid hurting the compile time with analysis of too big trees.
9811   if (Depth > MaxSCEVOperationsImplicationDepth)
9812     return false;
9813   // We only want to work with ICMP_SGT comparison so far.
9814   // TODO: Extend to ICMP_UGT?
9815   if (Pred == ICmpInst::ICMP_SLT) {
9816     Pred = ICmpInst::ICMP_SGT;
9817     std::swap(LHS, RHS);
9818     std::swap(FoundLHS, FoundRHS);
9819   }
9820   if (Pred != ICmpInst::ICMP_SGT)
9821     return false;
9822 
9823   auto GetOpFromSExt = [&](const SCEV *S) {
9824     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9825       return Ext->getOperand();
9826     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9827     // the constant in some cases.
9828     return S;
9829   };
9830 
9831   // Acquire values from extensions.
9832   auto *OrigLHS = LHS;
9833   auto *OrigFoundLHS = FoundLHS;
9834   LHS = GetOpFromSExt(LHS);
9835   FoundLHS = GetOpFromSExt(FoundLHS);
9836 
9837   // Is the SGT predicate can be proved trivially or using the found context.
9838   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9839     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9840            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9841                                   FoundRHS, Depth + 1);
9842   };
9843 
9844   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9845     // We want to avoid creation of any new non-constant SCEV. Since we are
9846     // going to compare the operands to RHS, we should be certain that we don't
9847     // need any size extensions for this. So let's decline all cases when the
9848     // sizes of types of LHS and RHS do not match.
9849     // TODO: Maybe try to get RHS from sext to catch more cases?
9850     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9851       return false;
9852 
9853     // Should not overflow.
9854     if (!LHSAddExpr->hasNoSignedWrap())
9855       return false;
9856 
9857     auto *LL = LHSAddExpr->getOperand(0);
9858     auto *LR = LHSAddExpr->getOperand(1);
9859     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9860 
9861     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9862     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9863       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9864     };
9865     // Try to prove the following rule:
9866     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9867     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9868     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9869       return true;
9870   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9871     Value *LL, *LR;
9872     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9873 
9874     using namespace llvm::PatternMatch;
9875 
9876     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9877       // Rules for division.
9878       // We are going to perform some comparisons with Denominator and its
9879       // derivative expressions. In general case, creating a SCEV for it may
9880       // lead to a complex analysis of the entire graph, and in particular it
9881       // can request trip count recalculation for the same loop. This would
9882       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9883       // this, we only want to create SCEVs that are constants in this section.
9884       // So we bail if Denominator is not a constant.
9885       if (!isa<ConstantInt>(LR))
9886         return false;
9887 
9888       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9889 
9890       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9891       // then a SCEV for the numerator already exists and matches with FoundLHS.
9892       auto *Numerator = getExistingSCEV(LL);
9893       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9894         return false;
9895 
9896       // Make sure that the numerator matches with FoundLHS and the denominator
9897       // is positive.
9898       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9899         return false;
9900 
9901       auto *DTy = Denominator->getType();
9902       auto *FRHSTy = FoundRHS->getType();
9903       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9904         // One of types is a pointer and another one is not. We cannot extend
9905         // them properly to a wider type, so let us just reject this case.
9906         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9907         // to avoid this check.
9908         return false;
9909 
9910       // Given that:
9911       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9912       auto *WTy = getWiderType(DTy, FRHSTy);
9913       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9914       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9915 
9916       // Try to prove the following rule:
9917       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9918       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9919       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9920       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9921       if (isKnownNonPositive(RHS) &&
9922           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9923         return true;
9924 
9925       // Try to prove the following rule:
9926       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9927       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9928       // If we divide it by Denominator > 2, then:
9929       // 1. If FoundLHS is negative, then the result is 0.
9930       // 2. If FoundLHS is non-negative, then the result is non-negative.
9931       // Anyways, the result is non-negative.
9932       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9933       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9934       if (isKnownNegative(RHS) &&
9935           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9936         return true;
9937     }
9938   }
9939 
9940   // If our expression contained SCEVUnknown Phis, and we split it down and now
9941   // need to prove something for them, try to prove the predicate for every
9942   // possible incoming values of those Phis.
9943   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
9944     return true;
9945 
9946   return false;
9947 }
9948 
9949 bool
9950 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
9951                                            const SCEV *LHS, const SCEV *RHS) {
9952   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9953          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9954          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9955          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9956 }
9957 
9958 bool
9959 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9960                                              const SCEV *LHS, const SCEV *RHS,
9961                                              const SCEV *FoundLHS,
9962                                              const SCEV *FoundRHS) {
9963   switch (Pred) {
9964   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9965   case ICmpInst::ICMP_EQ:
9966   case ICmpInst::ICMP_NE:
9967     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9968       return true;
9969     break;
9970   case ICmpInst::ICMP_SLT:
9971   case ICmpInst::ICMP_SLE:
9972     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9973         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9974       return true;
9975     break;
9976   case ICmpInst::ICMP_SGT:
9977   case ICmpInst::ICMP_SGE:
9978     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9979         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9980       return true;
9981     break;
9982   case ICmpInst::ICMP_ULT:
9983   case ICmpInst::ICMP_ULE:
9984     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9985         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9986       return true;
9987     break;
9988   case ICmpInst::ICMP_UGT:
9989   case ICmpInst::ICMP_UGE:
9990     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9991         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9992       return true;
9993     break;
9994   }
9995 
9996   // Maybe it can be proved via operations?
9997   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9998     return true;
9999 
10000   return false;
10001 }
10002 
10003 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10004                                                      const SCEV *LHS,
10005                                                      const SCEV *RHS,
10006                                                      const SCEV *FoundLHS,
10007                                                      const SCEV *FoundRHS) {
10008   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10009     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10010     // reduce the compile time impact of this optimization.
10011     return false;
10012 
10013   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10014   if (!Addend)
10015     return false;
10016 
10017   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10018 
10019   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10020   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10021   ConstantRange FoundLHSRange =
10022       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10023 
10024   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10025   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10026 
10027   // We can also compute the range of values for `LHS` that satisfy the
10028   // consequent, "`LHS` `Pred` `RHS`":
10029   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10030   ConstantRange SatisfyingLHSRange =
10031       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10032 
10033   // The antecedent implies the consequent if every value of `LHS` that
10034   // satisfies the antecedent also satisfies the consequent.
10035   return SatisfyingLHSRange.contains(LHSRange);
10036 }
10037 
10038 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10039                                          bool IsSigned, bool NoWrap) {
10040   assert(isKnownPositive(Stride) && "Positive stride expected!");
10041 
10042   if (NoWrap) return false;
10043 
10044   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10045   const SCEV *One = getOne(Stride->getType());
10046 
10047   if (IsSigned) {
10048     APInt MaxRHS = getSignedRangeMax(RHS);
10049     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10050     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10051 
10052     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10053     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10054   }
10055 
10056   APInt MaxRHS = getUnsignedRangeMax(RHS);
10057   APInt MaxValue = APInt::getMaxValue(BitWidth);
10058   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10059 
10060   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10061   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10062 }
10063 
10064 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10065                                          bool IsSigned, bool NoWrap) {
10066   if (NoWrap) return false;
10067 
10068   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10069   const SCEV *One = getOne(Stride->getType());
10070 
10071   if (IsSigned) {
10072     APInt MinRHS = getSignedRangeMin(RHS);
10073     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10074     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10075 
10076     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10077     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10078   }
10079 
10080   APInt MinRHS = getUnsignedRangeMin(RHS);
10081   APInt MinValue = APInt::getMinValue(BitWidth);
10082   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10083 
10084   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10085   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10086 }
10087 
10088 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10089                                             bool Equality) {
10090   const SCEV *One = getOne(Step->getType());
10091   Delta = Equality ? getAddExpr(Delta, Step)
10092                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10093   return getUDivExpr(Delta, Step);
10094 }
10095 
10096 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10097                                                     const SCEV *Stride,
10098                                                     const SCEV *End,
10099                                                     unsigned BitWidth,
10100                                                     bool IsSigned) {
10101 
10102   assert(!isKnownNonPositive(Stride) &&
10103          "Stride is expected strictly positive!");
10104   // Calculate the maximum backedge count based on the range of values
10105   // permitted by Start, End, and Stride.
10106   const SCEV *MaxBECount;
10107   APInt MinStart =
10108       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10109 
10110   APInt StrideForMaxBECount =
10111       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10112 
10113   // We already know that the stride is positive, so we paper over conservatism
10114   // in our range computation by forcing StrideForMaxBECount to be at least one.
10115   // In theory this is unnecessary, but we expect MaxBECount to be a
10116   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10117   // is nothing to constant fold it to).
10118   APInt One(BitWidth, 1, IsSigned);
10119   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10120 
10121   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10122                             : APInt::getMaxValue(BitWidth);
10123   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10124 
10125   // Although End can be a MAX expression we estimate MaxEnd considering only
10126   // the case End = RHS of the loop termination condition. This is safe because
10127   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10128   // taken count.
10129   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10130                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10131 
10132   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10133                               getConstant(StrideForMaxBECount) /* Step */,
10134                               false /* Equality */);
10135 
10136   return MaxBECount;
10137 }
10138 
10139 ScalarEvolution::ExitLimit
10140 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10141                                   const Loop *L, bool IsSigned,
10142                                   bool ControlsExit, bool AllowPredicates) {
10143   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10144 
10145   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10146   bool PredicatedIV = false;
10147 
10148   if (!IV && AllowPredicates) {
10149     // Try to make this an AddRec using runtime tests, in the first X
10150     // iterations of this loop, where X is the SCEV expression found by the
10151     // algorithm below.
10152     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10153     PredicatedIV = true;
10154   }
10155 
10156   // Avoid weird loops
10157   if (!IV || IV->getLoop() != L || !IV->isAffine())
10158     return getCouldNotCompute();
10159 
10160   bool NoWrap = ControlsExit &&
10161                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10162 
10163   const SCEV *Stride = IV->getStepRecurrence(*this);
10164 
10165   bool PositiveStride = isKnownPositive(Stride);
10166 
10167   // Avoid negative or zero stride values.
10168   if (!PositiveStride) {
10169     // We can compute the correct backedge taken count for loops with unknown
10170     // strides if we can prove that the loop is not an infinite loop with side
10171     // effects. Here's the loop structure we are trying to handle -
10172     //
10173     // i = start
10174     // do {
10175     //   A[i] = i;
10176     //   i += s;
10177     // } while (i < end);
10178     //
10179     // The backedge taken count for such loops is evaluated as -
10180     // (max(end, start + stride) - start - 1) /u stride
10181     //
10182     // The additional preconditions that we need to check to prove correctness
10183     // of the above formula is as follows -
10184     //
10185     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10186     //    NoWrap flag).
10187     // b) loop is single exit with no side effects.
10188     //
10189     //
10190     // Precondition a) implies that if the stride is negative, this is a single
10191     // trip loop. The backedge taken count formula reduces to zero in this case.
10192     //
10193     // Precondition b) implies that the unknown stride cannot be zero otherwise
10194     // we have UB.
10195     //
10196     // The positive stride case is the same as isKnownPositive(Stride) returning
10197     // true (original behavior of the function).
10198     //
10199     // We want to make sure that the stride is truly unknown as there are edge
10200     // cases where ScalarEvolution propagates no wrap flags to the
10201     // post-increment/decrement IV even though the increment/decrement operation
10202     // itself is wrapping. The computed backedge taken count may be wrong in
10203     // such cases. This is prevented by checking that the stride is not known to
10204     // be either positive or non-positive. For example, no wrap flags are
10205     // propagated to the post-increment IV of this loop with a trip count of 2 -
10206     //
10207     // unsigned char i;
10208     // for(i=127; i<128; i+=129)
10209     //   A[i] = i;
10210     //
10211     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10212         !loopHasNoSideEffects(L))
10213       return getCouldNotCompute();
10214   } else if (!Stride->isOne() &&
10215              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10216     // Avoid proven overflow cases: this will ensure that the backedge taken
10217     // count will not generate any unsigned overflow. Relaxed no-overflow
10218     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10219     // undefined behaviors like the case of C language.
10220     return getCouldNotCompute();
10221 
10222   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10223                                       : ICmpInst::ICMP_ULT;
10224   const SCEV *Start = IV->getStart();
10225   const SCEV *End = RHS;
10226   // When the RHS is not invariant, we do not know the end bound of the loop and
10227   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10228   // calculate the MaxBECount, given the start, stride and max value for the end
10229   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10230   // checked above).
10231   if (!isLoopInvariant(RHS, L)) {
10232     const SCEV *MaxBECount = computeMaxBECountForLT(
10233         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10234     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10235                      false /*MaxOrZero*/, Predicates);
10236   }
10237   // If the backedge is taken at least once, then it will be taken
10238   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10239   // is the LHS value of the less-than comparison the first time it is evaluated
10240   // and End is the RHS.
10241   const SCEV *BECountIfBackedgeTaken =
10242     computeBECount(getMinusSCEV(End, Start), Stride, false);
10243   // If the loop entry is guarded by the result of the backedge test of the
10244   // first loop iteration, then we know the backedge will be taken at least
10245   // once and so the backedge taken count is as above. If not then we use the
10246   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10247   // as if the backedge is taken at least once max(End,Start) is End and so the
10248   // result is as above, and if not max(End,Start) is Start so we get a backedge
10249   // count of zero.
10250   const SCEV *BECount;
10251   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10252     BECount = BECountIfBackedgeTaken;
10253   else {
10254     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10255     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10256   }
10257 
10258   const SCEV *MaxBECount;
10259   bool MaxOrZero = false;
10260   if (isa<SCEVConstant>(BECount))
10261     MaxBECount = BECount;
10262   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10263     // If we know exactly how many times the backedge will be taken if it's
10264     // taken at least once, then the backedge count will either be that or
10265     // zero.
10266     MaxBECount = BECountIfBackedgeTaken;
10267     MaxOrZero = true;
10268   } else {
10269     MaxBECount = computeMaxBECountForLT(
10270         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10271   }
10272 
10273   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10274       !isa<SCEVCouldNotCompute>(BECount))
10275     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10276 
10277   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10278 }
10279 
10280 ScalarEvolution::ExitLimit
10281 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10282                                      const Loop *L, bool IsSigned,
10283                                      bool ControlsExit, bool AllowPredicates) {
10284   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10285   // We handle only IV > Invariant
10286   if (!isLoopInvariant(RHS, L))
10287     return getCouldNotCompute();
10288 
10289   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10290   if (!IV && AllowPredicates)
10291     // Try to make this an AddRec using runtime tests, in the first X
10292     // iterations of this loop, where X is the SCEV expression found by the
10293     // algorithm below.
10294     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10295 
10296   // Avoid weird loops
10297   if (!IV || IV->getLoop() != L || !IV->isAffine())
10298     return getCouldNotCompute();
10299 
10300   bool NoWrap = ControlsExit &&
10301                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10302 
10303   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10304 
10305   // Avoid negative or zero stride values
10306   if (!isKnownPositive(Stride))
10307     return getCouldNotCompute();
10308 
10309   // Avoid proven overflow cases: this will ensure that the backedge taken count
10310   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10311   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10312   // behaviors like the case of C language.
10313   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10314     return getCouldNotCompute();
10315 
10316   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10317                                       : ICmpInst::ICMP_UGT;
10318 
10319   const SCEV *Start = IV->getStart();
10320   const SCEV *End = RHS;
10321   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10322     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10323 
10324   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10325 
10326   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10327                             : getUnsignedRangeMax(Start);
10328 
10329   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10330                              : getUnsignedRangeMin(Stride);
10331 
10332   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10333   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10334                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10335 
10336   // Although End can be a MIN expression we estimate MinEnd considering only
10337   // the case End = RHS. This is safe because in the other case (Start - End)
10338   // is zero, leading to a zero maximum backedge taken count.
10339   APInt MinEnd =
10340     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10341              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10342 
10343 
10344   const SCEV *MaxBECount = getCouldNotCompute();
10345   if (isa<SCEVConstant>(BECount))
10346     MaxBECount = BECount;
10347   else
10348     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10349                                 getConstant(MinStride), false);
10350 
10351   if (isa<SCEVCouldNotCompute>(MaxBECount))
10352     MaxBECount = BECount;
10353 
10354   return ExitLimit(BECount, MaxBECount, false, Predicates);
10355 }
10356 
10357 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10358                                                     ScalarEvolution &SE) const {
10359   if (Range.isFullSet())  // Infinite loop.
10360     return SE.getCouldNotCompute();
10361 
10362   // If the start is a non-zero constant, shift the range to simplify things.
10363   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10364     if (!SC->getValue()->isZero()) {
10365       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10366       Operands[0] = SE.getZero(SC->getType());
10367       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10368                                              getNoWrapFlags(FlagNW));
10369       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10370         return ShiftedAddRec->getNumIterationsInRange(
10371             Range.subtract(SC->getAPInt()), SE);
10372       // This is strange and shouldn't happen.
10373       return SE.getCouldNotCompute();
10374     }
10375 
10376   // The only time we can solve this is when we have all constant indices.
10377   // Otherwise, we cannot determine the overflow conditions.
10378   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10379     return SE.getCouldNotCompute();
10380 
10381   // Okay at this point we know that all elements of the chrec are constants and
10382   // that the start element is zero.
10383 
10384   // First check to see if the range contains zero.  If not, the first
10385   // iteration exits.
10386   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10387   if (!Range.contains(APInt(BitWidth, 0)))
10388     return SE.getZero(getType());
10389 
10390   if (isAffine()) {
10391     // If this is an affine expression then we have this situation:
10392     //   Solve {0,+,A} in Range  ===  Ax in Range
10393 
10394     // We know that zero is in the range.  If A is positive then we know that
10395     // the upper value of the range must be the first possible exit value.
10396     // If A is negative then the lower of the range is the last possible loop
10397     // value.  Also note that we already checked for a full range.
10398     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10399     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10400 
10401     // The exit value should be (End+A)/A.
10402     APInt ExitVal = (End + A).udiv(A);
10403     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10404 
10405     // Evaluate at the exit value.  If we really did fall out of the valid
10406     // range, then we computed our trip count, otherwise wrap around or other
10407     // things must have happened.
10408     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10409     if (Range.contains(Val->getValue()))
10410       return SE.getCouldNotCompute();  // Something strange happened
10411 
10412     // Ensure that the previous value is in the range.  This is a sanity check.
10413     assert(Range.contains(
10414            EvaluateConstantChrecAtConstant(this,
10415            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10416            "Linear scev computation is off in a bad way!");
10417     return SE.getConstant(ExitValue);
10418   } else if (isQuadratic()) {
10419     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10420     // quadratic equation to solve it.  To do this, we must frame our problem in
10421     // terms of figuring out when zero is crossed, instead of when
10422     // Range.getUpper() is crossed.
10423     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10424     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10425     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10426 
10427     // Next, solve the constructed addrec
10428     if (auto Roots =
10429             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10430       const SCEVConstant *R1 = Roots->first;
10431       const SCEVConstant *R2 = Roots->second;
10432       // Pick the smallest positive root value.
10433       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10434               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10435         if (!CB->getZExtValue())
10436           std::swap(R1, R2); // R1 is the minimum root now.
10437 
10438         // Make sure the root is not off by one.  The returned iteration should
10439         // not be in the range, but the previous one should be.  When solving
10440         // for "X*X < 5", for example, we should not return a root of 2.
10441         ConstantInt *R1Val =
10442             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10443         if (Range.contains(R1Val->getValue())) {
10444           // The next iteration must be out of the range...
10445           ConstantInt *NextVal =
10446               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10447 
10448           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10449           if (!Range.contains(R1Val->getValue()))
10450             return SE.getConstant(NextVal);
10451           return SE.getCouldNotCompute(); // Something strange happened
10452         }
10453 
10454         // If R1 was not in the range, then it is a good return value.  Make
10455         // sure that R1-1 WAS in the range though, just in case.
10456         ConstantInt *NextVal =
10457             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10458         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10459         if (Range.contains(R1Val->getValue()))
10460           return R1;
10461         return SE.getCouldNotCompute(); // Something strange happened
10462       }
10463     }
10464   }
10465 
10466   return SE.getCouldNotCompute();
10467 }
10468 
10469 const SCEVAddRecExpr *
10470 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10471   assert(getNumOperands() > 1 && "AddRec with zero step?");
10472   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10473   // but in this case we cannot guarantee that the value returned will be an
10474   // AddRec because SCEV does not have a fixed point where it stops
10475   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10476   // may happen if we reach arithmetic depth limit while simplifying. So we
10477   // construct the returned value explicitly.
10478   SmallVector<const SCEV *, 3> Ops;
10479   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10480   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10481   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10482     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10483   // We know that the last operand is not a constant zero (otherwise it would
10484   // have been popped out earlier). This guarantees us that if the result has
10485   // the same last operand, then it will also not be popped out, meaning that
10486   // the returned value will be an AddRec.
10487   const SCEV *Last = getOperand(getNumOperands() - 1);
10488   assert(!Last->isZero() && "Recurrency with zero step?");
10489   Ops.push_back(Last);
10490   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10491                                                SCEV::FlagAnyWrap));
10492 }
10493 
10494 // Return true when S contains at least an undef value.
10495 static inline bool containsUndefs(const SCEV *S) {
10496   return SCEVExprContains(S, [](const SCEV *S) {
10497     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10498       return isa<UndefValue>(SU->getValue());
10499     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10500       return isa<UndefValue>(SC->getValue());
10501     return false;
10502   });
10503 }
10504 
10505 namespace {
10506 
10507 // Collect all steps of SCEV expressions.
10508 struct SCEVCollectStrides {
10509   ScalarEvolution &SE;
10510   SmallVectorImpl<const SCEV *> &Strides;
10511 
10512   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10513       : SE(SE), Strides(S) {}
10514 
10515   bool follow(const SCEV *S) {
10516     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10517       Strides.push_back(AR->getStepRecurrence(SE));
10518     return true;
10519   }
10520 
10521   bool isDone() const { return false; }
10522 };
10523 
10524 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10525 struct SCEVCollectTerms {
10526   SmallVectorImpl<const SCEV *> &Terms;
10527 
10528   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10529 
10530   bool follow(const SCEV *S) {
10531     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10532         isa<SCEVSignExtendExpr>(S)) {
10533       if (!containsUndefs(S))
10534         Terms.push_back(S);
10535 
10536       // Stop recursion: once we collected a term, do not walk its operands.
10537       return false;
10538     }
10539 
10540     // Keep looking.
10541     return true;
10542   }
10543 
10544   bool isDone() const { return false; }
10545 };
10546 
10547 // Check if a SCEV contains an AddRecExpr.
10548 struct SCEVHasAddRec {
10549   bool &ContainsAddRec;
10550 
10551   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10552     ContainsAddRec = false;
10553   }
10554 
10555   bool follow(const SCEV *S) {
10556     if (isa<SCEVAddRecExpr>(S)) {
10557       ContainsAddRec = true;
10558 
10559       // Stop recursion: once we collected a term, do not walk its operands.
10560       return false;
10561     }
10562 
10563     // Keep looking.
10564     return true;
10565   }
10566 
10567   bool isDone() const { return false; }
10568 };
10569 
10570 // Find factors that are multiplied with an expression that (possibly as a
10571 // subexpression) contains an AddRecExpr. In the expression:
10572 //
10573 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10574 //
10575 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10576 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10577 // parameters as they form a product with an induction variable.
10578 //
10579 // This collector expects all array size parameters to be in the same MulExpr.
10580 // It might be necessary to later add support for collecting parameters that are
10581 // spread over different nested MulExpr.
10582 struct SCEVCollectAddRecMultiplies {
10583   SmallVectorImpl<const SCEV *> &Terms;
10584   ScalarEvolution &SE;
10585 
10586   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10587       : Terms(T), SE(SE) {}
10588 
10589   bool follow(const SCEV *S) {
10590     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10591       bool HasAddRec = false;
10592       SmallVector<const SCEV *, 0> Operands;
10593       for (auto Op : Mul->operands()) {
10594         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10595         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10596           Operands.push_back(Op);
10597         } else if (Unknown) {
10598           HasAddRec = true;
10599         } else {
10600           bool ContainsAddRec;
10601           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10602           visitAll(Op, ContiansAddRec);
10603           HasAddRec |= ContainsAddRec;
10604         }
10605       }
10606       if (Operands.size() == 0)
10607         return true;
10608 
10609       if (!HasAddRec)
10610         return false;
10611 
10612       Terms.push_back(SE.getMulExpr(Operands));
10613       // Stop recursion: once we collected a term, do not walk its operands.
10614       return false;
10615     }
10616 
10617     // Keep looking.
10618     return true;
10619   }
10620 
10621   bool isDone() const { return false; }
10622 };
10623 
10624 } // end anonymous namespace
10625 
10626 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10627 /// two places:
10628 ///   1) The strides of AddRec expressions.
10629 ///   2) Unknowns that are multiplied with AddRec expressions.
10630 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10631     SmallVectorImpl<const SCEV *> &Terms) {
10632   SmallVector<const SCEV *, 4> Strides;
10633   SCEVCollectStrides StrideCollector(*this, Strides);
10634   visitAll(Expr, StrideCollector);
10635 
10636   LLVM_DEBUG({
10637     dbgs() << "Strides:\n";
10638     for (const SCEV *S : Strides)
10639       dbgs() << *S << "\n";
10640   });
10641 
10642   for (const SCEV *S : Strides) {
10643     SCEVCollectTerms TermCollector(Terms);
10644     visitAll(S, TermCollector);
10645   }
10646 
10647   LLVM_DEBUG({
10648     dbgs() << "Terms:\n";
10649     for (const SCEV *T : Terms)
10650       dbgs() << *T << "\n";
10651   });
10652 
10653   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10654   visitAll(Expr, MulCollector);
10655 }
10656 
10657 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10658                                    SmallVectorImpl<const SCEV *> &Terms,
10659                                    SmallVectorImpl<const SCEV *> &Sizes) {
10660   int Last = Terms.size() - 1;
10661   const SCEV *Step = Terms[Last];
10662 
10663   // End of recursion.
10664   if (Last == 0) {
10665     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10666       SmallVector<const SCEV *, 2> Qs;
10667       for (const SCEV *Op : M->operands())
10668         if (!isa<SCEVConstant>(Op))
10669           Qs.push_back(Op);
10670 
10671       Step = SE.getMulExpr(Qs);
10672     }
10673 
10674     Sizes.push_back(Step);
10675     return true;
10676   }
10677 
10678   for (const SCEV *&Term : Terms) {
10679     // Normalize the terms before the next call to findArrayDimensionsRec.
10680     const SCEV *Q, *R;
10681     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10682 
10683     // Bail out when GCD does not evenly divide one of the terms.
10684     if (!R->isZero())
10685       return false;
10686 
10687     Term = Q;
10688   }
10689 
10690   // Remove all SCEVConstants.
10691   Terms.erase(
10692       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10693       Terms.end());
10694 
10695   if (Terms.size() > 0)
10696     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10697       return false;
10698 
10699   Sizes.push_back(Step);
10700   return true;
10701 }
10702 
10703 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10704 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10705   for (const SCEV *T : Terms)
10706     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10707       return true;
10708   return false;
10709 }
10710 
10711 // Return the number of product terms in S.
10712 static inline int numberOfTerms(const SCEV *S) {
10713   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10714     return Expr->getNumOperands();
10715   return 1;
10716 }
10717 
10718 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10719   if (isa<SCEVConstant>(T))
10720     return nullptr;
10721 
10722   if (isa<SCEVUnknown>(T))
10723     return T;
10724 
10725   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10726     SmallVector<const SCEV *, 2> Factors;
10727     for (const SCEV *Op : M->operands())
10728       if (!isa<SCEVConstant>(Op))
10729         Factors.push_back(Op);
10730 
10731     return SE.getMulExpr(Factors);
10732   }
10733 
10734   return T;
10735 }
10736 
10737 /// Return the size of an element read or written by Inst.
10738 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10739   Type *Ty;
10740   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10741     Ty = Store->getValueOperand()->getType();
10742   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10743     Ty = Load->getType();
10744   else
10745     return nullptr;
10746 
10747   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10748   return getSizeOfExpr(ETy, Ty);
10749 }
10750 
10751 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10752                                           SmallVectorImpl<const SCEV *> &Sizes,
10753                                           const SCEV *ElementSize) {
10754   if (Terms.size() < 1 || !ElementSize)
10755     return;
10756 
10757   // Early return when Terms do not contain parameters: we do not delinearize
10758   // non parametric SCEVs.
10759   if (!containsParameters(Terms))
10760     return;
10761 
10762   LLVM_DEBUG({
10763     dbgs() << "Terms:\n";
10764     for (const SCEV *T : Terms)
10765       dbgs() << *T << "\n";
10766   });
10767 
10768   // Remove duplicates.
10769   array_pod_sort(Terms.begin(), Terms.end());
10770   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10771 
10772   // Put larger terms first.
10773   llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10774     return numberOfTerms(LHS) > numberOfTerms(RHS);
10775   });
10776 
10777   // Try to divide all terms by the element size. If term is not divisible by
10778   // element size, proceed with the original term.
10779   for (const SCEV *&Term : Terms) {
10780     const SCEV *Q, *R;
10781     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10782     if (!Q->isZero())
10783       Term = Q;
10784   }
10785 
10786   SmallVector<const SCEV *, 4> NewTerms;
10787 
10788   // Remove constant factors.
10789   for (const SCEV *T : Terms)
10790     if (const SCEV *NewT = removeConstantFactors(*this, T))
10791       NewTerms.push_back(NewT);
10792 
10793   LLVM_DEBUG({
10794     dbgs() << "Terms after sorting:\n";
10795     for (const SCEV *T : NewTerms)
10796       dbgs() << *T << "\n";
10797   });
10798 
10799   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10800     Sizes.clear();
10801     return;
10802   }
10803 
10804   // The last element to be pushed into Sizes is the size of an element.
10805   Sizes.push_back(ElementSize);
10806 
10807   LLVM_DEBUG({
10808     dbgs() << "Sizes:\n";
10809     for (const SCEV *S : Sizes)
10810       dbgs() << *S << "\n";
10811   });
10812 }
10813 
10814 void ScalarEvolution::computeAccessFunctions(
10815     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10816     SmallVectorImpl<const SCEV *> &Sizes) {
10817   // Early exit in case this SCEV is not an affine multivariate function.
10818   if (Sizes.empty())
10819     return;
10820 
10821   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10822     if (!AR->isAffine())
10823       return;
10824 
10825   const SCEV *Res = Expr;
10826   int Last = Sizes.size() - 1;
10827   for (int i = Last; i >= 0; i--) {
10828     const SCEV *Q, *R;
10829     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10830 
10831     LLVM_DEBUG({
10832       dbgs() << "Res: " << *Res << "\n";
10833       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10834       dbgs() << "Res divided by Sizes[i]:\n";
10835       dbgs() << "Quotient: " << *Q << "\n";
10836       dbgs() << "Remainder: " << *R << "\n";
10837     });
10838 
10839     Res = Q;
10840 
10841     // Do not record the last subscript corresponding to the size of elements in
10842     // the array.
10843     if (i == Last) {
10844 
10845       // Bail out if the remainder is too complex.
10846       if (isa<SCEVAddRecExpr>(R)) {
10847         Subscripts.clear();
10848         Sizes.clear();
10849         return;
10850       }
10851 
10852       continue;
10853     }
10854 
10855     // Record the access function for the current subscript.
10856     Subscripts.push_back(R);
10857   }
10858 
10859   // Also push in last position the remainder of the last division: it will be
10860   // the access function of the innermost dimension.
10861   Subscripts.push_back(Res);
10862 
10863   std::reverse(Subscripts.begin(), Subscripts.end());
10864 
10865   LLVM_DEBUG({
10866     dbgs() << "Subscripts:\n";
10867     for (const SCEV *S : Subscripts)
10868       dbgs() << *S << "\n";
10869   });
10870 }
10871 
10872 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10873 /// sizes of an array access. Returns the remainder of the delinearization that
10874 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10875 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10876 /// expressions in the stride and base of a SCEV corresponding to the
10877 /// computation of a GCD (greatest common divisor) of base and stride.  When
10878 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10879 ///
10880 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10881 ///
10882 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10883 ///
10884 ///    for (long i = 0; i < n; i++)
10885 ///      for (long j = 0; j < m; j++)
10886 ///        for (long k = 0; k < o; k++)
10887 ///          A[i][j][k] = 1.0;
10888 ///  }
10889 ///
10890 /// the delinearization input is the following AddRec SCEV:
10891 ///
10892 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10893 ///
10894 /// From this SCEV, we are able to say that the base offset of the access is %A
10895 /// because it appears as an offset that does not divide any of the strides in
10896 /// the loops:
10897 ///
10898 ///  CHECK: Base offset: %A
10899 ///
10900 /// and then SCEV->delinearize determines the size of some of the dimensions of
10901 /// the array as these are the multiples by which the strides are happening:
10902 ///
10903 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10904 ///
10905 /// Note that the outermost dimension remains of UnknownSize because there are
10906 /// no strides that would help identifying the size of the last dimension: when
10907 /// the array has been statically allocated, one could compute the size of that
10908 /// dimension by dividing the overall size of the array by the size of the known
10909 /// dimensions: %m * %o * 8.
10910 ///
10911 /// Finally delinearize provides the access functions for the array reference
10912 /// that does correspond to A[i][j][k] of the above C testcase:
10913 ///
10914 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10915 ///
10916 /// The testcases are checking the output of a function pass:
10917 /// DelinearizationPass that walks through all loads and stores of a function
10918 /// asking for the SCEV of the memory access with respect to all enclosing
10919 /// loops, calling SCEV->delinearize on that and printing the results.
10920 void ScalarEvolution::delinearize(const SCEV *Expr,
10921                                  SmallVectorImpl<const SCEV *> &Subscripts,
10922                                  SmallVectorImpl<const SCEV *> &Sizes,
10923                                  const SCEV *ElementSize) {
10924   // First step: collect parametric terms.
10925   SmallVector<const SCEV *, 4> Terms;
10926   collectParametricTerms(Expr, Terms);
10927 
10928   if (Terms.empty())
10929     return;
10930 
10931   // Second step: find subscript sizes.
10932   findArrayDimensions(Terms, Sizes, ElementSize);
10933 
10934   if (Sizes.empty())
10935     return;
10936 
10937   // Third step: compute the access functions for each subscript.
10938   computeAccessFunctions(Expr, Subscripts, Sizes);
10939 
10940   if (Subscripts.empty())
10941     return;
10942 
10943   LLVM_DEBUG({
10944     dbgs() << "succeeded to delinearize " << *Expr << "\n";
10945     dbgs() << "ArrayDecl[UnknownSize]";
10946     for (const SCEV *S : Sizes)
10947       dbgs() << "[" << *S << "]";
10948 
10949     dbgs() << "\nArrayRef";
10950     for (const SCEV *S : Subscripts)
10951       dbgs() << "[" << *S << "]";
10952     dbgs() << "\n";
10953   });
10954 }
10955 
10956 //===----------------------------------------------------------------------===//
10957 //                   SCEVCallbackVH Class Implementation
10958 //===----------------------------------------------------------------------===//
10959 
10960 void ScalarEvolution::SCEVCallbackVH::deleted() {
10961   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10962   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10963     SE->ConstantEvolutionLoopExitValue.erase(PN);
10964   SE->eraseValueFromMap(getValPtr());
10965   // this now dangles!
10966 }
10967 
10968 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10969   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10970 
10971   // Forget all the expressions associated with users of the old value,
10972   // so that future queries will recompute the expressions using the new
10973   // value.
10974   Value *Old = getValPtr();
10975   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10976   SmallPtrSet<User *, 8> Visited;
10977   while (!Worklist.empty()) {
10978     User *U = Worklist.pop_back_val();
10979     // Deleting the Old value will cause this to dangle. Postpone
10980     // that until everything else is done.
10981     if (U == Old)
10982       continue;
10983     if (!Visited.insert(U).second)
10984       continue;
10985     if (PHINode *PN = dyn_cast<PHINode>(U))
10986       SE->ConstantEvolutionLoopExitValue.erase(PN);
10987     SE->eraseValueFromMap(U);
10988     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10989   }
10990   // Delete the Old value.
10991   if (PHINode *PN = dyn_cast<PHINode>(Old))
10992     SE->ConstantEvolutionLoopExitValue.erase(PN);
10993   SE->eraseValueFromMap(Old);
10994   // this now dangles!
10995 }
10996 
10997 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10998   : CallbackVH(V), SE(se) {}
10999 
11000 //===----------------------------------------------------------------------===//
11001 //                   ScalarEvolution Class Implementation
11002 //===----------------------------------------------------------------------===//
11003 
11004 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11005                                  AssumptionCache &AC, DominatorTree &DT,
11006                                  LoopInfo &LI)
11007     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11008       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11009       LoopDispositions(64), BlockDispositions(64) {
11010   // To use guards for proving predicates, we need to scan every instruction in
11011   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11012   // time if the IR does not actually contain any calls to
11013   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11014   //
11015   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11016   // to _add_ guards to the module when there weren't any before, and wants
11017   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11018   // efficient in lieu of being smart in that rather obscure case.
11019 
11020   auto *GuardDecl = F.getParent()->getFunction(
11021       Intrinsic::getName(Intrinsic::experimental_guard));
11022   HasGuards = GuardDecl && !GuardDecl->use_empty();
11023 }
11024 
11025 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11026     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11027       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11028       ValueExprMap(std::move(Arg.ValueExprMap)),
11029       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11030       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11031       PendingMerges(std::move(Arg.PendingMerges)),
11032       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11033       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11034       PredicatedBackedgeTakenCounts(
11035           std::move(Arg.PredicatedBackedgeTakenCounts)),
11036       ConstantEvolutionLoopExitValue(
11037           std::move(Arg.ConstantEvolutionLoopExitValue)),
11038       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11039       LoopDispositions(std::move(Arg.LoopDispositions)),
11040       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11041       BlockDispositions(std::move(Arg.BlockDispositions)),
11042       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11043       SignedRanges(std::move(Arg.SignedRanges)),
11044       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11045       UniquePreds(std::move(Arg.UniquePreds)),
11046       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11047       LoopUsers(std::move(Arg.LoopUsers)),
11048       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11049       FirstUnknown(Arg.FirstUnknown) {
11050   Arg.FirstUnknown = nullptr;
11051 }
11052 
11053 ScalarEvolution::~ScalarEvolution() {
11054   // Iterate through all the SCEVUnknown instances and call their
11055   // destructors, so that they release their references to their values.
11056   for (SCEVUnknown *U = FirstUnknown; U;) {
11057     SCEVUnknown *Tmp = U;
11058     U = U->Next;
11059     Tmp->~SCEVUnknown();
11060   }
11061   FirstUnknown = nullptr;
11062 
11063   ExprValueMap.clear();
11064   ValueExprMap.clear();
11065   HasRecMap.clear();
11066 
11067   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11068   // that a loop had multiple computable exits.
11069   for (auto &BTCI : BackedgeTakenCounts)
11070     BTCI.second.clear();
11071   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11072     BTCI.second.clear();
11073 
11074   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11075   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11076   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11077   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11078   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11079 }
11080 
11081 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11082   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11083 }
11084 
11085 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11086                           const Loop *L) {
11087   // Print all inner loops first
11088   for (Loop *I : *L)
11089     PrintLoopInfo(OS, SE, I);
11090 
11091   OS << "Loop ";
11092   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11093   OS << ": ";
11094 
11095   SmallVector<BasicBlock *, 8> ExitBlocks;
11096   L->getExitBlocks(ExitBlocks);
11097   if (ExitBlocks.size() != 1)
11098     OS << "<multiple exits> ";
11099 
11100   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11101     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
11102   } else {
11103     OS << "Unpredictable backedge-taken count. ";
11104   }
11105 
11106   OS << "\n"
11107         "Loop ";
11108   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11109   OS << ": ";
11110 
11111   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
11112     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
11113     if (SE->isBackedgeTakenCountMaxOrZero(L))
11114       OS << ", actual taken count either this or zero.";
11115   } else {
11116     OS << "Unpredictable max backedge-taken count. ";
11117   }
11118 
11119   OS << "\n"
11120         "Loop ";
11121   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11122   OS << ": ";
11123 
11124   SCEVUnionPredicate Pred;
11125   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11126   if (!isa<SCEVCouldNotCompute>(PBT)) {
11127     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11128     OS << " Predicates:\n";
11129     Pred.print(OS, 4);
11130   } else {
11131     OS << "Unpredictable predicated backedge-taken count. ";
11132   }
11133   OS << "\n";
11134 
11135   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11136     OS << "Loop ";
11137     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11138     OS << ": ";
11139     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11140   }
11141 }
11142 
11143 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11144   switch (LD) {
11145   case ScalarEvolution::LoopVariant:
11146     return "Variant";
11147   case ScalarEvolution::LoopInvariant:
11148     return "Invariant";
11149   case ScalarEvolution::LoopComputable:
11150     return "Computable";
11151   }
11152   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11153 }
11154 
11155 void ScalarEvolution::print(raw_ostream &OS) const {
11156   // ScalarEvolution's implementation of the print method is to print
11157   // out SCEV values of all instructions that are interesting. Doing
11158   // this potentially causes it to create new SCEV objects though,
11159   // which technically conflicts with the const qualifier. This isn't
11160   // observable from outside the class though, so casting away the
11161   // const isn't dangerous.
11162   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11163 
11164   OS << "Classifying expressions for: ";
11165   F.printAsOperand(OS, /*PrintType=*/false);
11166   OS << "\n";
11167   for (Instruction &I : instructions(F))
11168     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11169       OS << I << '\n';
11170       OS << "  -->  ";
11171       const SCEV *SV = SE.getSCEV(&I);
11172       SV->print(OS);
11173       if (!isa<SCEVCouldNotCompute>(SV)) {
11174         OS << " U: ";
11175         SE.getUnsignedRange(SV).print(OS);
11176         OS << " S: ";
11177         SE.getSignedRange(SV).print(OS);
11178       }
11179 
11180       const Loop *L = LI.getLoopFor(I.getParent());
11181 
11182       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11183       if (AtUse != SV) {
11184         OS << "  -->  ";
11185         AtUse->print(OS);
11186         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11187           OS << " U: ";
11188           SE.getUnsignedRange(AtUse).print(OS);
11189           OS << " S: ";
11190           SE.getSignedRange(AtUse).print(OS);
11191         }
11192       }
11193 
11194       if (L) {
11195         OS << "\t\t" "Exits: ";
11196         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11197         if (!SE.isLoopInvariant(ExitValue, L)) {
11198           OS << "<<Unknown>>";
11199         } else {
11200           OS << *ExitValue;
11201         }
11202 
11203         bool First = true;
11204         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11205           if (First) {
11206             OS << "\t\t" "LoopDispositions: { ";
11207             First = false;
11208           } else {
11209             OS << ", ";
11210           }
11211 
11212           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11213           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11214         }
11215 
11216         for (auto *InnerL : depth_first(L)) {
11217           if (InnerL == L)
11218             continue;
11219           if (First) {
11220             OS << "\t\t" "LoopDispositions: { ";
11221             First = false;
11222           } else {
11223             OS << ", ";
11224           }
11225 
11226           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11227           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11228         }
11229 
11230         OS << " }";
11231       }
11232 
11233       OS << "\n";
11234     }
11235 
11236   OS << "Determining loop execution counts for: ";
11237   F.printAsOperand(OS, /*PrintType=*/false);
11238   OS << "\n";
11239   for (Loop *I : LI)
11240     PrintLoopInfo(OS, &SE, I);
11241 }
11242 
11243 ScalarEvolution::LoopDisposition
11244 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11245   auto &Values = LoopDispositions[S];
11246   for (auto &V : Values) {
11247     if (V.getPointer() == L)
11248       return V.getInt();
11249   }
11250   Values.emplace_back(L, LoopVariant);
11251   LoopDisposition D = computeLoopDisposition(S, L);
11252   auto &Values2 = LoopDispositions[S];
11253   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11254     if (V.getPointer() == L) {
11255       V.setInt(D);
11256       break;
11257     }
11258   }
11259   return D;
11260 }
11261 
11262 ScalarEvolution::LoopDisposition
11263 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11264   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11265   case scConstant:
11266     return LoopInvariant;
11267   case scTruncate:
11268   case scZeroExtend:
11269   case scSignExtend:
11270     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11271   case scAddRecExpr: {
11272     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11273 
11274     // If L is the addrec's loop, it's computable.
11275     if (AR->getLoop() == L)
11276       return LoopComputable;
11277 
11278     // Add recurrences are never invariant in the function-body (null loop).
11279     if (!L)
11280       return LoopVariant;
11281 
11282     // Everything that is not defined at loop entry is variant.
11283     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11284       return LoopVariant;
11285     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11286            " dominate the contained loop's header?");
11287 
11288     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11289     if (AR->getLoop()->contains(L))
11290       return LoopInvariant;
11291 
11292     // This recurrence is variant w.r.t. L if any of its operands
11293     // are variant.
11294     for (auto *Op : AR->operands())
11295       if (!isLoopInvariant(Op, L))
11296         return LoopVariant;
11297 
11298     // Otherwise it's loop-invariant.
11299     return LoopInvariant;
11300   }
11301   case scAddExpr:
11302   case scMulExpr:
11303   case scUMaxExpr:
11304   case scSMaxExpr: {
11305     bool HasVarying = false;
11306     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11307       LoopDisposition D = getLoopDisposition(Op, L);
11308       if (D == LoopVariant)
11309         return LoopVariant;
11310       if (D == LoopComputable)
11311         HasVarying = true;
11312     }
11313     return HasVarying ? LoopComputable : LoopInvariant;
11314   }
11315   case scUDivExpr: {
11316     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11317     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11318     if (LD == LoopVariant)
11319       return LoopVariant;
11320     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11321     if (RD == LoopVariant)
11322       return LoopVariant;
11323     return (LD == LoopInvariant && RD == LoopInvariant) ?
11324            LoopInvariant : LoopComputable;
11325   }
11326   case scUnknown:
11327     // All non-instruction values are loop invariant.  All instructions are loop
11328     // invariant if they are not contained in the specified loop.
11329     // Instructions are never considered invariant in the function body
11330     // (null loop) because they are defined within the "loop".
11331     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11332       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11333     return LoopInvariant;
11334   case scCouldNotCompute:
11335     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11336   }
11337   llvm_unreachable("Unknown SCEV kind!");
11338 }
11339 
11340 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11341   return getLoopDisposition(S, L) == LoopInvariant;
11342 }
11343 
11344 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11345   return getLoopDisposition(S, L) == LoopComputable;
11346 }
11347 
11348 ScalarEvolution::BlockDisposition
11349 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11350   auto &Values = BlockDispositions[S];
11351   for (auto &V : Values) {
11352     if (V.getPointer() == BB)
11353       return V.getInt();
11354   }
11355   Values.emplace_back(BB, DoesNotDominateBlock);
11356   BlockDisposition D = computeBlockDisposition(S, BB);
11357   auto &Values2 = BlockDispositions[S];
11358   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11359     if (V.getPointer() == BB) {
11360       V.setInt(D);
11361       break;
11362     }
11363   }
11364   return D;
11365 }
11366 
11367 ScalarEvolution::BlockDisposition
11368 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11369   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11370   case scConstant:
11371     return ProperlyDominatesBlock;
11372   case scTruncate:
11373   case scZeroExtend:
11374   case scSignExtend:
11375     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11376   case scAddRecExpr: {
11377     // This uses a "dominates" query instead of "properly dominates" query
11378     // to test for proper dominance too, because the instruction which
11379     // produces the addrec's value is a PHI, and a PHI effectively properly
11380     // dominates its entire containing block.
11381     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11382     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11383       return DoesNotDominateBlock;
11384 
11385     // Fall through into SCEVNAryExpr handling.
11386     LLVM_FALLTHROUGH;
11387   }
11388   case scAddExpr:
11389   case scMulExpr:
11390   case scUMaxExpr:
11391   case scSMaxExpr: {
11392     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11393     bool Proper = true;
11394     for (const SCEV *NAryOp : NAry->operands()) {
11395       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11396       if (D == DoesNotDominateBlock)
11397         return DoesNotDominateBlock;
11398       if (D == DominatesBlock)
11399         Proper = false;
11400     }
11401     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11402   }
11403   case scUDivExpr: {
11404     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11405     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11406     BlockDisposition LD = getBlockDisposition(LHS, BB);
11407     if (LD == DoesNotDominateBlock)
11408       return DoesNotDominateBlock;
11409     BlockDisposition RD = getBlockDisposition(RHS, BB);
11410     if (RD == DoesNotDominateBlock)
11411       return DoesNotDominateBlock;
11412     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11413       ProperlyDominatesBlock : DominatesBlock;
11414   }
11415   case scUnknown:
11416     if (Instruction *I =
11417           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11418       if (I->getParent() == BB)
11419         return DominatesBlock;
11420       if (DT.properlyDominates(I->getParent(), BB))
11421         return ProperlyDominatesBlock;
11422       return DoesNotDominateBlock;
11423     }
11424     return ProperlyDominatesBlock;
11425   case scCouldNotCompute:
11426     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11427   }
11428   llvm_unreachable("Unknown SCEV kind!");
11429 }
11430 
11431 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11432   return getBlockDisposition(S, BB) >= DominatesBlock;
11433 }
11434 
11435 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11436   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11437 }
11438 
11439 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11440   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11441 }
11442 
11443 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11444   auto IsS = [&](const SCEV *X) { return S == X; };
11445   auto ContainsS = [&](const SCEV *X) {
11446     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11447   };
11448   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11449 }
11450 
11451 void
11452 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11453   ValuesAtScopes.erase(S);
11454   LoopDispositions.erase(S);
11455   BlockDispositions.erase(S);
11456   UnsignedRanges.erase(S);
11457   SignedRanges.erase(S);
11458   ExprValueMap.erase(S);
11459   HasRecMap.erase(S);
11460   MinTrailingZerosCache.erase(S);
11461 
11462   for (auto I = PredicatedSCEVRewrites.begin();
11463        I != PredicatedSCEVRewrites.end();) {
11464     std::pair<const SCEV *, const Loop *> Entry = I->first;
11465     if (Entry.first == S)
11466       PredicatedSCEVRewrites.erase(I++);
11467     else
11468       ++I;
11469   }
11470 
11471   auto RemoveSCEVFromBackedgeMap =
11472       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11473         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11474           BackedgeTakenInfo &BEInfo = I->second;
11475           if (BEInfo.hasOperand(S, this)) {
11476             BEInfo.clear();
11477             Map.erase(I++);
11478           } else
11479             ++I;
11480         }
11481       };
11482 
11483   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11484   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11485 }
11486 
11487 void
11488 ScalarEvolution::getUsedLoops(const SCEV *S,
11489                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11490   struct FindUsedLoops {
11491     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11492         : LoopsUsed(LoopsUsed) {}
11493     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11494     bool follow(const SCEV *S) {
11495       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11496         LoopsUsed.insert(AR->getLoop());
11497       return true;
11498     }
11499 
11500     bool isDone() const { return false; }
11501   };
11502 
11503   FindUsedLoops F(LoopsUsed);
11504   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11505 }
11506 
11507 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11508   SmallPtrSet<const Loop *, 8> LoopsUsed;
11509   getUsedLoops(S, LoopsUsed);
11510   for (auto *L : LoopsUsed)
11511     LoopUsers[L].push_back(S);
11512 }
11513 
11514 void ScalarEvolution::verify() const {
11515   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11516   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11517 
11518   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11519 
11520   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11521   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11522     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11523 
11524     const SCEV *visitConstant(const SCEVConstant *Constant) {
11525       return SE.getConstant(Constant->getAPInt());
11526     }
11527 
11528     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11529       return SE.getUnknown(Expr->getValue());
11530     }
11531 
11532     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11533       return SE.getCouldNotCompute();
11534     }
11535   };
11536 
11537   SCEVMapper SCM(SE2);
11538 
11539   while (!LoopStack.empty()) {
11540     auto *L = LoopStack.pop_back_val();
11541     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11542 
11543     auto *CurBECount = SCM.visit(
11544         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11545     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11546 
11547     if (CurBECount == SE2.getCouldNotCompute() ||
11548         NewBECount == SE2.getCouldNotCompute()) {
11549       // NB! This situation is legal, but is very suspicious -- whatever pass
11550       // change the loop to make a trip count go from could not compute to
11551       // computable or vice-versa *should have* invalidated SCEV.  However, we
11552       // choose not to assert here (for now) since we don't want false
11553       // positives.
11554       continue;
11555     }
11556 
11557     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11558       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11559       // not propagate undef aggressively).  This means we can (and do) fail
11560       // verification in cases where a transform makes the trip count of a loop
11561       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11562       // both cases the loop iterates "undef" times, but SCEV thinks we
11563       // increased the trip count of the loop by 1 incorrectly.
11564       continue;
11565     }
11566 
11567     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11568         SE.getTypeSizeInBits(NewBECount->getType()))
11569       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11570     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11571              SE.getTypeSizeInBits(NewBECount->getType()))
11572       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11573 
11574     auto *ConstantDelta =
11575         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11576 
11577     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11578       dbgs() << "Trip Count Changed!\n";
11579       dbgs() << "Old: " << *CurBECount << "\n";
11580       dbgs() << "New: " << *NewBECount << "\n";
11581       dbgs() << "Delta: " << *ConstantDelta << "\n";
11582       std::abort();
11583     }
11584   }
11585 }
11586 
11587 bool ScalarEvolution::invalidate(
11588     Function &F, const PreservedAnalyses &PA,
11589     FunctionAnalysisManager::Invalidator &Inv) {
11590   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11591   // of its dependencies is invalidated.
11592   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11593   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11594          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11595          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11596          Inv.invalidate<LoopAnalysis>(F, PA);
11597 }
11598 
11599 AnalysisKey ScalarEvolutionAnalysis::Key;
11600 
11601 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11602                                              FunctionAnalysisManager &AM) {
11603   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11604                          AM.getResult<AssumptionAnalysis>(F),
11605                          AM.getResult<DominatorTreeAnalysis>(F),
11606                          AM.getResult<LoopAnalysis>(F));
11607 }
11608 
11609 PreservedAnalyses
11610 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11611   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11612   return PreservedAnalyses::all();
11613 }
11614 
11615 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11616                       "Scalar Evolution Analysis", false, true)
11617 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11618 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11619 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11620 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11621 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11622                     "Scalar Evolution Analysis", false, true)
11623 
11624 char ScalarEvolutionWrapperPass::ID = 0;
11625 
11626 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11627   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11628 }
11629 
11630 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11631   SE.reset(new ScalarEvolution(
11632       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11633       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11634       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11635       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11636   return false;
11637 }
11638 
11639 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11640 
11641 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11642   SE->print(OS);
11643 }
11644 
11645 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11646   if (!VerifySCEV)
11647     return;
11648 
11649   SE->verify();
11650 }
11651 
11652 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11653   AU.setPreservesAll();
11654   AU.addRequiredTransitive<AssumptionCacheTracker>();
11655   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11656   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11657   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11658 }
11659 
11660 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11661                                                         const SCEV *RHS) {
11662   FoldingSetNodeID ID;
11663   assert(LHS->getType() == RHS->getType() &&
11664          "Type mismatch between LHS and RHS");
11665   // Unique this node based on the arguments
11666   ID.AddInteger(SCEVPredicate::P_Equal);
11667   ID.AddPointer(LHS);
11668   ID.AddPointer(RHS);
11669   void *IP = nullptr;
11670   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11671     return S;
11672   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11673       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11674   UniquePreds.InsertNode(Eq, IP);
11675   return Eq;
11676 }
11677 
11678 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11679     const SCEVAddRecExpr *AR,
11680     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11681   FoldingSetNodeID ID;
11682   // Unique this node based on the arguments
11683   ID.AddInteger(SCEVPredicate::P_Wrap);
11684   ID.AddPointer(AR);
11685   ID.AddInteger(AddedFlags);
11686   void *IP = nullptr;
11687   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11688     return S;
11689   auto *OF = new (SCEVAllocator)
11690       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11691   UniquePreds.InsertNode(OF, IP);
11692   return OF;
11693 }
11694 
11695 namespace {
11696 
11697 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11698 public:
11699 
11700   /// Rewrites \p S in the context of a loop L and the SCEV predication
11701   /// infrastructure.
11702   ///
11703   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11704   /// equivalences present in \p Pred.
11705   ///
11706   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11707   /// \p NewPreds such that the result will be an AddRecExpr.
11708   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11709                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11710                              SCEVUnionPredicate *Pred) {
11711     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11712     return Rewriter.visit(S);
11713   }
11714 
11715   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11716     if (Pred) {
11717       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11718       for (auto *Pred : ExprPreds)
11719         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11720           if (IPred->getLHS() == Expr)
11721             return IPred->getRHS();
11722     }
11723     return convertToAddRecWithPreds(Expr);
11724   }
11725 
11726   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11727     const SCEV *Operand = visit(Expr->getOperand());
11728     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11729     if (AR && AR->getLoop() == L && AR->isAffine()) {
11730       // This couldn't be folded because the operand didn't have the nuw
11731       // flag. Add the nusw flag as an assumption that we could make.
11732       const SCEV *Step = AR->getStepRecurrence(SE);
11733       Type *Ty = Expr->getType();
11734       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11735         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11736                                 SE.getSignExtendExpr(Step, Ty), L,
11737                                 AR->getNoWrapFlags());
11738     }
11739     return SE.getZeroExtendExpr(Operand, Expr->getType());
11740   }
11741 
11742   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11743     const SCEV *Operand = visit(Expr->getOperand());
11744     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11745     if (AR && AR->getLoop() == L && AR->isAffine()) {
11746       // This couldn't be folded because the operand didn't have the nsw
11747       // flag. Add the nssw flag as an assumption that we could make.
11748       const SCEV *Step = AR->getStepRecurrence(SE);
11749       Type *Ty = Expr->getType();
11750       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11751         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11752                                 SE.getSignExtendExpr(Step, Ty), L,
11753                                 AR->getNoWrapFlags());
11754     }
11755     return SE.getSignExtendExpr(Operand, Expr->getType());
11756   }
11757 
11758 private:
11759   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11760                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11761                         SCEVUnionPredicate *Pred)
11762       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11763 
11764   bool addOverflowAssumption(const SCEVPredicate *P) {
11765     if (!NewPreds) {
11766       // Check if we've already made this assumption.
11767       return Pred && Pred->implies(P);
11768     }
11769     NewPreds->insert(P);
11770     return true;
11771   }
11772 
11773   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11774                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11775     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11776     return addOverflowAssumption(A);
11777   }
11778 
11779   // If \p Expr represents a PHINode, we try to see if it can be represented
11780   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11781   // to add this predicate as a runtime overflow check, we return the AddRec.
11782   // If \p Expr does not meet these conditions (is not a PHI node, or we
11783   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11784   // return \p Expr.
11785   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11786     if (!isa<PHINode>(Expr->getValue()))
11787       return Expr;
11788     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11789     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11790     if (!PredicatedRewrite)
11791       return Expr;
11792     for (auto *P : PredicatedRewrite->second){
11793       // Wrap predicates from outer loops are not supported.
11794       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
11795         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
11796         if (L != AR->getLoop())
11797           return Expr;
11798       }
11799       if (!addOverflowAssumption(P))
11800         return Expr;
11801     }
11802     return PredicatedRewrite->first;
11803   }
11804 
11805   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11806   SCEVUnionPredicate *Pred;
11807   const Loop *L;
11808 };
11809 
11810 } // end anonymous namespace
11811 
11812 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11813                                                    SCEVUnionPredicate &Preds) {
11814   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11815 }
11816 
11817 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11818     const SCEV *S, const Loop *L,
11819     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11820   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11821   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11822   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11823 
11824   if (!AddRec)
11825     return nullptr;
11826 
11827   // Since the transformation was successful, we can now transfer the SCEV
11828   // predicates.
11829   for (auto *P : TransformPreds)
11830     Preds.insert(P);
11831 
11832   return AddRec;
11833 }
11834 
11835 /// SCEV predicates
11836 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11837                              SCEVPredicateKind Kind)
11838     : FastID(ID), Kind(Kind) {}
11839 
11840 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11841                                        const SCEV *LHS, const SCEV *RHS)
11842     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11843   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11844   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11845 }
11846 
11847 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11848   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11849 
11850   if (!Op)
11851     return false;
11852 
11853   return Op->LHS == LHS && Op->RHS == RHS;
11854 }
11855 
11856 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11857 
11858 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11859 
11860 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11861   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11862 }
11863 
11864 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11865                                      const SCEVAddRecExpr *AR,
11866                                      IncrementWrapFlags Flags)
11867     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11868 
11869 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11870 
11871 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11872   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11873 
11874   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11875 }
11876 
11877 bool SCEVWrapPredicate::isAlwaysTrue() const {
11878   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11879   IncrementWrapFlags IFlags = Flags;
11880 
11881   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11882     IFlags = clearFlags(IFlags, IncrementNSSW);
11883 
11884   return IFlags == IncrementAnyWrap;
11885 }
11886 
11887 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11888   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11889   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11890     OS << "<nusw>";
11891   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11892     OS << "<nssw>";
11893   OS << "\n";
11894 }
11895 
11896 SCEVWrapPredicate::IncrementWrapFlags
11897 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11898                                    ScalarEvolution &SE) {
11899   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11900   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11901 
11902   // We can safely transfer the NSW flag as NSSW.
11903   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11904     ImpliedFlags = IncrementNSSW;
11905 
11906   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11907     // If the increment is positive, the SCEV NUW flag will also imply the
11908     // WrapPredicate NUSW flag.
11909     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11910       if (Step->getValue()->getValue().isNonNegative())
11911         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11912   }
11913 
11914   return ImpliedFlags;
11915 }
11916 
11917 /// Union predicates don't get cached so create a dummy set ID for it.
11918 SCEVUnionPredicate::SCEVUnionPredicate()
11919     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11920 
11921 bool SCEVUnionPredicate::isAlwaysTrue() const {
11922   return all_of(Preds,
11923                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11924 }
11925 
11926 ArrayRef<const SCEVPredicate *>
11927 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11928   auto I = SCEVToPreds.find(Expr);
11929   if (I == SCEVToPreds.end())
11930     return ArrayRef<const SCEVPredicate *>();
11931   return I->second;
11932 }
11933 
11934 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11935   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11936     return all_of(Set->Preds,
11937                   [this](const SCEVPredicate *I) { return this->implies(I); });
11938 
11939   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11940   if (ScevPredsIt == SCEVToPreds.end())
11941     return false;
11942   auto &SCEVPreds = ScevPredsIt->second;
11943 
11944   return any_of(SCEVPreds,
11945                 [N](const SCEVPredicate *I) { return I->implies(N); });
11946 }
11947 
11948 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11949 
11950 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11951   for (auto Pred : Preds)
11952     Pred->print(OS, Depth);
11953 }
11954 
11955 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11956   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11957     for (auto Pred : Set->Preds)
11958       add(Pred);
11959     return;
11960   }
11961 
11962   if (implies(N))
11963     return;
11964 
11965   const SCEV *Key = N->getExpr();
11966   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11967                 " associated expression!");
11968 
11969   SCEVToPreds[Key].push_back(N);
11970   Preds.push_back(N);
11971 }
11972 
11973 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11974                                                      Loop &L)
11975     : SE(SE), L(L) {}
11976 
11977 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11978   const SCEV *Expr = SE.getSCEV(V);
11979   RewriteEntry &Entry = RewriteMap[Expr];
11980 
11981   // If we already have an entry and the version matches, return it.
11982   if (Entry.second && Generation == Entry.first)
11983     return Entry.second;
11984 
11985   // We found an entry but it's stale. Rewrite the stale entry
11986   // according to the current predicate.
11987   if (Entry.second)
11988     Expr = Entry.second;
11989 
11990   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11991   Entry = {Generation, NewSCEV};
11992 
11993   return NewSCEV;
11994 }
11995 
11996 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11997   if (!BackedgeCount) {
11998     SCEVUnionPredicate BackedgePred;
11999     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12000     addPredicate(BackedgePred);
12001   }
12002   return BackedgeCount;
12003 }
12004 
12005 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12006   if (Preds.implies(&Pred))
12007     return;
12008   Preds.add(&Pred);
12009   updateGeneration();
12010 }
12011 
12012 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12013   return Preds;
12014 }
12015 
12016 void PredicatedScalarEvolution::updateGeneration() {
12017   // If the generation number wrapped recompute everything.
12018   if (++Generation == 0) {
12019     for (auto &II : RewriteMap) {
12020       const SCEV *Rewritten = II.second.second;
12021       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12022     }
12023   }
12024 }
12025 
12026 void PredicatedScalarEvolution::setNoOverflow(
12027     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12028   const SCEV *Expr = getSCEV(V);
12029   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12030 
12031   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12032 
12033   // Clear the statically implied flags.
12034   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12035   addPredicate(*SE.getWrapPredicate(AR, Flags));
12036 
12037   auto II = FlagsMap.insert({V, Flags});
12038   if (!II.second)
12039     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12040 }
12041 
12042 bool PredicatedScalarEvolution::hasNoOverflow(
12043     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12044   const SCEV *Expr = getSCEV(V);
12045   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12046 
12047   Flags = SCEVWrapPredicate::clearFlags(
12048       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12049 
12050   auto II = FlagsMap.find(V);
12051 
12052   if (II != FlagsMap.end())
12053     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12054 
12055   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12056 }
12057 
12058 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12059   const SCEV *Expr = this->getSCEV(V);
12060   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12061   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12062 
12063   if (!New)
12064     return nullptr;
12065 
12066   for (auto *P : NewPreds)
12067     Preds.add(P);
12068 
12069   updateGeneration();
12070   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12071   return New;
12072 }
12073 
12074 PredicatedScalarEvolution::PredicatedScalarEvolution(
12075     const PredicatedScalarEvolution &Init)
12076     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12077       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12078   for (const auto &I : Init.FlagsMap)
12079     FlagsMap.insert(I);
12080 }
12081 
12082 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12083   // For each block.
12084   for (auto *BB : L.getBlocks())
12085     for (auto &I : *BB) {
12086       if (!SE.isSCEVable(I.getType()))
12087         continue;
12088 
12089       auto *Expr = SE.getSCEV(&I);
12090       auto II = RewriteMap.find(Expr);
12091 
12092       if (II == RewriteMap.end())
12093         continue;
12094 
12095       // Don't print things that are not interesting.
12096       if (II->second.second == Expr)
12097         continue;
12098 
12099       OS.indent(Depth) << "[PSE]" << I << ":\n";
12100       OS.indent(Depth + 2) << *Expr << "\n";
12101       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12102     }
12103 }
12104