1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
12 //
13 // There are several aspects to this library.  First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
18 //
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
24 //
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression.  These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
29 //
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
33 //
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
36 //
37 //===----------------------------------------------------------------------===//
38 //
39 // There are several good references for the techniques used in this analysis.
40 //
41 //  Chains of recurrences -- a method to expedite the evaluation
42 //  of closed-form functions
43 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44 //
45 //  On computational properties of chains of recurrences
46 //  Eugene V. Zima
47 //
48 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 //  Robert A. van Engelen
50 //
51 //  Efficient Symbolic Analysis for Optimizing Compilers
52 //  Robert A. van Engelen
53 //
54 //  Using the chains of recurrences algebra for data dependence testing and
55 //  induction variable substitution
56 //  MS Thesis, Johnie Birch
57 //
58 //===----------------------------------------------------------------------===//
59 
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.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<bool> VerifyIR(
166     "scev-verify-ir", cl::Hidden,
167     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
168     cl::init(false));
169 
170 static cl::opt<unsigned> MulOpsInlineThreshold(
171     "scev-mulops-inline-threshold", cl::Hidden,
172     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
173     cl::init(32));
174 
175 static cl::opt<unsigned> AddOpsInlineThreshold(
176     "scev-addops-inline-threshold", cl::Hidden,
177     cl::desc("Threshold for inlining addition operands into a SCEV"),
178     cl::init(500));
179 
180 static cl::opt<unsigned> MaxSCEVCompareDepth(
181     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
182     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
183     cl::init(32));
184 
185 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
186     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
188     cl::init(2));
189 
190 static cl::opt<unsigned> MaxValueCompareDepth(
191     "scalar-evolution-max-value-compare-depth", cl::Hidden,
192     cl::desc("Maximum depth of recursive value complexity comparisons"),
193     cl::init(2));
194 
195 static cl::opt<unsigned>
196     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
197                   cl::desc("Maximum depth of recursive arithmetics"),
198                   cl::init(32));
199 
200 static cl::opt<unsigned> MaxConstantEvolvingDepth(
201     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
202     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
203 
204 static cl::opt<unsigned>
205     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
206                 cl::desc("Maximum depth of recursive SExt/ZExt"),
207                 cl::init(8));
208 
209 static cl::opt<unsigned>
210     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
211                   cl::desc("Max coefficients in AddRec during evolving"),
212                   cl::init(8));
213 
214 static cl::opt<unsigned>
215     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
216                   cl::desc("Size of the expression which is considered huge"),
217                   cl::init(4096));
218 
219 //===----------------------------------------------------------------------===//
220 //                           SCEV class definitions
221 //===----------------------------------------------------------------------===//
222 
223 //===----------------------------------------------------------------------===//
224 // Implementation of the SCEV class.
225 //
226 
227 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
228 LLVM_DUMP_METHOD void SCEV::dump() const {
229   print(dbgs());
230   dbgs() << '\n';
231 }
232 #endif
233 
234 void SCEV::print(raw_ostream &OS) const {
235   switch (static_cast<SCEVTypes>(getSCEVType())) {
236   case scConstant:
237     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
238     return;
239   case scTruncate: {
240     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
241     const SCEV *Op = Trunc->getOperand();
242     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
243        << *Trunc->getType() << ")";
244     return;
245   }
246   case scZeroExtend: {
247     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
248     const SCEV *Op = ZExt->getOperand();
249     OS << "(zext " << *Op->getType() << " " << *Op << " to "
250        << *ZExt->getType() << ")";
251     return;
252   }
253   case scSignExtend: {
254     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
255     const SCEV *Op = SExt->getOperand();
256     OS << "(sext " << *Op->getType() << " " << *Op << " to "
257        << *SExt->getType() << ")";
258     return;
259   }
260   case scAddRecExpr: {
261     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
262     OS << "{" << *AR->getOperand(0);
263     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
264       OS << ",+," << *AR->getOperand(i);
265     OS << "}<";
266     if (AR->hasNoUnsignedWrap())
267       OS << "nuw><";
268     if (AR->hasNoSignedWrap())
269       OS << "nsw><";
270     if (AR->hasNoSelfWrap() &&
271         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
272       OS << "nw><";
273     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
274     OS << ">";
275     return;
276   }
277   case scAddExpr:
278   case scMulExpr:
279   case scUMaxExpr:
280   case scSMaxExpr: {
281     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
282     const char *OpStr = nullptr;
283     switch (NAry->getSCEVType()) {
284     case scAddExpr: OpStr = " + "; break;
285     case scMulExpr: OpStr = " * "; break;
286     case scUMaxExpr: OpStr = " umax "; break;
287     case scSMaxExpr: OpStr = " smax "; break;
288     }
289     OS << "(";
290     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
291          I != E; ++I) {
292       OS << **I;
293       if (std::next(I) != E)
294         OS << OpStr;
295     }
296     OS << ")";
297     switch (NAry->getSCEVType()) {
298     case scAddExpr:
299     case scMulExpr:
300       if (NAry->hasNoUnsignedWrap())
301         OS << "<nuw>";
302       if (NAry->hasNoSignedWrap())
303         OS << "<nsw>";
304     }
305     return;
306   }
307   case scUDivExpr: {
308     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
309     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
310     return;
311   }
312   case scUnknown: {
313     const SCEVUnknown *U = cast<SCEVUnknown>(this);
314     Type *AllocTy;
315     if (U->isSizeOf(AllocTy)) {
316       OS << "sizeof(" << *AllocTy << ")";
317       return;
318     }
319     if (U->isAlignOf(AllocTy)) {
320       OS << "alignof(" << *AllocTy << ")";
321       return;
322     }
323 
324     Type *CTy;
325     Constant *FieldNo;
326     if (U->isOffsetOf(CTy, FieldNo)) {
327       OS << "offsetof(" << *CTy << ", ";
328       FieldNo->printAsOperand(OS, false);
329       OS << ")";
330       return;
331     }
332 
333     // Otherwise just print it normally.
334     U->getValue()->printAsOperand(OS, false);
335     return;
336   }
337   case scCouldNotCompute:
338     OS << "***COULDNOTCOMPUTE***";
339     return;
340   }
341   llvm_unreachable("Unknown SCEV kind!");
342 }
343 
344 Type *SCEV::getType() const {
345   switch (static_cast<SCEVTypes>(getSCEVType())) {
346   case scConstant:
347     return cast<SCEVConstant>(this)->getType();
348   case scTruncate:
349   case scZeroExtend:
350   case scSignExtend:
351     return cast<SCEVCastExpr>(this)->getType();
352   case scAddRecExpr:
353   case scMulExpr:
354   case scUMaxExpr:
355   case scSMaxExpr:
356     return cast<SCEVNAryExpr>(this)->getType();
357   case scAddExpr:
358     return cast<SCEVAddExpr>(this)->getType();
359   case scUDivExpr:
360     return cast<SCEVUDivExpr>(this)->getType();
361   case scUnknown:
362     return cast<SCEVUnknown>(this)->getType();
363   case scCouldNotCompute:
364     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
365   }
366   llvm_unreachable("Unknown SCEV kind!");
367 }
368 
369 bool SCEV::isZero() const {
370   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
371     return SC->getValue()->isZero();
372   return false;
373 }
374 
375 bool SCEV::isOne() const {
376   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
377     return SC->getValue()->isOne();
378   return false;
379 }
380 
381 bool SCEV::isAllOnesValue() const {
382   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
383     return SC->getValue()->isMinusOne();
384   return false;
385 }
386 
387 bool SCEV::isNonConstantNegative() const {
388   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
389   if (!Mul) return false;
390 
391   // If there is a constant factor, it will be first.
392   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
393   if (!SC) return false;
394 
395   // Return true if the value is negative, this matches things like (-42 * V).
396   return SC->getAPInt().isNegative();
397 }
398 
399 SCEVCouldNotCompute::SCEVCouldNotCompute() :
400   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
401 
402 bool SCEVCouldNotCompute::classof(const SCEV *S) {
403   return S->getSCEVType() == scCouldNotCompute;
404 }
405 
406 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
407   FoldingSetNodeID ID;
408   ID.AddInteger(scConstant);
409   ID.AddPointer(V);
410   void *IP = nullptr;
411   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
412   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
413   UniqueSCEVs.InsertNode(S, IP);
414   return S;
415 }
416 
417 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
418   return getConstant(ConstantInt::get(getContext(), Val));
419 }
420 
421 const SCEV *
422 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
423   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
424   return getConstant(ConstantInt::get(ITy, V, isSigned));
425 }
426 
427 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
428                            unsigned SCEVTy, const SCEV *op, Type *ty)
429   : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
430 
431 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
432                                    const SCEV *op, Type *ty)
433   : SCEVCastExpr(ID, scTruncate, op, ty) {
434   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
435          "Cannot truncate non-integer value!");
436 }
437 
438 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
439                                        const SCEV *op, Type *ty)
440   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
441   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
442          "Cannot zero extend non-integer value!");
443 }
444 
445 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
446                                        const SCEV *op, Type *ty)
447   : SCEVCastExpr(ID, scSignExtend, op, ty) {
448   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
449          "Cannot sign extend non-integer value!");
450 }
451 
452 void SCEVUnknown::deleted() {
453   // Clear this SCEVUnknown from various maps.
454   SE->forgetMemoizedResults(this);
455 
456   // Remove this SCEVUnknown from the uniquing map.
457   SE->UniqueSCEVs.RemoveNode(this);
458 
459   // Release the value.
460   setValPtr(nullptr);
461 }
462 
463 void SCEVUnknown::allUsesReplacedWith(Value *New) {
464   // Remove this SCEVUnknown from the uniquing map.
465   SE->UniqueSCEVs.RemoveNode(this);
466 
467   // Update this SCEVUnknown to point to the new value. This is needed
468   // because there may still be outstanding SCEVs which still point to
469   // this SCEVUnknown.
470   setValPtr(New);
471 }
472 
473 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
474   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
475     if (VCE->getOpcode() == Instruction::PtrToInt)
476       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
477         if (CE->getOpcode() == Instruction::GetElementPtr &&
478             CE->getOperand(0)->isNullValue() &&
479             CE->getNumOperands() == 2)
480           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
481             if (CI->isOne()) {
482               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
483                                  ->getElementType();
484               return true;
485             }
486 
487   return false;
488 }
489 
490 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
491   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
492     if (VCE->getOpcode() == Instruction::PtrToInt)
493       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
494         if (CE->getOpcode() == Instruction::GetElementPtr &&
495             CE->getOperand(0)->isNullValue()) {
496           Type *Ty =
497             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
498           if (StructType *STy = dyn_cast<StructType>(Ty))
499             if (!STy->isPacked() &&
500                 CE->getNumOperands() == 3 &&
501                 CE->getOperand(1)->isNullValue()) {
502               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
503                 if (CI->isOne() &&
504                     STy->getNumElements() == 2 &&
505                     STy->getElementType(0)->isIntegerTy(1)) {
506                   AllocTy = STy->getElementType(1);
507                   return true;
508                 }
509             }
510         }
511 
512   return false;
513 }
514 
515 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
516   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
517     if (VCE->getOpcode() == Instruction::PtrToInt)
518       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
519         if (CE->getOpcode() == Instruction::GetElementPtr &&
520             CE->getNumOperands() == 3 &&
521             CE->getOperand(0)->isNullValue() &&
522             CE->getOperand(1)->isNullValue()) {
523           Type *Ty =
524             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
525           // Ignore vector types here so that ScalarEvolutionExpander doesn't
526           // emit getelementptrs that index into vectors.
527           if (Ty->isStructTy() || Ty->isArrayTy()) {
528             CTy = Ty;
529             FieldNo = CE->getOperand(2);
530             return true;
531           }
532         }
533 
534   return false;
535 }
536 
537 //===----------------------------------------------------------------------===//
538 //                               SCEV Utilities
539 //===----------------------------------------------------------------------===//
540 
541 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
542 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
543 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
544 /// have been previously deemed to be "equally complex" by this routine.  It is
545 /// intended to avoid exponential time complexity in cases like:
546 ///
547 ///   %a = f(%x, %y)
548 ///   %b = f(%a, %a)
549 ///   %c = f(%b, %b)
550 ///
551 ///   %d = f(%x, %y)
552 ///   %e = f(%d, %d)
553 ///   %f = f(%e, %e)
554 ///
555 ///   CompareValueComplexity(%f, %c)
556 ///
557 /// Since we do not continue running this routine on expression trees once we
558 /// have seen unequal values, there is no need to track them in the cache.
559 static int
560 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
561                        const LoopInfo *const LI, Value *LV, Value *RV,
562                        unsigned Depth) {
563   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
564     return 0;
565 
566   // Order pointer values after integer values. This helps SCEVExpander form
567   // GEPs.
568   bool LIsPointer = LV->getType()->isPointerTy(),
569        RIsPointer = RV->getType()->isPointerTy();
570   if (LIsPointer != RIsPointer)
571     return (int)LIsPointer - (int)RIsPointer;
572 
573   // Compare getValueID values.
574   unsigned LID = LV->getValueID(), RID = RV->getValueID();
575   if (LID != RID)
576     return (int)LID - (int)RID;
577 
578   // Sort arguments by their position.
579   if (const auto *LA = dyn_cast<Argument>(LV)) {
580     const auto *RA = cast<Argument>(RV);
581     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
582     return (int)LArgNo - (int)RArgNo;
583   }
584 
585   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
586     const auto *RGV = cast<GlobalValue>(RV);
587 
588     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
589       auto LT = GV->getLinkage();
590       return !(GlobalValue::isPrivateLinkage(LT) ||
591                GlobalValue::isInternalLinkage(LT));
592     };
593 
594     // Use the names to distinguish the two values, but only if the
595     // names are semantically important.
596     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
597       return LGV->getName().compare(RGV->getName());
598   }
599 
600   // For instructions, compare their loop depth, and their operand count.  This
601   // is pretty loose.
602   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
603     const auto *RInst = cast<Instruction>(RV);
604 
605     // Compare loop depths.
606     const BasicBlock *LParent = LInst->getParent(),
607                      *RParent = RInst->getParent();
608     if (LParent != RParent) {
609       unsigned LDepth = LI->getLoopDepth(LParent),
610                RDepth = LI->getLoopDepth(RParent);
611       if (LDepth != RDepth)
612         return (int)LDepth - (int)RDepth;
613     }
614 
615     // Compare the number of operands.
616     unsigned LNumOps = LInst->getNumOperands(),
617              RNumOps = RInst->getNumOperands();
618     if (LNumOps != RNumOps)
619       return (int)LNumOps - (int)RNumOps;
620 
621     for (unsigned Idx : seq(0u, LNumOps)) {
622       int Result =
623           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
624                                  RInst->getOperand(Idx), Depth + 1);
625       if (Result != 0)
626         return Result;
627     }
628   }
629 
630   EqCacheValue.unionSets(LV, RV);
631   return 0;
632 }
633 
634 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
635 // than RHS, respectively. A three-way result allows recursive comparisons to be
636 // more efficient.
637 static int CompareSCEVComplexity(
638     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
639     EquivalenceClasses<const Value *> &EqCacheValue,
640     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
641     DominatorTree &DT, unsigned Depth = 0) {
642   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
643   if (LHS == RHS)
644     return 0;
645 
646   // Primarily, sort the SCEVs by their getSCEVType().
647   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
648   if (LType != RType)
649     return (int)LType - (int)RType;
650 
651   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
652     return 0;
653   // Aside from the getSCEVType() ordering, the particular ordering
654   // isn't very important except that it's beneficial to be consistent,
655   // so that (a + b) and (b + a) don't end up as different expressions.
656   switch (static_cast<SCEVTypes>(LType)) {
657   case scUnknown: {
658     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
659     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
660 
661     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
662                                    RU->getValue(), Depth + 1);
663     if (X == 0)
664       EqCacheSCEV.unionSets(LHS, RHS);
665     return X;
666   }
667 
668   case scConstant: {
669     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
670     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
671 
672     // Compare constant values.
673     const APInt &LA = LC->getAPInt();
674     const APInt &RA = RC->getAPInt();
675     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
676     if (LBitWidth != RBitWidth)
677       return (int)LBitWidth - (int)RBitWidth;
678     return LA.ult(RA) ? -1 : 1;
679   }
680 
681   case scAddRecExpr: {
682     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
683     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
684 
685     // There is always a dominance between two recs that are used by one SCEV,
686     // so we can safely sort recs by loop header dominance. We require such
687     // order in getAddExpr.
688     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
689     if (LLoop != RLoop) {
690       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
691       assert(LHead != RHead && "Two loops share the same header?");
692       if (DT.dominates(LHead, RHead))
693         return 1;
694       else
695         assert(DT.dominates(RHead, LHead) &&
696                "No dominance between recurrences used by one SCEV?");
697       return -1;
698     }
699 
700     // Addrec complexity grows with operand count.
701     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
702     if (LNumOps != RNumOps)
703       return (int)LNumOps - (int)RNumOps;
704 
705     // Lexicographically compare.
706     for (unsigned i = 0; i != LNumOps; ++i) {
707       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
708                                     LA->getOperand(i), RA->getOperand(i), DT,
709                                     Depth + 1);
710       if (X != 0)
711         return X;
712     }
713     EqCacheSCEV.unionSets(LHS, RHS);
714     return 0;
715   }
716 
717   case scAddExpr:
718   case scMulExpr:
719   case scSMaxExpr:
720   case scUMaxExpr: {
721     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
722     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
723 
724     // Lexicographically compare n-ary expressions.
725     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
726     if (LNumOps != RNumOps)
727       return (int)LNumOps - (int)RNumOps;
728 
729     for (unsigned i = 0; i != LNumOps; ++i) {
730       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
731                                     LC->getOperand(i), RC->getOperand(i), DT,
732                                     Depth + 1);
733       if (X != 0)
734         return X;
735     }
736     EqCacheSCEV.unionSets(LHS, RHS);
737     return 0;
738   }
739 
740   case scUDivExpr: {
741     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
742     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
743 
744     // Lexicographically compare udiv expressions.
745     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
746                                   RC->getLHS(), DT, Depth + 1);
747     if (X != 0)
748       return X;
749     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
750                               RC->getRHS(), DT, Depth + 1);
751     if (X == 0)
752       EqCacheSCEV.unionSets(LHS, RHS);
753     return X;
754   }
755 
756   case scTruncate:
757   case scZeroExtend:
758   case scSignExtend: {
759     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
760     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
761 
762     // Compare cast expressions by operand.
763     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
764                                   LC->getOperand(), RC->getOperand(), DT,
765                                   Depth + 1);
766     if (X == 0)
767       EqCacheSCEV.unionSets(LHS, RHS);
768     return X;
769   }
770 
771   case scCouldNotCompute:
772     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
773   }
774   llvm_unreachable("Unknown SCEV kind!");
775 }
776 
777 /// Given a list of SCEV objects, order them by their complexity, and group
778 /// objects of the same complexity together by value.  When this routine is
779 /// finished, we know that any duplicates in the vector are consecutive and that
780 /// complexity is monotonically increasing.
781 ///
782 /// Note that we go take special precautions to ensure that we get deterministic
783 /// results from this routine.  In other words, we don't want the results of
784 /// this to depend on where the addresses of various SCEV objects happened to
785 /// land in memory.
786 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
787                               LoopInfo *LI, DominatorTree &DT) {
788   if (Ops.size() < 2) return;  // Noop
789 
790   EquivalenceClasses<const SCEV *> EqCacheSCEV;
791   EquivalenceClasses<const Value *> EqCacheValue;
792   if (Ops.size() == 2) {
793     // This is the common case, which also happens to be trivially simple.
794     // Special case it.
795     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
796     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
797       std::swap(LHS, RHS);
798     return;
799   }
800 
801   // Do the rough sort by complexity.
802   std::stable_sort(Ops.begin(), Ops.end(),
803                    [&](const SCEV *LHS, const SCEV *RHS) {
804                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
805                                                   LHS, RHS, DT) < 0;
806                    });
807 
808   // Now that we are sorted by complexity, group elements of the same
809   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
810   // be extremely short in practice.  Note that we take this approach because we
811   // do not want to depend on the addresses of the objects we are grouping.
812   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
813     const SCEV *S = Ops[i];
814     unsigned Complexity = S->getSCEVType();
815 
816     // If there are any objects of the same complexity and same value as this
817     // one, group them.
818     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
819       if (Ops[j] == S) { // Found a duplicate.
820         // Move it to immediately after i'th element.
821         std::swap(Ops[i+1], Ops[j]);
822         ++i;   // no need to rescan it.
823         if (i == e-2) return;  // Done!
824       }
825     }
826   }
827 }
828 
829 // Returns the size of the SCEV S.
830 static inline int sizeOfSCEV(const SCEV *S) {
831   struct FindSCEVSize {
832     int Size = 0;
833 
834     FindSCEVSize() = default;
835 
836     bool follow(const SCEV *S) {
837       ++Size;
838       // Keep looking at all operands of S.
839       return true;
840     }
841 
842     bool isDone() const {
843       return false;
844     }
845   };
846 
847   FindSCEVSize F;
848   SCEVTraversal<FindSCEVSize> ST(F);
849   ST.visitAll(S);
850   return F.Size;
851 }
852 
853 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
854 /// nodes.
855 static bool isHugeExpression(const SCEV *S) {
856   return S->getExpressionSize() >= HugeExprThreshold;
857 }
858 
859 /// Returns true of \p Ops contains a huge SCEV (see definition above).
860 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
861   return any_of(Ops, isHugeExpression);
862 }
863 
864 namespace {
865 
866 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
867 public:
868   // Computes the Quotient and Remainder of the division of Numerator by
869   // Denominator.
870   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
871                      const SCEV *Denominator, const SCEV **Quotient,
872                      const SCEV **Remainder) {
873     assert(Numerator && Denominator && "Uninitialized SCEV");
874 
875     SCEVDivision D(SE, Numerator, Denominator);
876 
877     // Check for the trivial case here to avoid having to check for it in the
878     // rest of the code.
879     if (Numerator == Denominator) {
880       *Quotient = D.One;
881       *Remainder = D.Zero;
882       return;
883     }
884 
885     if (Numerator->isZero()) {
886       *Quotient = D.Zero;
887       *Remainder = D.Zero;
888       return;
889     }
890 
891     // A simple case when N/1. The quotient is N.
892     if (Denominator->isOne()) {
893       *Quotient = Numerator;
894       *Remainder = D.Zero;
895       return;
896     }
897 
898     // Split the Denominator when it is a product.
899     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
900       const SCEV *Q, *R;
901       *Quotient = Numerator;
902       for (const SCEV *Op : T->operands()) {
903         divide(SE, *Quotient, Op, &Q, &R);
904         *Quotient = Q;
905 
906         // Bail out when the Numerator is not divisible by one of the terms of
907         // the Denominator.
908         if (!R->isZero()) {
909           *Quotient = D.Zero;
910           *Remainder = Numerator;
911           return;
912         }
913       }
914       *Remainder = D.Zero;
915       return;
916     }
917 
918     D.visit(Numerator);
919     *Quotient = D.Quotient;
920     *Remainder = D.Remainder;
921   }
922 
923   // Except in the trivial case described above, we do not know how to divide
924   // Expr by Denominator for the following functions with empty implementation.
925   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
926   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
927   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
928   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
929   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
930   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
931   void visitUnknown(const SCEVUnknown *Numerator) {}
932   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
933 
934   void visitConstant(const SCEVConstant *Numerator) {
935     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
936       APInt NumeratorVal = Numerator->getAPInt();
937       APInt DenominatorVal = D->getAPInt();
938       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
939       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
940 
941       if (NumeratorBW > DenominatorBW)
942         DenominatorVal = DenominatorVal.sext(NumeratorBW);
943       else if (NumeratorBW < DenominatorBW)
944         NumeratorVal = NumeratorVal.sext(DenominatorBW);
945 
946       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
947       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
948       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
949       Quotient = SE.getConstant(QuotientVal);
950       Remainder = SE.getConstant(RemainderVal);
951       return;
952     }
953   }
954 
955   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
956     const SCEV *StartQ, *StartR, *StepQ, *StepR;
957     if (!Numerator->isAffine())
958       return cannotDivide(Numerator);
959     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
960     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
961     // Bail out if the types do not match.
962     Type *Ty = Denominator->getType();
963     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
964         Ty != StepQ->getType() || Ty != StepR->getType())
965       return cannotDivide(Numerator);
966     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
967                                 Numerator->getNoWrapFlags());
968     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
969                                  Numerator->getNoWrapFlags());
970   }
971 
972   void visitAddExpr(const SCEVAddExpr *Numerator) {
973     SmallVector<const SCEV *, 2> Qs, Rs;
974     Type *Ty = Denominator->getType();
975 
976     for (const SCEV *Op : Numerator->operands()) {
977       const SCEV *Q, *R;
978       divide(SE, Op, Denominator, &Q, &R);
979 
980       // Bail out if types do not match.
981       if (Ty != Q->getType() || Ty != R->getType())
982         return cannotDivide(Numerator);
983 
984       Qs.push_back(Q);
985       Rs.push_back(R);
986     }
987 
988     if (Qs.size() == 1) {
989       Quotient = Qs[0];
990       Remainder = Rs[0];
991       return;
992     }
993 
994     Quotient = SE.getAddExpr(Qs);
995     Remainder = SE.getAddExpr(Rs);
996   }
997 
998   void visitMulExpr(const SCEVMulExpr *Numerator) {
999     SmallVector<const SCEV *, 2> Qs;
1000     Type *Ty = Denominator->getType();
1001 
1002     bool FoundDenominatorTerm = false;
1003     for (const SCEV *Op : Numerator->operands()) {
1004       // Bail out if types do not match.
1005       if (Ty != Op->getType())
1006         return cannotDivide(Numerator);
1007 
1008       if (FoundDenominatorTerm) {
1009         Qs.push_back(Op);
1010         continue;
1011       }
1012 
1013       // Check whether Denominator divides one of the product operands.
1014       const SCEV *Q, *R;
1015       divide(SE, Op, Denominator, &Q, &R);
1016       if (!R->isZero()) {
1017         Qs.push_back(Op);
1018         continue;
1019       }
1020 
1021       // Bail out if types do not match.
1022       if (Ty != Q->getType())
1023         return cannotDivide(Numerator);
1024 
1025       FoundDenominatorTerm = true;
1026       Qs.push_back(Q);
1027     }
1028 
1029     if (FoundDenominatorTerm) {
1030       Remainder = Zero;
1031       if (Qs.size() == 1)
1032         Quotient = Qs[0];
1033       else
1034         Quotient = SE.getMulExpr(Qs);
1035       return;
1036     }
1037 
1038     if (!isa<SCEVUnknown>(Denominator))
1039       return cannotDivide(Numerator);
1040 
1041     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1042     ValueToValueMap RewriteMap;
1043     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1044         cast<SCEVConstant>(Zero)->getValue();
1045     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1046 
1047     if (Remainder->isZero()) {
1048       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1049       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1050           cast<SCEVConstant>(One)->getValue();
1051       Quotient =
1052           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1053       return;
1054     }
1055 
1056     // Quotient is (Numerator - Remainder) divided by Denominator.
1057     const SCEV *Q, *R;
1058     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1059     // This SCEV does not seem to simplify: fail the division here.
1060     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1061       return cannotDivide(Numerator);
1062     divide(SE, Diff, Denominator, &Q, &R);
1063     if (R != Zero)
1064       return cannotDivide(Numerator);
1065     Quotient = Q;
1066   }
1067 
1068 private:
1069   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1070                const SCEV *Denominator)
1071       : SE(S), Denominator(Denominator) {
1072     Zero = SE.getZero(Denominator->getType());
1073     One = SE.getOne(Denominator->getType());
1074 
1075     // We generally do not know how to divide Expr by Denominator. We
1076     // initialize the division to a "cannot divide" state to simplify the rest
1077     // of the code.
1078     cannotDivide(Numerator);
1079   }
1080 
1081   // Convenience function for giving up on the division. We set the quotient to
1082   // be equal to zero and the remainder to be equal to the numerator.
1083   void cannotDivide(const SCEV *Numerator) {
1084     Quotient = Zero;
1085     Remainder = Numerator;
1086   }
1087 
1088   ScalarEvolution &SE;
1089   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1090 };
1091 
1092 } // end anonymous namespace
1093 
1094 //===----------------------------------------------------------------------===//
1095 //                      Simple SCEV method implementations
1096 //===----------------------------------------------------------------------===//
1097 
1098 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1099 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1100                                        ScalarEvolution &SE,
1101                                        Type *ResultTy) {
1102   // Handle the simplest case efficiently.
1103   if (K == 1)
1104     return SE.getTruncateOrZeroExtend(It, ResultTy);
1105 
1106   // We are using the following formula for BC(It, K):
1107   //
1108   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1109   //
1110   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1111   // overflow.  Hence, we must assure that the result of our computation is
1112   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1113   // safe in modular arithmetic.
1114   //
1115   // However, this code doesn't use exactly that formula; the formula it uses
1116   // is something like the following, where T is the number of factors of 2 in
1117   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1118   // exponentiation:
1119   //
1120   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1121   //
1122   // This formula is trivially equivalent to the previous formula.  However,
1123   // this formula can be implemented much more efficiently.  The trick is that
1124   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1125   // arithmetic.  To do exact division in modular arithmetic, all we have
1126   // to do is multiply by the inverse.  Therefore, this step can be done at
1127   // width W.
1128   //
1129   // The next issue is how to safely do the division by 2^T.  The way this
1130   // is done is by doing the multiplication step at a width of at least W + T
1131   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1132   // when we perform the division by 2^T (which is equivalent to a right shift
1133   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1134   // truncated out after the division by 2^T.
1135   //
1136   // In comparison to just directly using the first formula, this technique
1137   // is much more efficient; using the first formula requires W * K bits,
1138   // but this formula less than W + K bits. Also, the first formula requires
1139   // a division step, whereas this formula only requires multiplies and shifts.
1140   //
1141   // It doesn't matter whether the subtraction step is done in the calculation
1142   // width or the input iteration count's width; if the subtraction overflows,
1143   // the result must be zero anyway.  We prefer here to do it in the width of
1144   // the induction variable because it helps a lot for certain cases; CodeGen
1145   // isn't smart enough to ignore the overflow, which leads to much less
1146   // efficient code if the width of the subtraction is wider than the native
1147   // register width.
1148   //
1149   // (It's possible to not widen at all by pulling out factors of 2 before
1150   // the multiplication; for example, K=2 can be calculated as
1151   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1152   // extra arithmetic, so it's not an obvious win, and it gets
1153   // much more complicated for K > 3.)
1154 
1155   // Protection from insane SCEVs; this bound is conservative,
1156   // but it probably doesn't matter.
1157   if (K > 1000)
1158     return SE.getCouldNotCompute();
1159 
1160   unsigned W = SE.getTypeSizeInBits(ResultTy);
1161 
1162   // Calculate K! / 2^T and T; we divide out the factors of two before
1163   // multiplying for calculating K! / 2^T to avoid overflow.
1164   // Other overflow doesn't matter because we only care about the bottom
1165   // W bits of the result.
1166   APInt OddFactorial(W, 1);
1167   unsigned T = 1;
1168   for (unsigned i = 3; i <= K; ++i) {
1169     APInt Mult(W, i);
1170     unsigned TwoFactors = Mult.countTrailingZeros();
1171     T += TwoFactors;
1172     Mult.lshrInPlace(TwoFactors);
1173     OddFactorial *= Mult;
1174   }
1175 
1176   // We need at least W + T bits for the multiplication step
1177   unsigned CalculationBits = W + T;
1178 
1179   // Calculate 2^T, at width T+W.
1180   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1181 
1182   // Calculate the multiplicative inverse of K! / 2^T;
1183   // this multiplication factor will perform the exact division by
1184   // K! / 2^T.
1185   APInt Mod = APInt::getSignedMinValue(W+1);
1186   APInt MultiplyFactor = OddFactorial.zext(W+1);
1187   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1188   MultiplyFactor = MultiplyFactor.trunc(W);
1189 
1190   // Calculate the product, at width T+W
1191   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1192                                                       CalculationBits);
1193   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1194   for (unsigned i = 1; i != K; ++i) {
1195     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1196     Dividend = SE.getMulExpr(Dividend,
1197                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1198   }
1199 
1200   // Divide by 2^T
1201   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1202 
1203   // Truncate the result, and divide by K! / 2^T.
1204 
1205   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1206                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1207 }
1208 
1209 /// Return the value of this chain of recurrences at the specified iteration
1210 /// number.  We can evaluate this recurrence by multiplying each element in the
1211 /// chain by the binomial coefficient corresponding to it.  In other words, we
1212 /// can evaluate {A,+,B,+,C,+,D} as:
1213 ///
1214 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1215 ///
1216 /// where BC(It, k) stands for binomial coefficient.
1217 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1218                                                 ScalarEvolution &SE) const {
1219   const SCEV *Result = getStart();
1220   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1221     // The computation is correct in the face of overflow provided that the
1222     // multiplication is performed _after_ the evaluation of the binomial
1223     // coefficient.
1224     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1225     if (isa<SCEVCouldNotCompute>(Coeff))
1226       return Coeff;
1227 
1228     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1229   }
1230   return Result;
1231 }
1232 
1233 //===----------------------------------------------------------------------===//
1234 //                    SCEV Expression folder implementations
1235 //===----------------------------------------------------------------------===//
1236 
1237 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1238                                              Type *Ty) {
1239   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1240          "This is not a truncating conversion!");
1241   assert(isSCEVable(Ty) &&
1242          "This is not a conversion to a SCEVable type!");
1243   Ty = getEffectiveSCEVType(Ty);
1244 
1245   FoldingSetNodeID ID;
1246   ID.AddInteger(scTruncate);
1247   ID.AddPointer(Op);
1248   ID.AddPointer(Ty);
1249   void *IP = nullptr;
1250   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1251 
1252   // Fold if the operand is constant.
1253   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1254     return getConstant(
1255       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1256 
1257   // trunc(trunc(x)) --> trunc(x)
1258   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1259     return getTruncateExpr(ST->getOperand(), Ty);
1260 
1261   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1262   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1263     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1264 
1265   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1266   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1267     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1268 
1269   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1270   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1271   // if after transforming we have at most one truncate, not counting truncates
1272   // that replace other casts.
1273   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1274     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1275     SmallVector<const SCEV *, 4> Operands;
1276     unsigned numTruncs = 0;
1277     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1278          ++i) {
1279       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty);
1280       if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1281         numTruncs++;
1282       Operands.push_back(S);
1283     }
1284     if (numTruncs < 2) {
1285       if (isa<SCEVAddExpr>(Op))
1286         return getAddExpr(Operands);
1287       else if (isa<SCEVMulExpr>(Op))
1288         return getMulExpr(Operands);
1289       else
1290         llvm_unreachable("Unexpected SCEV type for Op.");
1291     }
1292     // Although we checked in the beginning that ID is not in the cache, it is
1293     // possible that during recursion and different modification ID was inserted
1294     // into the cache. So if we find 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 // Finds an integer D for an expression (C + x + y + ...) such that the top
1576 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1577 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1578 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1579 // the (C + x + y + ...) expression is \p WholeAddExpr.
1580 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1581                                             const SCEVConstant *ConstantTerm,
1582                                             const SCEVAddExpr *WholeAddExpr) {
1583   const APInt C = ConstantTerm->getAPInt();
1584   const unsigned BitWidth = C.getBitWidth();
1585   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1586   uint32_t TZ = BitWidth;
1587   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1588     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1589   if (TZ) {
1590     // Set D to be as many least significant bits of C as possible while still
1591     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1592     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1593   }
1594   return APInt(BitWidth, 0);
1595 }
1596 
1597 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1598 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1599 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1600 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1601 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1602                                             const APInt &ConstantStart,
1603                                             const SCEV *Step) {
1604   const unsigned BitWidth = ConstantStart.getBitWidth();
1605   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1606   if (TZ)
1607     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1608                          : ConstantStart;
1609   return APInt(BitWidth, 0);
1610 }
1611 
1612 const SCEV *
1613 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1614   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1615          "This is not an extending conversion!");
1616   assert(isSCEVable(Ty) &&
1617          "This is not a conversion to a SCEVable type!");
1618   Ty = getEffectiveSCEVType(Ty);
1619 
1620   // Fold if the operand is constant.
1621   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1622     return getConstant(
1623       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1624 
1625   // zext(zext(x)) --> zext(x)
1626   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1627     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1628 
1629   // Before doing any expensive analysis, check to see if we've already
1630   // computed a SCEV for this Op and Ty.
1631   FoldingSetNodeID ID;
1632   ID.AddInteger(scZeroExtend);
1633   ID.AddPointer(Op);
1634   ID.AddPointer(Ty);
1635   void *IP = nullptr;
1636   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1637   if (Depth > MaxExtDepth) {
1638     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1639                                                      Op, Ty);
1640     UniqueSCEVs.InsertNode(S, IP);
1641     addToLoopUseLists(S);
1642     return S;
1643   }
1644 
1645   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1646   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1647     // It's possible the bits taken off by the truncate were all zero bits. If
1648     // so, we should be able to simplify this further.
1649     const SCEV *X = ST->getOperand();
1650     ConstantRange CR = getUnsignedRange(X);
1651     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1652     unsigned NewBits = getTypeSizeInBits(Ty);
1653     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1654             CR.zextOrTrunc(NewBits)))
1655       return getTruncateOrZeroExtend(X, Ty);
1656   }
1657 
1658   // If the input value is a chrec scev, and we can prove that the value
1659   // did not overflow the old, smaller, value, we can zero extend all of the
1660   // operands (often constants).  This allows analysis of something like
1661   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1662   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1663     if (AR->isAffine()) {
1664       const SCEV *Start = AR->getStart();
1665       const SCEV *Step = AR->getStepRecurrence(*this);
1666       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1667       const Loop *L = AR->getLoop();
1668 
1669       if (!AR->hasNoUnsignedWrap()) {
1670         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1671         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1672       }
1673 
1674       // If we have special knowledge that this addrec won't overflow,
1675       // we don't need to do any further analysis.
1676       if (AR->hasNoUnsignedWrap())
1677         return getAddRecExpr(
1678             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1679             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1680 
1681       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1682       // Note that this serves two purposes: It filters out loops that are
1683       // simply not analyzable, and it covers the case where this code is
1684       // being called from within backedge-taken count analysis, such that
1685       // attempting to ask for the backedge-taken count would likely result
1686       // in infinite recursion. In the later case, the analysis code will
1687       // cope with a conservative value, and it will take care to purge
1688       // that value once it has finished.
1689       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1690       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1691         // Manually compute the final value for AR, checking for
1692         // overflow.
1693 
1694         // Check whether the backedge-taken count can be losslessly casted to
1695         // the addrec's type. The count is always unsigned.
1696         const SCEV *CastedMaxBECount =
1697           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1698         const SCEV *RecastedMaxBECount =
1699           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1700         if (MaxBECount == RecastedMaxBECount) {
1701           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1702           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1703           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1704                                         SCEV::FlagAnyWrap, Depth + 1);
1705           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1706                                                           SCEV::FlagAnyWrap,
1707                                                           Depth + 1),
1708                                                WideTy, Depth + 1);
1709           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1710           const SCEV *WideMaxBECount =
1711             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1712           const SCEV *OperandExtendedAdd =
1713             getAddExpr(WideStart,
1714                        getMulExpr(WideMaxBECount,
1715                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1716                                   SCEV::FlagAnyWrap, Depth + 1),
1717                        SCEV::FlagAnyWrap, Depth + 1);
1718           if (ZAdd == OperandExtendedAdd) {
1719             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1720             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1721             // Return the expression with the addrec on the outside.
1722             return getAddRecExpr(
1723                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1724                                                          Depth + 1),
1725                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1726                 AR->getNoWrapFlags());
1727           }
1728           // Similar to above, only this time treat the step value as signed.
1729           // This covers loops that count down.
1730           OperandExtendedAdd =
1731             getAddExpr(WideStart,
1732                        getMulExpr(WideMaxBECount,
1733                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1734                                   SCEV::FlagAnyWrap, Depth + 1),
1735                        SCEV::FlagAnyWrap, Depth + 1);
1736           if (ZAdd == OperandExtendedAdd) {
1737             // Cache knowledge of AR NW, which is propagated to this AddRec.
1738             // Negative step causes unsigned wrap, but it still can't self-wrap.
1739             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1740             // Return the expression with the addrec on the outside.
1741             return getAddRecExpr(
1742                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1743                                                          Depth + 1),
1744                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1745                 AR->getNoWrapFlags());
1746           }
1747         }
1748       }
1749 
1750       // Normally, in the cases we can prove no-overflow via a
1751       // backedge guarding condition, we can also compute a backedge
1752       // taken count for the loop.  The exceptions are assumptions and
1753       // guards present in the loop -- SCEV is not great at exploiting
1754       // these to compute max backedge taken counts, but can still use
1755       // these to prove lack of overflow.  Use this fact to avoid
1756       // doing extra work that may not pay off.
1757       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1758           !AC.assumptions().empty()) {
1759         // If the backedge is guarded by a comparison with the pre-inc
1760         // value the addrec is safe. Also, if the entry is guarded by
1761         // a comparison with the start value and the backedge is
1762         // guarded by a comparison with the post-inc value, the addrec
1763         // is safe.
1764         if (isKnownPositive(Step)) {
1765           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1766                                       getUnsignedRangeMax(Step));
1767           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1768               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1769             // Cache knowledge of AR NUW, which is propagated to this
1770             // AddRec.
1771             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1772             // Return the expression with the addrec on the outside.
1773             return getAddRecExpr(
1774                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1775                                                          Depth + 1),
1776                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1777                 AR->getNoWrapFlags());
1778           }
1779         } else if (isKnownNegative(Step)) {
1780           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1781                                       getSignedRangeMin(Step));
1782           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1783               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1784             // Cache knowledge of AR NW, which is propagated to this
1785             // AddRec.  Negative step causes unsigned wrap, but it
1786             // still can't self-wrap.
1787             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1788             // Return the expression with the addrec on the outside.
1789             return getAddRecExpr(
1790                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1791                                                          Depth + 1),
1792                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1793                 AR->getNoWrapFlags());
1794           }
1795         }
1796       }
1797 
1798       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1799       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1800       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1801       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1802         const APInt &C = SC->getAPInt();
1803         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1804         if (D != 0) {
1805           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1806           const SCEV *SResidual =
1807               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1808           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1809           return getAddExpr(SZExtD, SZExtR,
1810                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1811                             Depth + 1);
1812         }
1813       }
1814 
1815       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1816         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1817         return getAddRecExpr(
1818             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1819             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1820       }
1821     }
1822 
1823   // zext(A % B) --> zext(A) % zext(B)
1824   {
1825     const SCEV *LHS;
1826     const SCEV *RHS;
1827     if (matchURem(Op, LHS, RHS))
1828       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1829                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1830   }
1831 
1832   // zext(A / B) --> zext(A) / zext(B).
1833   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1834     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1835                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1836 
1837   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1838     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1839     if (SA->hasNoUnsignedWrap()) {
1840       // If the addition does not unsign overflow then we can, by definition,
1841       // commute the zero extension with the addition operation.
1842       SmallVector<const SCEV *, 4> Ops;
1843       for (const auto *Op : SA->operands())
1844         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1845       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1846     }
1847 
1848     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1849     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1850     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1851     //
1852     // Often address arithmetics contain expressions like
1853     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1854     // This transformation is useful while proving that such expressions are
1855     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1856     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1857       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1858       if (D != 0) {
1859         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1860         const SCEV *SResidual =
1861             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1862         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1863         return getAddExpr(SZExtD, SZExtR,
1864                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1865                           Depth + 1);
1866       }
1867     }
1868   }
1869 
1870   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1871     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1872     if (SM->hasNoUnsignedWrap()) {
1873       // If the multiply does not unsign overflow then we can, by definition,
1874       // commute the zero extension with the multiply operation.
1875       SmallVector<const SCEV *, 4> Ops;
1876       for (const auto *Op : SM->operands())
1877         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1878       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1879     }
1880 
1881     // zext(2^K * (trunc X to iN)) to iM ->
1882     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1883     //
1884     // Proof:
1885     //
1886     //     zext(2^K * (trunc X to iN)) to iM
1887     //   = zext((trunc X to iN) << K) to iM
1888     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1889     //     (because shl removes the top K bits)
1890     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1891     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1892     //
1893     if (SM->getNumOperands() == 2)
1894       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1895         if (MulLHS->getAPInt().isPowerOf2())
1896           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1897             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1898                                MulLHS->getAPInt().logBase2();
1899             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1900             return getMulExpr(
1901                 getZeroExtendExpr(MulLHS, Ty),
1902                 getZeroExtendExpr(
1903                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1904                 SCEV::FlagNUW, Depth + 1);
1905           }
1906   }
1907 
1908   // The cast wasn't folded; create an explicit cast node.
1909   // Recompute the insert position, as it may have been invalidated.
1910   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1911   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1912                                                    Op, Ty);
1913   UniqueSCEVs.InsertNode(S, IP);
1914   addToLoopUseLists(S);
1915   return S;
1916 }
1917 
1918 const SCEV *
1919 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1920   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1921          "This is not an extending conversion!");
1922   assert(isSCEVable(Ty) &&
1923          "This is not a conversion to a SCEVable type!");
1924   Ty = getEffectiveSCEVType(Ty);
1925 
1926   // Fold if the operand is constant.
1927   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1928     return getConstant(
1929       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1930 
1931   // sext(sext(x)) --> sext(x)
1932   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1933     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1934 
1935   // sext(zext(x)) --> zext(x)
1936   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1937     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1938 
1939   // Before doing any expensive analysis, check to see if we've already
1940   // computed a SCEV for this Op and Ty.
1941   FoldingSetNodeID ID;
1942   ID.AddInteger(scSignExtend);
1943   ID.AddPointer(Op);
1944   ID.AddPointer(Ty);
1945   void *IP = nullptr;
1946   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1947   // Limit recursion depth.
1948   if (Depth > MaxExtDepth) {
1949     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1950                                                      Op, Ty);
1951     UniqueSCEVs.InsertNode(S, IP);
1952     addToLoopUseLists(S);
1953     return S;
1954   }
1955 
1956   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1957   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1958     // It's possible the bits taken off by the truncate were all sign bits. If
1959     // so, we should be able to simplify this further.
1960     const SCEV *X = ST->getOperand();
1961     ConstantRange CR = getSignedRange(X);
1962     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1963     unsigned NewBits = getTypeSizeInBits(Ty);
1964     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1965             CR.sextOrTrunc(NewBits)))
1966       return getTruncateOrSignExtend(X, Ty);
1967   }
1968 
1969   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1970     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1971     if (SA->hasNoSignedWrap()) {
1972       // If the addition does not sign overflow then we can, by definition,
1973       // commute the sign extension with the addition operation.
1974       SmallVector<const SCEV *, 4> Ops;
1975       for (const auto *Op : SA->operands())
1976         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1977       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1978     }
1979 
1980     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1981     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1982     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1983     //
1984     // For instance, this will bring two seemingly different expressions:
1985     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1986     //         sext(6 + 20 * %x + 24 * %y)
1987     // to the same form:
1988     //     2 + sext(4 + 20 * %x + 24 * %y)
1989     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1990       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1991       if (D != 0) {
1992         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1993         const SCEV *SResidual =
1994             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1995         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1996         return getAddExpr(SSExtD, SSExtR,
1997                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1998                           Depth + 1);
1999       }
2000     }
2001   }
2002   // If the input value is a chrec scev, and we can prove that the value
2003   // did not overflow the old, smaller, value, we can sign extend all of the
2004   // operands (often constants).  This allows analysis of something like
2005   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
2006   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2007     if (AR->isAffine()) {
2008       const SCEV *Start = AR->getStart();
2009       const SCEV *Step = AR->getStepRecurrence(*this);
2010       unsigned BitWidth = getTypeSizeInBits(AR->getType());
2011       const Loop *L = AR->getLoop();
2012 
2013       if (!AR->hasNoSignedWrap()) {
2014         auto NewFlags = proveNoWrapViaConstantRanges(AR);
2015         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2016       }
2017 
2018       // If we have special knowledge that this addrec won't overflow,
2019       // we don't need to do any further analysis.
2020       if (AR->hasNoSignedWrap())
2021         return getAddRecExpr(
2022             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2023             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2024 
2025       // Check whether the backedge-taken count is SCEVCouldNotCompute.
2026       // Note that this serves two purposes: It filters out loops that are
2027       // simply not analyzable, and it covers the case where this code is
2028       // being called from within backedge-taken count analysis, such that
2029       // attempting to ask for the backedge-taken count would likely result
2030       // in infinite recursion. In the later case, the analysis code will
2031       // cope with a conservative value, and it will take care to purge
2032       // that value once it has finished.
2033       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
2034       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2035         // Manually compute the final value for AR, checking for
2036         // overflow.
2037 
2038         // Check whether the backedge-taken count can be losslessly casted to
2039         // the addrec's type. The count is always unsigned.
2040         const SCEV *CastedMaxBECount =
2041           getTruncateOrZeroExtend(MaxBECount, Start->getType());
2042         const SCEV *RecastedMaxBECount =
2043           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
2044         if (MaxBECount == RecastedMaxBECount) {
2045           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2046           // Check whether Start+Step*MaxBECount has no signed overflow.
2047           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2048                                         SCEV::FlagAnyWrap, Depth + 1);
2049           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2050                                                           SCEV::FlagAnyWrap,
2051                                                           Depth + 1),
2052                                                WideTy, Depth + 1);
2053           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2054           const SCEV *WideMaxBECount =
2055             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2056           const SCEV *OperandExtendedAdd =
2057             getAddExpr(WideStart,
2058                        getMulExpr(WideMaxBECount,
2059                                   getSignExtendExpr(Step, WideTy, Depth + 1),
2060                                   SCEV::FlagAnyWrap, Depth + 1),
2061                        SCEV::FlagAnyWrap, Depth + 1);
2062           if (SAdd == OperandExtendedAdd) {
2063             // Cache knowledge of AR NSW, which is propagated to this AddRec.
2064             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2065             // Return the expression with the addrec on the outside.
2066             return getAddRecExpr(
2067                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2068                                                          Depth + 1),
2069                 getSignExtendExpr(Step, Ty, Depth + 1), L,
2070                 AR->getNoWrapFlags());
2071           }
2072           // Similar to above, only this time treat the step value as unsigned.
2073           // This covers loops that count up with an unsigned step.
2074           OperandExtendedAdd =
2075             getAddExpr(WideStart,
2076                        getMulExpr(WideMaxBECount,
2077                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
2078                                   SCEV::FlagAnyWrap, Depth + 1),
2079                        SCEV::FlagAnyWrap, Depth + 1);
2080           if (SAdd == OperandExtendedAdd) {
2081             // If AR wraps around then
2082             //
2083             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
2084             // => SAdd != OperandExtendedAdd
2085             //
2086             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2087             // (SAdd == OperandExtendedAdd => AR is NW)
2088 
2089             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2090 
2091             // Return the expression with the addrec on the outside.
2092             return getAddRecExpr(
2093                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2094                                                          Depth + 1),
2095                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2096                 AR->getNoWrapFlags());
2097           }
2098         }
2099       }
2100 
2101       // Normally, in the cases we can prove no-overflow via a
2102       // backedge guarding condition, we can also compute a backedge
2103       // taken count for the loop.  The exceptions are assumptions and
2104       // guards present in the loop -- SCEV is not great at exploiting
2105       // these to compute max backedge taken counts, but can still use
2106       // these to prove lack of overflow.  Use this fact to avoid
2107       // doing extra work that may not pay off.
2108 
2109       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2110           !AC.assumptions().empty()) {
2111         // If the backedge is guarded by a comparison with the pre-inc
2112         // value the addrec is safe. Also, if the entry is guarded by
2113         // a comparison with the start value and the backedge is
2114         // guarded by a comparison with the post-inc value, the addrec
2115         // is safe.
2116         ICmpInst::Predicate Pred;
2117         const SCEV *OverflowLimit =
2118             getSignedOverflowLimitForStep(Step, &Pred, this);
2119         if (OverflowLimit &&
2120             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2121              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2122           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2123           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2124           return getAddRecExpr(
2125               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2126               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2127         }
2128       }
2129 
2130       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2131       // if D + (C - D + Step * n) could be proven to not signed wrap
2132       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2133       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2134         const APInt &C = SC->getAPInt();
2135         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2136         if (D != 0) {
2137           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2138           const SCEV *SResidual =
2139               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2140           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2141           return getAddExpr(SSExtD, SSExtR,
2142                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2143                             Depth + 1);
2144         }
2145       }
2146 
2147       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2148         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2149         return getAddRecExpr(
2150             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2151             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2152       }
2153     }
2154 
2155   // If the input value is provably positive and we could not simplify
2156   // away the sext build a zext instead.
2157   if (isKnownNonNegative(Op))
2158     return getZeroExtendExpr(Op, Ty, Depth + 1);
2159 
2160   // The cast wasn't folded; create an explicit cast node.
2161   // Recompute the insert position, as it may have been invalidated.
2162   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2163   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2164                                                    Op, Ty);
2165   UniqueSCEVs.InsertNode(S, IP);
2166   addToLoopUseLists(S);
2167   return S;
2168 }
2169 
2170 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2171 /// unspecified bits out to the given type.
2172 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2173                                               Type *Ty) {
2174   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2175          "This is not an extending conversion!");
2176   assert(isSCEVable(Ty) &&
2177          "This is not a conversion to a SCEVable type!");
2178   Ty = getEffectiveSCEVType(Ty);
2179 
2180   // Sign-extend negative constants.
2181   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2182     if (SC->getAPInt().isNegative())
2183       return getSignExtendExpr(Op, Ty);
2184 
2185   // Peel off a truncate cast.
2186   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2187     const SCEV *NewOp = T->getOperand();
2188     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2189       return getAnyExtendExpr(NewOp, Ty);
2190     return getTruncateOrNoop(NewOp, Ty);
2191   }
2192 
2193   // Next try a zext cast. If the cast is folded, use it.
2194   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2195   if (!isa<SCEVZeroExtendExpr>(ZExt))
2196     return ZExt;
2197 
2198   // Next try a sext cast. If the cast is folded, use it.
2199   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2200   if (!isa<SCEVSignExtendExpr>(SExt))
2201     return SExt;
2202 
2203   // Force the cast to be folded into the operands of an addrec.
2204   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2205     SmallVector<const SCEV *, 4> Ops;
2206     for (const SCEV *Op : AR->operands())
2207       Ops.push_back(getAnyExtendExpr(Op, Ty));
2208     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2209   }
2210 
2211   // If the expression is obviously signed, use the sext cast value.
2212   if (isa<SCEVSMaxExpr>(Op))
2213     return SExt;
2214 
2215   // Absent any other information, use the zext cast value.
2216   return ZExt;
2217 }
2218 
2219 /// Process the given Ops list, which is a list of operands to be added under
2220 /// the given scale, update the given map. This is a helper function for
2221 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2222 /// that would form an add expression like this:
2223 ///
2224 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2225 ///
2226 /// where A and B are constants, update the map with these values:
2227 ///
2228 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2229 ///
2230 /// and add 13 + A*B*29 to AccumulatedConstant.
2231 /// This will allow getAddRecExpr to produce this:
2232 ///
2233 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2234 ///
2235 /// This form often exposes folding opportunities that are hidden in
2236 /// the original operand list.
2237 ///
2238 /// Return true iff it appears that any interesting folding opportunities
2239 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2240 /// the common case where no interesting opportunities are present, and
2241 /// is also used as a check to avoid infinite recursion.
2242 static bool
2243 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2244                              SmallVectorImpl<const SCEV *> &NewOps,
2245                              APInt &AccumulatedConstant,
2246                              const SCEV *const *Ops, size_t NumOperands,
2247                              const APInt &Scale,
2248                              ScalarEvolution &SE) {
2249   bool Interesting = false;
2250 
2251   // Iterate over the add operands. They are sorted, with constants first.
2252   unsigned i = 0;
2253   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2254     ++i;
2255     // Pull a buried constant out to the outside.
2256     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2257       Interesting = true;
2258     AccumulatedConstant += Scale * C->getAPInt();
2259   }
2260 
2261   // Next comes everything else. We're especially interested in multiplies
2262   // here, but they're in the middle, so just visit the rest with one loop.
2263   for (; i != NumOperands; ++i) {
2264     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2265     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2266       APInt NewScale =
2267           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2268       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2269         // A multiplication of a constant with another add; recurse.
2270         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2271         Interesting |=
2272           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2273                                        Add->op_begin(), Add->getNumOperands(),
2274                                        NewScale, SE);
2275       } else {
2276         // A multiplication of a constant with some other value. Update
2277         // the map.
2278         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2279         const SCEV *Key = SE.getMulExpr(MulOps);
2280         auto Pair = M.insert({Key, NewScale});
2281         if (Pair.second) {
2282           NewOps.push_back(Pair.first->first);
2283         } else {
2284           Pair.first->second += NewScale;
2285           // The map already had an entry for this value, which may indicate
2286           // a folding opportunity.
2287           Interesting = true;
2288         }
2289       }
2290     } else {
2291       // An ordinary operand. Update the map.
2292       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2293           M.insert({Ops[i], Scale});
2294       if (Pair.second) {
2295         NewOps.push_back(Pair.first->first);
2296       } else {
2297         Pair.first->second += Scale;
2298         // The map already had an entry for this value, which may indicate
2299         // a folding opportunity.
2300         Interesting = true;
2301       }
2302     }
2303   }
2304 
2305   return Interesting;
2306 }
2307 
2308 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2309 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2310 // can't-overflow flags for the operation if possible.
2311 static SCEV::NoWrapFlags
2312 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2313                       const ArrayRef<const SCEV *> Ops,
2314                       SCEV::NoWrapFlags Flags) {
2315   using namespace std::placeholders;
2316 
2317   using OBO = OverflowingBinaryOperator;
2318 
2319   bool CanAnalyze =
2320       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2321   (void)CanAnalyze;
2322   assert(CanAnalyze && "don't call from other places!");
2323 
2324   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2325   SCEV::NoWrapFlags SignOrUnsignWrap =
2326       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2327 
2328   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2329   auto IsKnownNonNegative = [&](const SCEV *S) {
2330     return SE->isKnownNonNegative(S);
2331   };
2332 
2333   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2334     Flags =
2335         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2336 
2337   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2338 
2339   if (SignOrUnsignWrap != SignOrUnsignMask &&
2340       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2341       isa<SCEVConstant>(Ops[0])) {
2342 
2343     auto Opcode = [&] {
2344       switch (Type) {
2345       case scAddExpr:
2346         return Instruction::Add;
2347       case scMulExpr:
2348         return Instruction::Mul;
2349       default:
2350         llvm_unreachable("Unexpected SCEV op.");
2351       }
2352     }();
2353 
2354     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2355 
2356     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2357     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2358       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2359           Opcode, C, OBO::NoSignedWrap);
2360       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2361         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2362     }
2363 
2364     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2365     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2366       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2367           Opcode, C, OBO::NoUnsignedWrap);
2368       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2369         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2370     }
2371   }
2372 
2373   return Flags;
2374 }
2375 
2376 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2377   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2378 }
2379 
2380 /// Get a canonical add expression, or something simpler if possible.
2381 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2382                                         SCEV::NoWrapFlags Flags,
2383                                         unsigned Depth) {
2384   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2385          "only nuw or nsw allowed");
2386   assert(!Ops.empty() && "Cannot get empty add!");
2387   if (Ops.size() == 1) return Ops[0];
2388 #ifndef NDEBUG
2389   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2390   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2391     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2392            "SCEVAddExpr operand types don't match!");
2393 #endif
2394 
2395   // Sort by complexity, this groups all similar expression types together.
2396   GroupByComplexity(Ops, &LI, DT);
2397 
2398   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2399 
2400   // If there are any constants, fold them together.
2401   unsigned Idx = 0;
2402   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2403     ++Idx;
2404     assert(Idx < Ops.size());
2405     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2406       // We found two constants, fold them together!
2407       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2408       if (Ops.size() == 2) return Ops[0];
2409       Ops.erase(Ops.begin()+1);  // Erase the folded element
2410       LHSC = cast<SCEVConstant>(Ops[0]);
2411     }
2412 
2413     // If we are left with a constant zero being added, strip it off.
2414     if (LHSC->getValue()->isZero()) {
2415       Ops.erase(Ops.begin());
2416       --Idx;
2417     }
2418 
2419     if (Ops.size() == 1) return Ops[0];
2420   }
2421 
2422   // Limit recursion calls depth.
2423   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2424     return getOrCreateAddExpr(Ops, Flags);
2425 
2426   // Okay, check to see if the same value occurs in the operand list more than
2427   // once.  If so, merge them together into an multiply expression.  Since we
2428   // sorted the list, these values are required to be adjacent.
2429   Type *Ty = Ops[0]->getType();
2430   bool FoundMatch = false;
2431   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2432     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2433       // Scan ahead to count how many equal operands there are.
2434       unsigned Count = 2;
2435       while (i+Count != e && Ops[i+Count] == Ops[i])
2436         ++Count;
2437       // Merge the values into a multiply.
2438       const SCEV *Scale = getConstant(Ty, Count);
2439       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2440       if (Ops.size() == Count)
2441         return Mul;
2442       Ops[i] = Mul;
2443       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2444       --i; e -= Count - 1;
2445       FoundMatch = true;
2446     }
2447   if (FoundMatch)
2448     return getAddExpr(Ops, Flags, Depth + 1);
2449 
2450   // Check for truncates. If all the operands are truncated from the same
2451   // type, see if factoring out the truncate would permit the result to be
2452   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2453   // if the contents of the resulting outer trunc fold to something simple.
2454   auto FindTruncSrcType = [&]() -> Type * {
2455     // We're ultimately looking to fold an addrec of truncs and muls of only
2456     // constants and truncs, so if we find any other types of SCEV
2457     // as operands of the addrec then we bail and return nullptr here.
2458     // Otherwise, we return the type of the operand of a trunc that we find.
2459     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2460       return T->getOperand()->getType();
2461     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2462       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2463       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2464         return T->getOperand()->getType();
2465     }
2466     return nullptr;
2467   };
2468   if (auto *SrcType = FindTruncSrcType()) {
2469     SmallVector<const SCEV *, 8> LargeOps;
2470     bool Ok = true;
2471     // Check all the operands to see if they can be represented in the
2472     // source type of the truncate.
2473     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2474       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2475         if (T->getOperand()->getType() != SrcType) {
2476           Ok = false;
2477           break;
2478         }
2479         LargeOps.push_back(T->getOperand());
2480       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2481         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2482       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2483         SmallVector<const SCEV *, 8> LargeMulOps;
2484         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2485           if (const SCEVTruncateExpr *T =
2486                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2487             if (T->getOperand()->getType() != SrcType) {
2488               Ok = false;
2489               break;
2490             }
2491             LargeMulOps.push_back(T->getOperand());
2492           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2493             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2494           } else {
2495             Ok = false;
2496             break;
2497           }
2498         }
2499         if (Ok)
2500           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2501       } else {
2502         Ok = false;
2503         break;
2504       }
2505     }
2506     if (Ok) {
2507       // Evaluate the expression in the larger type.
2508       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2509       // If it folds to something simple, use it. Otherwise, don't.
2510       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2511         return getTruncateExpr(Fold, Ty);
2512     }
2513   }
2514 
2515   // Skip past any other cast SCEVs.
2516   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2517     ++Idx;
2518 
2519   // If there are add operands they would be next.
2520   if (Idx < Ops.size()) {
2521     bool DeletedAdd = false;
2522     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2523       if (Ops.size() > AddOpsInlineThreshold ||
2524           Add->getNumOperands() > AddOpsInlineThreshold)
2525         break;
2526       // If we have an add, expand the add operands onto the end of the operands
2527       // list.
2528       Ops.erase(Ops.begin()+Idx);
2529       Ops.append(Add->op_begin(), Add->op_end());
2530       DeletedAdd = true;
2531     }
2532 
2533     // If we deleted at least one add, we added operands to the end of the list,
2534     // and they are not necessarily sorted.  Recurse to resort and resimplify
2535     // any operands we just acquired.
2536     if (DeletedAdd)
2537       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2538   }
2539 
2540   // Skip over the add expression until we get to a multiply.
2541   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2542     ++Idx;
2543 
2544   // Check to see if there are any folding opportunities present with
2545   // operands multiplied by constant values.
2546   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2547     uint64_t BitWidth = getTypeSizeInBits(Ty);
2548     DenseMap<const SCEV *, APInt> M;
2549     SmallVector<const SCEV *, 8> NewOps;
2550     APInt AccumulatedConstant(BitWidth, 0);
2551     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2552                                      Ops.data(), Ops.size(),
2553                                      APInt(BitWidth, 1), *this)) {
2554       struct APIntCompare {
2555         bool operator()(const APInt &LHS, const APInt &RHS) const {
2556           return LHS.ult(RHS);
2557         }
2558       };
2559 
2560       // Some interesting folding opportunity is present, so its worthwhile to
2561       // re-generate the operands list. Group the operands by constant scale,
2562       // to avoid multiplying by the same constant scale multiple times.
2563       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2564       for (const SCEV *NewOp : NewOps)
2565         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2566       // Re-generate the operands list.
2567       Ops.clear();
2568       if (AccumulatedConstant != 0)
2569         Ops.push_back(getConstant(AccumulatedConstant));
2570       for (auto &MulOp : MulOpLists)
2571         if (MulOp.first != 0)
2572           Ops.push_back(getMulExpr(
2573               getConstant(MulOp.first),
2574               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2575               SCEV::FlagAnyWrap, Depth + 1));
2576       if (Ops.empty())
2577         return getZero(Ty);
2578       if (Ops.size() == 1)
2579         return Ops[0];
2580       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2581     }
2582   }
2583 
2584   // If we are adding something to a multiply expression, make sure the
2585   // something is not already an operand of the multiply.  If so, merge it into
2586   // the multiply.
2587   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2588     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2589     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2590       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2591       if (isa<SCEVConstant>(MulOpSCEV))
2592         continue;
2593       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2594         if (MulOpSCEV == Ops[AddOp]) {
2595           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2596           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2597           if (Mul->getNumOperands() != 2) {
2598             // If the multiply has more than two operands, we must get the
2599             // Y*Z term.
2600             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2601                                                 Mul->op_begin()+MulOp);
2602             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2603             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2604           }
2605           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2606           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2607           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2608                                             SCEV::FlagAnyWrap, Depth + 1);
2609           if (Ops.size() == 2) return OuterMul;
2610           if (AddOp < Idx) {
2611             Ops.erase(Ops.begin()+AddOp);
2612             Ops.erase(Ops.begin()+Idx-1);
2613           } else {
2614             Ops.erase(Ops.begin()+Idx);
2615             Ops.erase(Ops.begin()+AddOp-1);
2616           }
2617           Ops.push_back(OuterMul);
2618           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2619         }
2620 
2621       // Check this multiply against other multiplies being added together.
2622       for (unsigned OtherMulIdx = Idx+1;
2623            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2624            ++OtherMulIdx) {
2625         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2626         // If MulOp occurs in OtherMul, we can fold the two multiplies
2627         // together.
2628         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2629              OMulOp != e; ++OMulOp)
2630           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2631             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2632             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2633             if (Mul->getNumOperands() != 2) {
2634               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2635                                                   Mul->op_begin()+MulOp);
2636               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2637               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2638             }
2639             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2640             if (OtherMul->getNumOperands() != 2) {
2641               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2642                                                   OtherMul->op_begin()+OMulOp);
2643               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2644               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2645             }
2646             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2647             const SCEV *InnerMulSum =
2648                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2649             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2650                                               SCEV::FlagAnyWrap, Depth + 1);
2651             if (Ops.size() == 2) return OuterMul;
2652             Ops.erase(Ops.begin()+Idx);
2653             Ops.erase(Ops.begin()+OtherMulIdx-1);
2654             Ops.push_back(OuterMul);
2655             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2656           }
2657       }
2658     }
2659   }
2660 
2661   // If there are any add recurrences in the operands list, see if any other
2662   // added values are loop invariant.  If so, we can fold them into the
2663   // recurrence.
2664   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2665     ++Idx;
2666 
2667   // Scan over all recurrences, trying to fold loop invariants into them.
2668   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2669     // Scan all of the other operands to this add and add them to the vector if
2670     // they are loop invariant w.r.t. the recurrence.
2671     SmallVector<const SCEV *, 8> LIOps;
2672     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2673     const Loop *AddRecLoop = AddRec->getLoop();
2674     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2675       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2676         LIOps.push_back(Ops[i]);
2677         Ops.erase(Ops.begin()+i);
2678         --i; --e;
2679       }
2680 
2681     // If we found some loop invariants, fold them into the recurrence.
2682     if (!LIOps.empty()) {
2683       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2684       LIOps.push_back(AddRec->getStart());
2685 
2686       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2687                                              AddRec->op_end());
2688       // This follows from the fact that the no-wrap flags on the outer add
2689       // expression are applicable on the 0th iteration, when the add recurrence
2690       // will be equal to its start value.
2691       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2692 
2693       // Build the new addrec. Propagate the NUW and NSW flags if both the
2694       // outer add and the inner addrec are guaranteed to have no overflow.
2695       // Always propagate NW.
2696       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2697       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2698 
2699       // If all of the other operands were loop invariant, we are done.
2700       if (Ops.size() == 1) return NewRec;
2701 
2702       // Otherwise, add the folded AddRec by the non-invariant parts.
2703       for (unsigned i = 0;; ++i)
2704         if (Ops[i] == AddRec) {
2705           Ops[i] = NewRec;
2706           break;
2707         }
2708       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2709     }
2710 
2711     // Okay, if there weren't any loop invariants to be folded, check to see if
2712     // there are multiple AddRec's with the same loop induction variable being
2713     // added together.  If so, we can fold them.
2714     for (unsigned OtherIdx = Idx+1;
2715          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2716          ++OtherIdx) {
2717       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2718       // so that the 1st found AddRecExpr is dominated by all others.
2719       assert(DT.dominates(
2720            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2721            AddRec->getLoop()->getHeader()) &&
2722         "AddRecExprs are not sorted in reverse dominance order?");
2723       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2724         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2725         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2726                                                AddRec->op_end());
2727         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2728              ++OtherIdx) {
2729           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2730           if (OtherAddRec->getLoop() == AddRecLoop) {
2731             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2732                  i != e; ++i) {
2733               if (i >= AddRecOps.size()) {
2734                 AddRecOps.append(OtherAddRec->op_begin()+i,
2735                                  OtherAddRec->op_end());
2736                 break;
2737               }
2738               SmallVector<const SCEV *, 2> TwoOps = {
2739                   AddRecOps[i], OtherAddRec->getOperand(i)};
2740               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2741             }
2742             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2743           }
2744         }
2745         // Step size has changed, so we cannot guarantee no self-wraparound.
2746         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2747         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2748       }
2749     }
2750 
2751     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2752     // next one.
2753   }
2754 
2755   // Okay, it looks like we really DO need an add expr.  Check to see if we
2756   // already have one, otherwise create a new one.
2757   return getOrCreateAddExpr(Ops, Flags);
2758 }
2759 
2760 const SCEV *
2761 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2762                                     SCEV::NoWrapFlags Flags) {
2763   FoldingSetNodeID ID;
2764   ID.AddInteger(scAddExpr);
2765   for (const SCEV *Op : Ops)
2766     ID.AddPointer(Op);
2767   void *IP = nullptr;
2768   SCEVAddExpr *S =
2769       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2770   if (!S) {
2771     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2772     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2773     S = new (SCEVAllocator)
2774         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2775     UniqueSCEVs.InsertNode(S, IP);
2776     addToLoopUseLists(S);
2777   }
2778   S->setNoWrapFlags(Flags);
2779   return S;
2780 }
2781 
2782 const SCEV *
2783 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2784                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2785   FoldingSetNodeID ID;
2786   ID.AddInteger(scAddRecExpr);
2787   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2788     ID.AddPointer(Ops[i]);
2789   ID.AddPointer(L);
2790   void *IP = nullptr;
2791   SCEVAddRecExpr *S =
2792       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2793   if (!S) {
2794     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2795     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2796     S = new (SCEVAllocator)
2797         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2798     UniqueSCEVs.InsertNode(S, IP);
2799     addToLoopUseLists(S);
2800   }
2801   S->setNoWrapFlags(Flags);
2802   return S;
2803 }
2804 
2805 const SCEV *
2806 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2807                                     SCEV::NoWrapFlags Flags) {
2808   FoldingSetNodeID ID;
2809   ID.AddInteger(scMulExpr);
2810   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2811     ID.AddPointer(Ops[i]);
2812   void *IP = nullptr;
2813   SCEVMulExpr *S =
2814     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2815   if (!S) {
2816     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2817     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2818     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2819                                         O, Ops.size());
2820     UniqueSCEVs.InsertNode(S, IP);
2821     addToLoopUseLists(S);
2822   }
2823   S->setNoWrapFlags(Flags);
2824   return S;
2825 }
2826 
2827 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2828   uint64_t k = i*j;
2829   if (j > 1 && k / j != i) Overflow = true;
2830   return k;
2831 }
2832 
2833 /// Compute the result of "n choose k", the binomial coefficient.  If an
2834 /// intermediate computation overflows, Overflow will be set and the return will
2835 /// be garbage. Overflow is not cleared on absence of overflow.
2836 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2837   // We use the multiplicative formula:
2838   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2839   // At each iteration, we take the n-th term of the numeral and divide by the
2840   // (k-n)th term of the denominator.  This division will always produce an
2841   // integral result, and helps reduce the chance of overflow in the
2842   // intermediate computations. However, we can still overflow even when the
2843   // final result would fit.
2844 
2845   if (n == 0 || n == k) return 1;
2846   if (k > n) return 0;
2847 
2848   if (k > n/2)
2849     k = n-k;
2850 
2851   uint64_t r = 1;
2852   for (uint64_t i = 1; i <= k; ++i) {
2853     r = umul_ov(r, n-(i-1), Overflow);
2854     r /= i;
2855   }
2856   return r;
2857 }
2858 
2859 /// Determine if any of the operands in this SCEV are a constant or if
2860 /// any of the add or multiply expressions in this SCEV contain a constant.
2861 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2862   struct FindConstantInAddMulChain {
2863     bool FoundConstant = false;
2864 
2865     bool follow(const SCEV *S) {
2866       FoundConstant |= isa<SCEVConstant>(S);
2867       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2868     }
2869 
2870     bool isDone() const {
2871       return FoundConstant;
2872     }
2873   };
2874 
2875   FindConstantInAddMulChain F;
2876   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2877   ST.visitAll(StartExpr);
2878   return F.FoundConstant;
2879 }
2880 
2881 /// Get a canonical multiply expression, or something simpler if possible.
2882 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2883                                         SCEV::NoWrapFlags Flags,
2884                                         unsigned Depth) {
2885   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2886          "only nuw or nsw allowed");
2887   assert(!Ops.empty() && "Cannot get empty mul!");
2888   if (Ops.size() == 1) return Ops[0];
2889 #ifndef NDEBUG
2890   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2891   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2892     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2893            "SCEVMulExpr operand types don't match!");
2894 #endif
2895 
2896   // Sort by complexity, this groups all similar expression types together.
2897   GroupByComplexity(Ops, &LI, DT);
2898 
2899   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2900 
2901   // Limit recursion calls depth.
2902   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2903     return getOrCreateMulExpr(Ops, Flags);
2904 
2905   // If there are any constants, fold them together.
2906   unsigned Idx = 0;
2907   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2908 
2909     if (Ops.size() == 2)
2910       // C1*(C2+V) -> C1*C2 + C1*V
2911       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2912         // If any of Add's ops are Adds or Muls with a constant, apply this
2913         // transformation as well.
2914         //
2915         // TODO: There are some cases where this transformation is not
2916         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2917         // this transformation should be narrowed down.
2918         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2919           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2920                                        SCEV::FlagAnyWrap, Depth + 1),
2921                             getMulExpr(LHSC, Add->getOperand(1),
2922                                        SCEV::FlagAnyWrap, Depth + 1),
2923                             SCEV::FlagAnyWrap, Depth + 1);
2924 
2925     ++Idx;
2926     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2927       // We found two constants, fold them together!
2928       ConstantInt *Fold =
2929           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2930       Ops[0] = getConstant(Fold);
2931       Ops.erase(Ops.begin()+1);  // Erase the folded element
2932       if (Ops.size() == 1) return Ops[0];
2933       LHSC = cast<SCEVConstant>(Ops[0]);
2934     }
2935 
2936     // If we are left with a constant one being multiplied, strip it off.
2937     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2938       Ops.erase(Ops.begin());
2939       --Idx;
2940     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2941       // If we have a multiply of zero, it will always be zero.
2942       return Ops[0];
2943     } else if (Ops[0]->isAllOnesValue()) {
2944       // If we have a mul by -1 of an add, try distributing the -1 among the
2945       // add operands.
2946       if (Ops.size() == 2) {
2947         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2948           SmallVector<const SCEV *, 4> NewOps;
2949           bool AnyFolded = false;
2950           for (const SCEV *AddOp : Add->operands()) {
2951             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2952                                          Depth + 1);
2953             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2954             NewOps.push_back(Mul);
2955           }
2956           if (AnyFolded)
2957             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2958         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2959           // Negation preserves a recurrence's no self-wrap property.
2960           SmallVector<const SCEV *, 4> Operands;
2961           for (const SCEV *AddRecOp : AddRec->operands())
2962             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2963                                           Depth + 1));
2964 
2965           return getAddRecExpr(Operands, AddRec->getLoop(),
2966                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2967         }
2968       }
2969     }
2970 
2971     if (Ops.size() == 1)
2972       return Ops[0];
2973   }
2974 
2975   // Skip over the add expression until we get to a multiply.
2976   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2977     ++Idx;
2978 
2979   // If there are mul operands inline them all into this expression.
2980   if (Idx < Ops.size()) {
2981     bool DeletedMul = false;
2982     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2983       if (Ops.size() > MulOpsInlineThreshold)
2984         break;
2985       // If we have an mul, expand the mul operands onto the end of the
2986       // operands list.
2987       Ops.erase(Ops.begin()+Idx);
2988       Ops.append(Mul->op_begin(), Mul->op_end());
2989       DeletedMul = true;
2990     }
2991 
2992     // If we deleted at least one mul, we added operands to the end of the
2993     // list, and they are not necessarily sorted.  Recurse to resort and
2994     // resimplify any operands we just acquired.
2995     if (DeletedMul)
2996       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2997   }
2998 
2999   // If there are any add recurrences in the operands list, see if any other
3000   // added values are loop invariant.  If so, we can fold them into the
3001   // recurrence.
3002   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3003     ++Idx;
3004 
3005   // Scan over all recurrences, trying to fold loop invariants into them.
3006   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3007     // Scan all of the other operands to this mul and add them to the vector
3008     // if they are loop invariant w.r.t. the recurrence.
3009     SmallVector<const SCEV *, 8> LIOps;
3010     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3011     const Loop *AddRecLoop = AddRec->getLoop();
3012     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3013       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3014         LIOps.push_back(Ops[i]);
3015         Ops.erase(Ops.begin()+i);
3016         --i; --e;
3017       }
3018 
3019     // If we found some loop invariants, fold them into the recurrence.
3020     if (!LIOps.empty()) {
3021       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
3022       SmallVector<const SCEV *, 4> NewOps;
3023       NewOps.reserve(AddRec->getNumOperands());
3024       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3025       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3026         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3027                                     SCEV::FlagAnyWrap, Depth + 1));
3028 
3029       // Build the new addrec. Propagate the NUW and NSW flags if both the
3030       // outer mul and the inner addrec are guaranteed to have no overflow.
3031       //
3032       // No self-wrap cannot be guaranteed after changing the step size, but
3033       // will be inferred if either NUW or NSW is true.
3034       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3035       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3036 
3037       // If all of the other operands were loop invariant, we are done.
3038       if (Ops.size() == 1) return NewRec;
3039 
3040       // Otherwise, multiply the folded AddRec by the non-invariant parts.
3041       for (unsigned i = 0;; ++i)
3042         if (Ops[i] == AddRec) {
3043           Ops[i] = NewRec;
3044           break;
3045         }
3046       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3047     }
3048 
3049     // Okay, if there weren't any loop invariants to be folded, check to see
3050     // if there are multiple AddRec's with the same loop induction variable
3051     // being multiplied together.  If so, we can fold them.
3052 
3053     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3054     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3055     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3056     //   ]]],+,...up to x=2n}.
3057     // Note that the arguments to choose() are always integers with values
3058     // known at compile time, never SCEV objects.
3059     //
3060     // The implementation avoids pointless extra computations when the two
3061     // addrec's are of different length (mathematically, it's equivalent to
3062     // an infinite stream of zeros on the right).
3063     bool OpsModified = false;
3064     for (unsigned OtherIdx = Idx+1;
3065          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3066          ++OtherIdx) {
3067       const SCEVAddRecExpr *OtherAddRec =
3068         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3069       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3070         continue;
3071 
3072       // Limit max number of arguments to avoid creation of unreasonably big
3073       // SCEVAddRecs with very complex operands.
3074       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3075           MaxAddRecSize || isHugeExpression(AddRec) ||
3076           isHugeExpression(OtherAddRec))
3077         continue;
3078 
3079       bool Overflow = false;
3080       Type *Ty = AddRec->getType();
3081       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3082       SmallVector<const SCEV*, 7> AddRecOps;
3083       for (int x = 0, xe = AddRec->getNumOperands() +
3084              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3085         SmallVector <const SCEV *, 7> SumOps;
3086         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3087           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3088           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3089                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3090                z < ze && !Overflow; ++z) {
3091             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3092             uint64_t Coeff;
3093             if (LargerThan64Bits)
3094               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3095             else
3096               Coeff = Coeff1*Coeff2;
3097             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3098             const SCEV *Term1 = AddRec->getOperand(y-z);
3099             const SCEV *Term2 = OtherAddRec->getOperand(z);
3100             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3101                                         SCEV::FlagAnyWrap, Depth + 1));
3102           }
3103         }
3104         if (SumOps.empty())
3105           SumOps.push_back(getZero(Ty));
3106         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3107       }
3108       if (!Overflow) {
3109         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3110                                               SCEV::FlagAnyWrap);
3111         if (Ops.size() == 2) return NewAddRec;
3112         Ops[Idx] = NewAddRec;
3113         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3114         OpsModified = true;
3115         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3116         if (!AddRec)
3117           break;
3118       }
3119     }
3120     if (OpsModified)
3121       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3122 
3123     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3124     // next one.
3125   }
3126 
3127   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3128   // already have one, otherwise create a new one.
3129   return getOrCreateMulExpr(Ops, Flags);
3130 }
3131 
3132 /// Represents an unsigned remainder expression based on unsigned division.
3133 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3134                                          const SCEV *RHS) {
3135   assert(getEffectiveSCEVType(LHS->getType()) ==
3136          getEffectiveSCEVType(RHS->getType()) &&
3137          "SCEVURemExpr operand types don't match!");
3138 
3139   // Short-circuit easy cases
3140   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3141     // If constant is one, the result is trivial
3142     if (RHSC->getValue()->isOne())
3143       return getZero(LHS->getType()); // X urem 1 --> 0
3144 
3145     // If constant is a power of two, fold into a zext(trunc(LHS)).
3146     if (RHSC->getAPInt().isPowerOf2()) {
3147       Type *FullTy = LHS->getType();
3148       Type *TruncTy =
3149           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3150       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3151     }
3152   }
3153 
3154   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3155   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3156   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3157   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3158 }
3159 
3160 /// Get a canonical unsigned division expression, or something simpler if
3161 /// possible.
3162 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3163                                          const SCEV *RHS) {
3164   assert(getEffectiveSCEVType(LHS->getType()) ==
3165          getEffectiveSCEVType(RHS->getType()) &&
3166          "SCEVUDivExpr operand types don't match!");
3167 
3168   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3169     if (RHSC->getValue()->isOne())
3170       return LHS;                               // X udiv 1 --> x
3171     // If the denominator is zero, the result of the udiv is undefined. Don't
3172     // try to analyze it, because the resolution chosen here may differ from
3173     // the resolution chosen in other parts of the compiler.
3174     if (!RHSC->getValue()->isZero()) {
3175       // Determine if the division can be folded into the operands of
3176       // its operands.
3177       // TODO: Generalize this to non-constants by using known-bits information.
3178       Type *Ty = LHS->getType();
3179       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3180       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3181       // For non-power-of-two values, effectively round the value up to the
3182       // nearest power of two.
3183       if (!RHSC->getAPInt().isPowerOf2())
3184         ++MaxShiftAmt;
3185       IntegerType *ExtTy =
3186         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3187       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3188         if (const SCEVConstant *Step =
3189             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3190           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3191           const APInt &StepInt = Step->getAPInt();
3192           const APInt &DivInt = RHSC->getAPInt();
3193           if (!StepInt.urem(DivInt) &&
3194               getZeroExtendExpr(AR, ExtTy) ==
3195               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3196                             getZeroExtendExpr(Step, ExtTy),
3197                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3198             SmallVector<const SCEV *, 4> Operands;
3199             for (const SCEV *Op : AR->operands())
3200               Operands.push_back(getUDivExpr(Op, RHS));
3201             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3202           }
3203           /// Get a canonical UDivExpr for a recurrence.
3204           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3205           // We can currently only fold X%N if X is constant.
3206           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3207           if (StartC && !DivInt.urem(StepInt) &&
3208               getZeroExtendExpr(AR, ExtTy) ==
3209               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3210                             getZeroExtendExpr(Step, ExtTy),
3211                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3212             const APInt &StartInt = StartC->getAPInt();
3213             const APInt &StartRem = StartInt.urem(StepInt);
3214             if (StartRem != 0)
3215               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3216                                   AR->getLoop(), SCEV::FlagNW);
3217           }
3218         }
3219       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3220       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3221         SmallVector<const SCEV *, 4> Operands;
3222         for (const SCEV *Op : M->operands())
3223           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3224         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3225           // Find an operand that's safely divisible.
3226           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3227             const SCEV *Op = M->getOperand(i);
3228             const SCEV *Div = getUDivExpr(Op, RHSC);
3229             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3230               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3231                                                       M->op_end());
3232               Operands[i] = Div;
3233               return getMulExpr(Operands);
3234             }
3235           }
3236       }
3237 
3238       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3239       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3240         if (auto *DivisorConstant =
3241                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3242           bool Overflow = false;
3243           APInt NewRHS =
3244               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3245           if (Overflow) {
3246             return getConstant(RHSC->getType(), 0, false);
3247           }
3248           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3249         }
3250       }
3251 
3252       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3253       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3254         SmallVector<const SCEV *, 4> Operands;
3255         for (const SCEV *Op : A->operands())
3256           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3257         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3258           Operands.clear();
3259           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3260             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3261             if (isa<SCEVUDivExpr>(Op) ||
3262                 getMulExpr(Op, RHS) != A->getOperand(i))
3263               break;
3264             Operands.push_back(Op);
3265           }
3266           if (Operands.size() == A->getNumOperands())
3267             return getAddExpr(Operands);
3268         }
3269       }
3270 
3271       // Fold if both operands are constant.
3272       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3273         Constant *LHSCV = LHSC->getValue();
3274         Constant *RHSCV = RHSC->getValue();
3275         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3276                                                                    RHSCV)));
3277       }
3278     }
3279   }
3280 
3281   FoldingSetNodeID ID;
3282   ID.AddInteger(scUDivExpr);
3283   ID.AddPointer(LHS);
3284   ID.AddPointer(RHS);
3285   void *IP = nullptr;
3286   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3287   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3288                                              LHS, RHS);
3289   UniqueSCEVs.InsertNode(S, IP);
3290   addToLoopUseLists(S);
3291   return S;
3292 }
3293 
3294 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3295   APInt A = C1->getAPInt().abs();
3296   APInt B = C2->getAPInt().abs();
3297   uint32_t ABW = A.getBitWidth();
3298   uint32_t BBW = B.getBitWidth();
3299 
3300   if (ABW > BBW)
3301     B = B.zext(ABW);
3302   else if (ABW < BBW)
3303     A = A.zext(BBW);
3304 
3305   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3306 }
3307 
3308 /// Get a canonical unsigned division expression, or something simpler if
3309 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3310 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3311 /// it's not exact because the udiv may be clearing bits.
3312 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3313                                               const SCEV *RHS) {
3314   // TODO: we could try to find factors in all sorts of things, but for now we
3315   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3316   // end of this file for inspiration.
3317 
3318   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3319   if (!Mul || !Mul->hasNoUnsignedWrap())
3320     return getUDivExpr(LHS, RHS);
3321 
3322   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3323     // If the mulexpr multiplies by a constant, then that constant must be the
3324     // first element of the mulexpr.
3325     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3326       if (LHSCst == RHSCst) {
3327         SmallVector<const SCEV *, 2> Operands;
3328         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3329         return getMulExpr(Operands);
3330       }
3331 
3332       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3333       // that there's a factor provided by one of the other terms. We need to
3334       // check.
3335       APInt Factor = gcd(LHSCst, RHSCst);
3336       if (!Factor.isIntN(1)) {
3337         LHSCst =
3338             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3339         RHSCst =
3340             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3341         SmallVector<const SCEV *, 2> Operands;
3342         Operands.push_back(LHSCst);
3343         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3344         LHS = getMulExpr(Operands);
3345         RHS = RHSCst;
3346         Mul = dyn_cast<SCEVMulExpr>(LHS);
3347         if (!Mul)
3348           return getUDivExactExpr(LHS, RHS);
3349       }
3350     }
3351   }
3352 
3353   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3354     if (Mul->getOperand(i) == RHS) {
3355       SmallVector<const SCEV *, 2> Operands;
3356       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3357       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3358       return getMulExpr(Operands);
3359     }
3360   }
3361 
3362   return getUDivExpr(LHS, RHS);
3363 }
3364 
3365 /// Get an add recurrence expression for the specified loop.  Simplify the
3366 /// expression as much as possible.
3367 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3368                                            const Loop *L,
3369                                            SCEV::NoWrapFlags Flags) {
3370   SmallVector<const SCEV *, 4> Operands;
3371   Operands.push_back(Start);
3372   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3373     if (StepChrec->getLoop() == L) {
3374       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3375       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3376     }
3377 
3378   Operands.push_back(Step);
3379   return getAddRecExpr(Operands, L, Flags);
3380 }
3381 
3382 /// Get an add recurrence expression for the specified loop.  Simplify the
3383 /// expression as much as possible.
3384 const SCEV *
3385 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3386                                const Loop *L, SCEV::NoWrapFlags Flags) {
3387   if (Operands.size() == 1) return Operands[0];
3388 #ifndef NDEBUG
3389   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3390   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3391     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3392            "SCEVAddRecExpr operand types don't match!");
3393   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3394     assert(isLoopInvariant(Operands[i], L) &&
3395            "SCEVAddRecExpr operand is not loop-invariant!");
3396 #endif
3397 
3398   if (Operands.back()->isZero()) {
3399     Operands.pop_back();
3400     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3401   }
3402 
3403   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3404   // use that information to infer NUW and NSW flags. However, computing a
3405   // BE count requires calling getAddRecExpr, so we may not yet have a
3406   // meaningful BE count at this point (and if we don't, we'd be stuck
3407   // with a SCEVCouldNotCompute as the cached BE count).
3408 
3409   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3410 
3411   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3412   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3413     const Loop *NestedLoop = NestedAR->getLoop();
3414     if (L->contains(NestedLoop)
3415             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3416             : (!NestedLoop->contains(L) &&
3417                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3418       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3419                                                   NestedAR->op_end());
3420       Operands[0] = NestedAR->getStart();
3421       // AddRecs require their operands be loop-invariant with respect to their
3422       // loops. Don't perform this transformation if it would break this
3423       // requirement.
3424       bool AllInvariant = all_of(
3425           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3426 
3427       if (AllInvariant) {
3428         // Create a recurrence for the outer loop with the same step size.
3429         //
3430         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3431         // inner recurrence has the same property.
3432         SCEV::NoWrapFlags OuterFlags =
3433           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3434 
3435         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3436         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3437           return isLoopInvariant(Op, NestedLoop);
3438         });
3439 
3440         if (AllInvariant) {
3441           // Ok, both add recurrences are valid after the transformation.
3442           //
3443           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3444           // the outer recurrence has the same property.
3445           SCEV::NoWrapFlags InnerFlags =
3446             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3447           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3448         }
3449       }
3450       // Reset Operands to its original state.
3451       Operands[0] = NestedAR;
3452     }
3453   }
3454 
3455   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3456   // already have one, otherwise create a new one.
3457   return getOrCreateAddRecExpr(Operands, L, Flags);
3458 }
3459 
3460 const SCEV *
3461 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3462                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3463   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3464   // getSCEV(Base)->getType() has the same address space as Base->getType()
3465   // because SCEV::getType() preserves the address space.
3466   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3467   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3468   // instruction to its SCEV, because the Instruction may be guarded by control
3469   // flow and the no-overflow bits may not be valid for the expression in any
3470   // context. This can be fixed similarly to how these flags are handled for
3471   // adds.
3472   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3473                                              : SCEV::FlagAnyWrap;
3474 
3475   const SCEV *TotalOffset = getZero(IntPtrTy);
3476   // The array size is unimportant. The first thing we do on CurTy is getting
3477   // its element type.
3478   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3479   for (const SCEV *IndexExpr : IndexExprs) {
3480     // Compute the (potentially symbolic) offset in bytes for this index.
3481     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3482       // For a struct, add the member offset.
3483       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3484       unsigned FieldNo = Index->getZExtValue();
3485       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3486 
3487       // Add the field offset to the running total offset.
3488       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3489 
3490       // Update CurTy to the type of the field at Index.
3491       CurTy = STy->getTypeAtIndex(Index);
3492     } else {
3493       // Update CurTy to its element type.
3494       CurTy = cast<SequentialType>(CurTy)->getElementType();
3495       // For an array, add the element offset, explicitly scaled.
3496       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3497       // Getelementptr indices are signed.
3498       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3499 
3500       // Multiply the index by the element size to compute the element offset.
3501       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3502 
3503       // Add the element offset to the running total offset.
3504       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3505     }
3506   }
3507 
3508   // Add the total offset from all the GEP indices to the base.
3509   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3510 }
3511 
3512 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3513                                          const SCEV *RHS) {
3514   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3515   return getSMaxExpr(Ops);
3516 }
3517 
3518 const SCEV *
3519 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3520   assert(!Ops.empty() && "Cannot get empty smax!");
3521   if (Ops.size() == 1) return Ops[0];
3522 #ifndef NDEBUG
3523   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3524   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3525     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3526            "SCEVSMaxExpr operand types don't match!");
3527 #endif
3528 
3529   // Sort by complexity, this groups all similar expression types together.
3530   GroupByComplexity(Ops, &LI, DT);
3531 
3532   // If there are any constants, fold them together.
3533   unsigned Idx = 0;
3534   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3535     ++Idx;
3536     assert(Idx < Ops.size());
3537     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3538       // We found two constants, fold them together!
3539       ConstantInt *Fold = ConstantInt::get(
3540           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3541       Ops[0] = getConstant(Fold);
3542       Ops.erase(Ops.begin()+1);  // Erase the folded element
3543       if (Ops.size() == 1) return Ops[0];
3544       LHSC = cast<SCEVConstant>(Ops[0]);
3545     }
3546 
3547     // If we are left with a constant minimum-int, strip it off.
3548     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3549       Ops.erase(Ops.begin());
3550       --Idx;
3551     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3552       // If we have an smax with a constant maximum-int, it will always be
3553       // maximum-int.
3554       return Ops[0];
3555     }
3556 
3557     if (Ops.size() == 1) return Ops[0];
3558   }
3559 
3560   // Find the first SMax
3561   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3562     ++Idx;
3563 
3564   // Check to see if one of the operands is an SMax. If so, expand its operands
3565   // onto our operand list, and recurse to simplify.
3566   if (Idx < Ops.size()) {
3567     bool DeletedSMax = false;
3568     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3569       Ops.erase(Ops.begin()+Idx);
3570       Ops.append(SMax->op_begin(), SMax->op_end());
3571       DeletedSMax = true;
3572     }
3573 
3574     if (DeletedSMax)
3575       return getSMaxExpr(Ops);
3576   }
3577 
3578   // Okay, check to see if the same value occurs in the operand list twice.  If
3579   // so, delete one.  Since we sorted the list, these values are required to
3580   // be adjacent.
3581   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3582     //  X smax Y smax Y  -->  X smax Y
3583     //  X smax Y         -->  X, if X is always greater than Y
3584     if (Ops[i] == Ops[i+1] ||
3585         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3586       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3587       --i; --e;
3588     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3589       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3590       --i; --e;
3591     }
3592 
3593   if (Ops.size() == 1) return Ops[0];
3594 
3595   assert(!Ops.empty() && "Reduced smax down to nothing!");
3596 
3597   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3598   // already have one, otherwise create a new one.
3599   FoldingSetNodeID ID;
3600   ID.AddInteger(scSMaxExpr);
3601   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3602     ID.AddPointer(Ops[i]);
3603   void *IP = nullptr;
3604   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3605   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3606   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3607   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3608                                              O, Ops.size());
3609   UniqueSCEVs.InsertNode(S, IP);
3610   addToLoopUseLists(S);
3611   return S;
3612 }
3613 
3614 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3615                                          const SCEV *RHS) {
3616   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3617   return getUMaxExpr(Ops);
3618 }
3619 
3620 const SCEV *
3621 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3622   assert(!Ops.empty() && "Cannot get empty umax!");
3623   if (Ops.size() == 1) return Ops[0];
3624 #ifndef NDEBUG
3625   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3626   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3627     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3628            "SCEVUMaxExpr operand types don't match!");
3629 #endif
3630 
3631   // Sort by complexity, this groups all similar expression types together.
3632   GroupByComplexity(Ops, &LI, DT);
3633 
3634   // If there are any constants, fold them together.
3635   unsigned Idx = 0;
3636   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3637     ++Idx;
3638     assert(Idx < Ops.size());
3639     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3640       // We found two constants, fold them together!
3641       ConstantInt *Fold = ConstantInt::get(
3642           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3643       Ops[0] = getConstant(Fold);
3644       Ops.erase(Ops.begin()+1);  // Erase the folded element
3645       if (Ops.size() == 1) return Ops[0];
3646       LHSC = cast<SCEVConstant>(Ops[0]);
3647     }
3648 
3649     // If we are left with a constant minimum-int, strip it off.
3650     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3651       Ops.erase(Ops.begin());
3652       --Idx;
3653     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3654       // If we have an umax with a constant maximum-int, it will always be
3655       // maximum-int.
3656       return Ops[0];
3657     }
3658 
3659     if (Ops.size() == 1) return Ops[0];
3660   }
3661 
3662   // Find the first UMax
3663   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3664     ++Idx;
3665 
3666   // Check to see if one of the operands is a UMax. If so, expand its operands
3667   // onto our operand list, and recurse to simplify.
3668   if (Idx < Ops.size()) {
3669     bool DeletedUMax = false;
3670     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3671       Ops.erase(Ops.begin()+Idx);
3672       Ops.append(UMax->op_begin(), UMax->op_end());
3673       DeletedUMax = true;
3674     }
3675 
3676     if (DeletedUMax)
3677       return getUMaxExpr(Ops);
3678   }
3679 
3680   // Okay, check to see if the same value occurs in the operand list twice.  If
3681   // so, delete one.  Since we sorted the list, these values are required to
3682   // be adjacent.
3683   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3684     //  X umax Y umax Y  -->  X umax Y
3685     //  X umax Y         -->  X, if X is always greater than Y
3686     if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
3687                                     ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
3688       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3689       --i; --e;
3690     } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
3691                                                Ops[i + 1])) {
3692       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3693       --i; --e;
3694     }
3695 
3696   if (Ops.size() == 1) return Ops[0];
3697 
3698   assert(!Ops.empty() && "Reduced umax down to nothing!");
3699 
3700   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3701   // already have one, otherwise create a new one.
3702   FoldingSetNodeID ID;
3703   ID.AddInteger(scUMaxExpr);
3704   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3705     ID.AddPointer(Ops[i]);
3706   void *IP = nullptr;
3707   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3708   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3709   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3710   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3711                                              O, Ops.size());
3712   UniqueSCEVs.InsertNode(S, IP);
3713   addToLoopUseLists(S);
3714   return S;
3715 }
3716 
3717 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3718                                          const SCEV *RHS) {
3719   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3720   return getSMinExpr(Ops);
3721 }
3722 
3723 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3724   // ~smax(~x, ~y, ~z) == smin(x, y, z).
3725   SmallVector<const SCEV *, 2> NotOps;
3726   for (auto *S : Ops)
3727     NotOps.push_back(getNotSCEV(S));
3728   return getNotSCEV(getSMaxExpr(NotOps));
3729 }
3730 
3731 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3732                                          const SCEV *RHS) {
3733   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3734   return getUMinExpr(Ops);
3735 }
3736 
3737 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3738   assert(!Ops.empty() && "At least one operand must be!");
3739   // Trivial case.
3740   if (Ops.size() == 1)
3741     return Ops[0];
3742 
3743   // ~umax(~x, ~y, ~z) == umin(x, y, z).
3744   SmallVector<const SCEV *, 2> NotOps;
3745   for (auto *S : Ops)
3746     NotOps.push_back(getNotSCEV(S));
3747   return getNotSCEV(getUMaxExpr(NotOps));
3748 }
3749 
3750 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3751   // We can bypass creating a target-independent
3752   // constant expression and then folding it back into a ConstantInt.
3753   // This is just a compile-time optimization.
3754   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3755 }
3756 
3757 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3758                                              StructType *STy,
3759                                              unsigned FieldNo) {
3760   // We can bypass creating a target-independent
3761   // constant expression and then folding it back into a ConstantInt.
3762   // This is just a compile-time optimization.
3763   return getConstant(
3764       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3765 }
3766 
3767 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3768   // Don't attempt to do anything other than create a SCEVUnknown object
3769   // here.  createSCEV only calls getUnknown after checking for all other
3770   // interesting possibilities, and any other code that calls getUnknown
3771   // is doing so in order to hide a value from SCEV canonicalization.
3772 
3773   FoldingSetNodeID ID;
3774   ID.AddInteger(scUnknown);
3775   ID.AddPointer(V);
3776   void *IP = nullptr;
3777   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3778     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3779            "Stale SCEVUnknown in uniquing map!");
3780     return S;
3781   }
3782   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3783                                             FirstUnknown);
3784   FirstUnknown = cast<SCEVUnknown>(S);
3785   UniqueSCEVs.InsertNode(S, IP);
3786   return S;
3787 }
3788 
3789 //===----------------------------------------------------------------------===//
3790 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3791 //
3792 
3793 /// Test if values of the given type are analyzable within the SCEV
3794 /// framework. This primarily includes integer types, and it can optionally
3795 /// include pointer types if the ScalarEvolution class has access to
3796 /// target-specific information.
3797 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3798   // Integers and pointers are always SCEVable.
3799   return Ty->isIntOrPtrTy();
3800 }
3801 
3802 /// Return the size in bits of the specified type, for which isSCEVable must
3803 /// return true.
3804 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3805   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3806   if (Ty->isPointerTy())
3807     return getDataLayout().getIndexTypeSizeInBits(Ty);
3808   return getDataLayout().getTypeSizeInBits(Ty);
3809 }
3810 
3811 /// Return a type with the same bitwidth as the given type and which represents
3812 /// how SCEV will treat the given type, for which isSCEVable must return
3813 /// true. For pointer types, this is the pointer-sized integer type.
3814 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3815   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3816 
3817   if (Ty->isIntegerTy())
3818     return Ty;
3819 
3820   // The only other support type is pointer.
3821   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3822   return getDataLayout().getIntPtrType(Ty);
3823 }
3824 
3825 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3826   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3827 }
3828 
3829 const SCEV *ScalarEvolution::getCouldNotCompute() {
3830   return CouldNotCompute.get();
3831 }
3832 
3833 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3834   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3835     auto *SU = dyn_cast<SCEVUnknown>(S);
3836     return SU && SU->getValue() == nullptr;
3837   });
3838 
3839   return !ContainsNulls;
3840 }
3841 
3842 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3843   HasRecMapType::iterator I = HasRecMap.find(S);
3844   if (I != HasRecMap.end())
3845     return I->second;
3846 
3847   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3848   HasRecMap.insert({S, FoundAddRec});
3849   return FoundAddRec;
3850 }
3851 
3852 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3853 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3854 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3855 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3856   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3857   if (!Add)
3858     return {S, nullptr};
3859 
3860   if (Add->getNumOperands() != 2)
3861     return {S, nullptr};
3862 
3863   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3864   if (!ConstOp)
3865     return {S, nullptr};
3866 
3867   return {Add->getOperand(1), ConstOp->getValue()};
3868 }
3869 
3870 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3871 /// by the value and offset from any ValueOffsetPair in the set.
3872 SetVector<ScalarEvolution::ValueOffsetPair> *
3873 ScalarEvolution::getSCEVValues(const SCEV *S) {
3874   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3875   if (SI == ExprValueMap.end())
3876     return nullptr;
3877 #ifndef NDEBUG
3878   if (VerifySCEVMap) {
3879     // Check there is no dangling Value in the set returned.
3880     for (const auto &VE : SI->second)
3881       assert(ValueExprMap.count(VE.first));
3882   }
3883 #endif
3884   return &SI->second;
3885 }
3886 
3887 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3888 /// cannot be used separately. eraseValueFromMap should be used to remove
3889 /// V from ValueExprMap and ExprValueMap at the same time.
3890 void ScalarEvolution::eraseValueFromMap(Value *V) {
3891   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3892   if (I != ValueExprMap.end()) {
3893     const SCEV *S = I->second;
3894     // Remove {V, 0} from the set of ExprValueMap[S]
3895     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3896       SV->remove({V, nullptr});
3897 
3898     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3899     const SCEV *Stripped;
3900     ConstantInt *Offset;
3901     std::tie(Stripped, Offset) = splitAddExpr(S);
3902     if (Offset != nullptr) {
3903       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3904         SV->remove({V, Offset});
3905     }
3906     ValueExprMap.erase(V);
3907   }
3908 }
3909 
3910 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3911 /// TODO: In reality it is better to check the poison recursively
3912 /// but this is better than nothing.
3913 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3914   if (auto *I = dyn_cast<Instruction>(V)) {
3915     if (isa<OverflowingBinaryOperator>(I)) {
3916       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3917         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3918           return true;
3919         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3920           return true;
3921       }
3922     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3923       return true;
3924   }
3925   return false;
3926 }
3927 
3928 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3929 /// create a new one.
3930 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3931   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3932 
3933   const SCEV *S = getExistingSCEV(V);
3934   if (S == nullptr) {
3935     S = createSCEV(V);
3936     // During PHI resolution, it is possible to create two SCEVs for the same
3937     // V, so it is needed to double check whether V->S is inserted into
3938     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3939     std::pair<ValueExprMapType::iterator, bool> Pair =
3940         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3941     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3942       ExprValueMap[S].insert({V, nullptr});
3943 
3944       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3945       // ExprValueMap.
3946       const SCEV *Stripped = S;
3947       ConstantInt *Offset = nullptr;
3948       std::tie(Stripped, Offset) = splitAddExpr(S);
3949       // If stripped is SCEVUnknown, don't bother to save
3950       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3951       // increase the complexity of the expansion code.
3952       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3953       // because it may generate add/sub instead of GEP in SCEV expansion.
3954       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3955           !isa<GetElementPtrInst>(V))
3956         ExprValueMap[Stripped].insert({V, Offset});
3957     }
3958   }
3959   return S;
3960 }
3961 
3962 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3963   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3964 
3965   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3966   if (I != ValueExprMap.end()) {
3967     const SCEV *S = I->second;
3968     if (checkValidity(S))
3969       return S;
3970     eraseValueFromMap(V);
3971     forgetMemoizedResults(S);
3972   }
3973   return nullptr;
3974 }
3975 
3976 /// Return a SCEV corresponding to -V = -1*V
3977 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3978                                              SCEV::NoWrapFlags Flags) {
3979   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3980     return getConstant(
3981                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3982 
3983   Type *Ty = V->getType();
3984   Ty = getEffectiveSCEVType(Ty);
3985   return getMulExpr(
3986       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3987 }
3988 
3989 /// Return a SCEV corresponding to ~V = -1-V
3990 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3991   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3992     return getConstant(
3993                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3994 
3995   Type *Ty = V->getType();
3996   Ty = getEffectiveSCEVType(Ty);
3997   const SCEV *AllOnes =
3998                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3999   return getMinusSCEV(AllOnes, V);
4000 }
4001 
4002 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4003                                           SCEV::NoWrapFlags Flags,
4004                                           unsigned Depth) {
4005   // Fast path: X - X --> 0.
4006   if (LHS == RHS)
4007     return getZero(LHS->getType());
4008 
4009   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4010   // makes it so that we cannot make much use of NUW.
4011   auto AddFlags = SCEV::FlagAnyWrap;
4012   const bool RHSIsNotMinSigned =
4013       !getSignedRangeMin(RHS).isMinSignedValue();
4014   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4015     // Let M be the minimum representable signed value. Then (-1)*RHS
4016     // signed-wraps if and only if RHS is M. That can happen even for
4017     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4018     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4019     // (-1)*RHS, we need to prove that RHS != M.
4020     //
4021     // If LHS is non-negative and we know that LHS - RHS does not
4022     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4023     // either by proving that RHS > M or that LHS >= 0.
4024     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4025       AddFlags = SCEV::FlagNSW;
4026     }
4027   }
4028 
4029   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4030   // RHS is NSW and LHS >= 0.
4031   //
4032   // The difficulty here is that the NSW flag may have been proven
4033   // relative to a loop that is to be found in a recurrence in LHS and
4034   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4035   // larger scope than intended.
4036   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4037 
4038   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4039 }
4040 
4041 const SCEV *
4042 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
4043   Type *SrcTy = V->getType();
4044   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4045          "Cannot truncate or zero extend with non-integer arguments!");
4046   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4047     return V;  // No conversion
4048   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4049     return getTruncateExpr(V, Ty);
4050   return getZeroExtendExpr(V, Ty);
4051 }
4052 
4053 const SCEV *
4054 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
4055                                          Type *Ty) {
4056   Type *SrcTy = V->getType();
4057   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4058          "Cannot truncate or zero extend with non-integer arguments!");
4059   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4060     return V;  // No conversion
4061   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4062     return getTruncateExpr(V, Ty);
4063   return getSignExtendExpr(V, Ty);
4064 }
4065 
4066 const SCEV *
4067 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4068   Type *SrcTy = V->getType();
4069   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4070          "Cannot noop or zero extend with non-integer arguments!");
4071   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4072          "getNoopOrZeroExtend cannot truncate!");
4073   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4074     return V;  // No conversion
4075   return getZeroExtendExpr(V, Ty);
4076 }
4077 
4078 const SCEV *
4079 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4080   Type *SrcTy = V->getType();
4081   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4082          "Cannot noop or sign extend with non-integer arguments!");
4083   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4084          "getNoopOrSignExtend cannot truncate!");
4085   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4086     return V;  // No conversion
4087   return getSignExtendExpr(V, Ty);
4088 }
4089 
4090 const SCEV *
4091 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4092   Type *SrcTy = V->getType();
4093   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4094          "Cannot noop or any extend with non-integer arguments!");
4095   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4096          "getNoopOrAnyExtend cannot truncate!");
4097   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4098     return V;  // No conversion
4099   return getAnyExtendExpr(V, Ty);
4100 }
4101 
4102 const SCEV *
4103 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4104   Type *SrcTy = V->getType();
4105   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4106          "Cannot truncate or noop with non-integer arguments!");
4107   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4108          "getTruncateOrNoop cannot extend!");
4109   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4110     return V;  // No conversion
4111   return getTruncateExpr(V, Ty);
4112 }
4113 
4114 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4115                                                         const SCEV *RHS) {
4116   const SCEV *PromotedLHS = LHS;
4117   const SCEV *PromotedRHS = RHS;
4118 
4119   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4120     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4121   else
4122     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4123 
4124   return getUMaxExpr(PromotedLHS, PromotedRHS);
4125 }
4126 
4127 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4128                                                         const SCEV *RHS) {
4129   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4130   return getUMinFromMismatchedTypes(Ops);
4131 }
4132 
4133 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4134     SmallVectorImpl<const SCEV *> &Ops) {
4135   assert(!Ops.empty() && "At least one operand must be!");
4136   // Trivial case.
4137   if (Ops.size() == 1)
4138     return Ops[0];
4139 
4140   // Find the max type first.
4141   Type *MaxType = nullptr;
4142   for (auto *S : Ops)
4143     if (MaxType)
4144       MaxType = getWiderType(MaxType, S->getType());
4145     else
4146       MaxType = S->getType();
4147 
4148   // Extend all ops to max type.
4149   SmallVector<const SCEV *, 2> PromotedOps;
4150   for (auto *S : Ops)
4151     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4152 
4153   // Generate umin.
4154   return getUMinExpr(PromotedOps);
4155 }
4156 
4157 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4158   // A pointer operand may evaluate to a nonpointer expression, such as null.
4159   if (!V->getType()->isPointerTy())
4160     return V;
4161 
4162   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4163     return getPointerBase(Cast->getOperand());
4164   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4165     const SCEV *PtrOp = nullptr;
4166     for (const SCEV *NAryOp : NAry->operands()) {
4167       if (NAryOp->getType()->isPointerTy()) {
4168         // Cannot find the base of an expression with multiple pointer operands.
4169         if (PtrOp)
4170           return V;
4171         PtrOp = NAryOp;
4172       }
4173     }
4174     if (!PtrOp)
4175       return V;
4176     return getPointerBase(PtrOp);
4177   }
4178   return V;
4179 }
4180 
4181 /// Push users of the given Instruction onto the given Worklist.
4182 static void
4183 PushDefUseChildren(Instruction *I,
4184                    SmallVectorImpl<Instruction *> &Worklist) {
4185   // Push the def-use children onto the Worklist stack.
4186   for (User *U : I->users())
4187     Worklist.push_back(cast<Instruction>(U));
4188 }
4189 
4190 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4191   SmallVector<Instruction *, 16> Worklist;
4192   PushDefUseChildren(PN, Worklist);
4193 
4194   SmallPtrSet<Instruction *, 8> Visited;
4195   Visited.insert(PN);
4196   while (!Worklist.empty()) {
4197     Instruction *I = Worklist.pop_back_val();
4198     if (!Visited.insert(I).second)
4199       continue;
4200 
4201     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4202     if (It != ValueExprMap.end()) {
4203       const SCEV *Old = It->second;
4204 
4205       // Short-circuit the def-use traversal if the symbolic name
4206       // ceases to appear in expressions.
4207       if (Old != SymName && !hasOperand(Old, SymName))
4208         continue;
4209 
4210       // SCEVUnknown for a PHI either means that it has an unrecognized
4211       // structure, it's a PHI that's in the progress of being computed
4212       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4213       // additional loop trip count information isn't going to change anything.
4214       // In the second case, createNodeForPHI will perform the necessary
4215       // updates on its own when it gets to that point. In the third, we do
4216       // want to forget the SCEVUnknown.
4217       if (!isa<PHINode>(I) ||
4218           !isa<SCEVUnknown>(Old) ||
4219           (I != PN && Old == SymName)) {
4220         eraseValueFromMap(It->first);
4221         forgetMemoizedResults(Old);
4222       }
4223     }
4224 
4225     PushDefUseChildren(I, Worklist);
4226   }
4227 }
4228 
4229 namespace {
4230 
4231 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4232 /// expression in case its Loop is L. If it is not L then
4233 /// if IgnoreOtherLoops is true then use AddRec itself
4234 /// otherwise rewrite cannot be done.
4235 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4236 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4237 public:
4238   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4239                              bool IgnoreOtherLoops = true) {
4240     SCEVInitRewriter Rewriter(L, SE);
4241     const SCEV *Result = Rewriter.visit(S);
4242     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4243       return SE.getCouldNotCompute();
4244     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4245                ? SE.getCouldNotCompute()
4246                : Result;
4247   }
4248 
4249   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4250     if (!SE.isLoopInvariant(Expr, L))
4251       SeenLoopVariantSCEVUnknown = true;
4252     return Expr;
4253   }
4254 
4255   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4256     // Only re-write AddRecExprs for this loop.
4257     if (Expr->getLoop() == L)
4258       return Expr->getStart();
4259     SeenOtherLoops = true;
4260     return Expr;
4261   }
4262 
4263   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4264 
4265   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4266 
4267 private:
4268   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4269       : SCEVRewriteVisitor(SE), L(L) {}
4270 
4271   const Loop *L;
4272   bool SeenLoopVariantSCEVUnknown = false;
4273   bool SeenOtherLoops = false;
4274 };
4275 
4276 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4277 /// increment expression in case its Loop is L. If it is not L then
4278 /// use AddRec itself.
4279 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4280 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4281 public:
4282   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4283     SCEVPostIncRewriter Rewriter(L, SE);
4284     const SCEV *Result = Rewriter.visit(S);
4285     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4286         ? SE.getCouldNotCompute()
4287         : Result;
4288   }
4289 
4290   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4291     if (!SE.isLoopInvariant(Expr, L))
4292       SeenLoopVariantSCEVUnknown = true;
4293     return Expr;
4294   }
4295 
4296   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4297     // Only re-write AddRecExprs for this loop.
4298     if (Expr->getLoop() == L)
4299       return Expr->getPostIncExpr(SE);
4300     SeenOtherLoops = true;
4301     return Expr;
4302   }
4303 
4304   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4305 
4306   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4307 
4308 private:
4309   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4310       : SCEVRewriteVisitor(SE), L(L) {}
4311 
4312   const Loop *L;
4313   bool SeenLoopVariantSCEVUnknown = false;
4314   bool SeenOtherLoops = false;
4315 };
4316 
4317 /// This class evaluates the compare condition by matching it against the
4318 /// condition of loop latch. If there is a match we assume a true value
4319 /// for the condition while building SCEV nodes.
4320 class SCEVBackedgeConditionFolder
4321     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4322 public:
4323   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4324                              ScalarEvolution &SE) {
4325     bool IsPosBECond = false;
4326     Value *BECond = nullptr;
4327     if (BasicBlock *Latch = L->getLoopLatch()) {
4328       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4329       if (BI && BI->isConditional()) {
4330         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4331                "Both outgoing branches should not target same header!");
4332         BECond = BI->getCondition();
4333         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4334       } else {
4335         return S;
4336       }
4337     }
4338     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4339     return Rewriter.visit(S);
4340   }
4341 
4342   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4343     const SCEV *Result = Expr;
4344     bool InvariantF = SE.isLoopInvariant(Expr, L);
4345 
4346     if (!InvariantF) {
4347       Instruction *I = cast<Instruction>(Expr->getValue());
4348       switch (I->getOpcode()) {
4349       case Instruction::Select: {
4350         SelectInst *SI = cast<SelectInst>(I);
4351         Optional<const SCEV *> Res =
4352             compareWithBackedgeCondition(SI->getCondition());
4353         if (Res.hasValue()) {
4354           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4355           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4356         }
4357         break;
4358       }
4359       default: {
4360         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4361         if (Res.hasValue())
4362           Result = Res.getValue();
4363         break;
4364       }
4365       }
4366     }
4367     return Result;
4368   }
4369 
4370 private:
4371   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4372                                        bool IsPosBECond, ScalarEvolution &SE)
4373       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4374         IsPositiveBECond(IsPosBECond) {}
4375 
4376   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4377 
4378   const Loop *L;
4379   /// Loop back condition.
4380   Value *BackedgeCond = nullptr;
4381   /// Set to true if loop back is on positive branch condition.
4382   bool IsPositiveBECond;
4383 };
4384 
4385 Optional<const SCEV *>
4386 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4387 
4388   // If value matches the backedge condition for loop latch,
4389   // then return a constant evolution node based on loopback
4390   // branch taken.
4391   if (BackedgeCond == IC)
4392     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4393                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4394   return None;
4395 }
4396 
4397 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4398 public:
4399   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4400                              ScalarEvolution &SE) {
4401     SCEVShiftRewriter Rewriter(L, SE);
4402     const SCEV *Result = Rewriter.visit(S);
4403     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4404   }
4405 
4406   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4407     // Only allow AddRecExprs for this loop.
4408     if (!SE.isLoopInvariant(Expr, L))
4409       Valid = false;
4410     return Expr;
4411   }
4412 
4413   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4414     if (Expr->getLoop() == L && Expr->isAffine())
4415       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4416     Valid = false;
4417     return Expr;
4418   }
4419 
4420   bool isValid() { return Valid; }
4421 
4422 private:
4423   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4424       : SCEVRewriteVisitor(SE), L(L) {}
4425 
4426   const Loop *L;
4427   bool Valid = true;
4428 };
4429 
4430 } // end anonymous namespace
4431 
4432 SCEV::NoWrapFlags
4433 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4434   if (!AR->isAffine())
4435     return SCEV::FlagAnyWrap;
4436 
4437   using OBO = OverflowingBinaryOperator;
4438 
4439   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4440 
4441   if (!AR->hasNoSignedWrap()) {
4442     ConstantRange AddRecRange = getSignedRange(AR);
4443     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4444 
4445     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4446         Instruction::Add, IncRange, OBO::NoSignedWrap);
4447     if (NSWRegion.contains(AddRecRange))
4448       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4449   }
4450 
4451   if (!AR->hasNoUnsignedWrap()) {
4452     ConstantRange AddRecRange = getUnsignedRange(AR);
4453     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4454 
4455     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4456         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4457     if (NUWRegion.contains(AddRecRange))
4458       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4459   }
4460 
4461   return Result;
4462 }
4463 
4464 namespace {
4465 
4466 /// Represents an abstract binary operation.  This may exist as a
4467 /// normal instruction or constant expression, or may have been
4468 /// derived from an expression tree.
4469 struct BinaryOp {
4470   unsigned Opcode;
4471   Value *LHS;
4472   Value *RHS;
4473   bool IsNSW = false;
4474   bool IsNUW = false;
4475 
4476   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4477   /// constant expression.
4478   Operator *Op = nullptr;
4479 
4480   explicit BinaryOp(Operator *Op)
4481       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4482         Op(Op) {
4483     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4484       IsNSW = OBO->hasNoSignedWrap();
4485       IsNUW = OBO->hasNoUnsignedWrap();
4486     }
4487   }
4488 
4489   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4490                     bool IsNUW = false)
4491       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4492 };
4493 
4494 } // end anonymous namespace
4495 
4496 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4497 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4498   auto *Op = dyn_cast<Operator>(V);
4499   if (!Op)
4500     return None;
4501 
4502   // Implementation detail: all the cleverness here should happen without
4503   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4504   // SCEV expressions when possible, and we should not break that.
4505 
4506   switch (Op->getOpcode()) {
4507   case Instruction::Add:
4508   case Instruction::Sub:
4509   case Instruction::Mul:
4510   case Instruction::UDiv:
4511   case Instruction::URem:
4512   case Instruction::And:
4513   case Instruction::Or:
4514   case Instruction::AShr:
4515   case Instruction::Shl:
4516     return BinaryOp(Op);
4517 
4518   case Instruction::Xor:
4519     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4520       // If the RHS of the xor is a signmask, then this is just an add.
4521       // Instcombine turns add of signmask into xor as a strength reduction step.
4522       if (RHSC->getValue().isSignMask())
4523         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4524     return BinaryOp(Op);
4525 
4526   case Instruction::LShr:
4527     // Turn logical shift right of a constant into a unsigned divide.
4528     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4529       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4530 
4531       // If the shift count is not less than the bitwidth, the result of
4532       // the shift is undefined. Don't try to analyze it, because the
4533       // resolution chosen here may differ from the resolution chosen in
4534       // other parts of the compiler.
4535       if (SA->getValue().ult(BitWidth)) {
4536         Constant *X =
4537             ConstantInt::get(SA->getContext(),
4538                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4539         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4540       }
4541     }
4542     return BinaryOp(Op);
4543 
4544   case Instruction::ExtractValue: {
4545     auto *EVI = cast<ExtractValueInst>(Op);
4546     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4547       break;
4548 
4549     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4550     if (!CI)
4551       break;
4552 
4553     if (auto *F = CI->getCalledFunction())
4554       switch (F->getIntrinsicID()) {
4555       case Intrinsic::sadd_with_overflow:
4556       case Intrinsic::uadd_with_overflow:
4557         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4558           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4559                           CI->getArgOperand(1));
4560 
4561         // Now that we know that all uses of the arithmetic-result component of
4562         // CI are guarded by the overflow check, we can go ahead and pretend
4563         // that the arithmetic is non-overflowing.
4564         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4565           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4566                           CI->getArgOperand(1), /* IsNSW = */ true,
4567                           /* IsNUW = */ false);
4568         else
4569           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4570                           CI->getArgOperand(1), /* IsNSW = */ false,
4571                           /* IsNUW*/ true);
4572       case Intrinsic::ssub_with_overflow:
4573       case Intrinsic::usub_with_overflow:
4574         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4575           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4576                           CI->getArgOperand(1));
4577 
4578         // The same reasoning as sadd/uadd above.
4579         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4580           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4581                           CI->getArgOperand(1), /* IsNSW = */ true,
4582                           /* IsNUW = */ false);
4583         else
4584           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4585                           CI->getArgOperand(1), /* IsNSW = */ false,
4586                           /* IsNUW = */ true);
4587       case Intrinsic::smul_with_overflow:
4588       case Intrinsic::umul_with_overflow:
4589         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4590                         CI->getArgOperand(1));
4591       default:
4592         break;
4593       }
4594     break;
4595   }
4596 
4597   default:
4598     break;
4599   }
4600 
4601   return None;
4602 }
4603 
4604 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4605 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4606 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4607 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4608 /// follows one of the following patterns:
4609 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4610 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4611 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4612 /// we return the type of the truncation operation, and indicate whether the
4613 /// truncated type should be treated as signed/unsigned by setting
4614 /// \p Signed to true/false, respectively.
4615 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4616                                bool &Signed, ScalarEvolution &SE) {
4617   // The case where Op == SymbolicPHI (that is, with no type conversions on
4618   // the way) is handled by the regular add recurrence creating logic and
4619   // would have already been triggered in createAddRecForPHI. Reaching it here
4620   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4621   // because one of the other operands of the SCEVAddExpr updating this PHI is
4622   // not invariant).
4623   //
4624   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4625   // this case predicates that allow us to prove that Op == SymbolicPHI will
4626   // be added.
4627   if (Op == SymbolicPHI)
4628     return nullptr;
4629 
4630   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4631   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4632   if (SourceBits != NewBits)
4633     return nullptr;
4634 
4635   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4636   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4637   if (!SExt && !ZExt)
4638     return nullptr;
4639   const SCEVTruncateExpr *Trunc =
4640       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4641            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4642   if (!Trunc)
4643     return nullptr;
4644   const SCEV *X = Trunc->getOperand();
4645   if (X != SymbolicPHI)
4646     return nullptr;
4647   Signed = SExt != nullptr;
4648   return Trunc->getType();
4649 }
4650 
4651 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4652   if (!PN->getType()->isIntegerTy())
4653     return nullptr;
4654   const Loop *L = LI.getLoopFor(PN->getParent());
4655   if (!L || L->getHeader() != PN->getParent())
4656     return nullptr;
4657   return L;
4658 }
4659 
4660 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4661 // computation that updates the phi follows the following pattern:
4662 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4663 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4664 // If so, try to see if it can be rewritten as an AddRecExpr under some
4665 // Predicates. If successful, return them as a pair. Also cache the results
4666 // of the analysis.
4667 //
4668 // Example usage scenario:
4669 //    Say the Rewriter is called for the following SCEV:
4670 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4671 //    where:
4672 //         %X = phi i64 (%Start, %BEValue)
4673 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4674 //    and call this function with %SymbolicPHI = %X.
4675 //
4676 //    The analysis will find that the value coming around the backedge has
4677 //    the following SCEV:
4678 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4679 //    Upon concluding that this matches the desired pattern, the function
4680 //    will return the pair {NewAddRec, SmallPredsVec} where:
4681 //         NewAddRec = {%Start,+,%Step}
4682 //         SmallPredsVec = {P1, P2, P3} as follows:
4683 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4684 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4685 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4686 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4687 //    under the predicates {P1,P2,P3}.
4688 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4689 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4690 //
4691 // TODO's:
4692 //
4693 // 1) Extend the Induction descriptor to also support inductions that involve
4694 //    casts: When needed (namely, when we are called in the context of the
4695 //    vectorizer induction analysis), a Set of cast instructions will be
4696 //    populated by this method, and provided back to isInductionPHI. This is
4697 //    needed to allow the vectorizer to properly record them to be ignored by
4698 //    the cost model and to avoid vectorizing them (otherwise these casts,
4699 //    which are redundant under the runtime overflow checks, will be
4700 //    vectorized, which can be costly).
4701 //
4702 // 2) Support additional induction/PHISCEV patterns: We also want to support
4703 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4704 //    after the induction update operation (the induction increment):
4705 //
4706 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4707 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4708 //
4709 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4710 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4711 //
4712 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4713 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4714 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4715   SmallVector<const SCEVPredicate *, 3> Predicates;
4716 
4717   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4718   // return an AddRec expression under some predicate.
4719 
4720   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4721   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4722   assert(L && "Expecting an integer loop header phi");
4723 
4724   // The loop may have multiple entrances or multiple exits; we can analyze
4725   // this phi as an addrec if it has a unique entry value and a unique
4726   // backedge value.
4727   Value *BEValueV = nullptr, *StartValueV = nullptr;
4728   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4729     Value *V = PN->getIncomingValue(i);
4730     if (L->contains(PN->getIncomingBlock(i))) {
4731       if (!BEValueV) {
4732         BEValueV = V;
4733       } else if (BEValueV != V) {
4734         BEValueV = nullptr;
4735         break;
4736       }
4737     } else if (!StartValueV) {
4738       StartValueV = V;
4739     } else if (StartValueV != V) {
4740       StartValueV = nullptr;
4741       break;
4742     }
4743   }
4744   if (!BEValueV || !StartValueV)
4745     return None;
4746 
4747   const SCEV *BEValue = getSCEV(BEValueV);
4748 
4749   // If the value coming around the backedge is an add with the symbolic
4750   // value we just inserted, possibly with casts that we can ignore under
4751   // an appropriate runtime guard, then we found a simple induction variable!
4752   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4753   if (!Add)
4754     return None;
4755 
4756   // If there is a single occurrence of the symbolic value, possibly
4757   // casted, replace it with a recurrence.
4758   unsigned FoundIndex = Add->getNumOperands();
4759   Type *TruncTy = nullptr;
4760   bool Signed;
4761   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4762     if ((TruncTy =
4763              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4764       if (FoundIndex == e) {
4765         FoundIndex = i;
4766         break;
4767       }
4768 
4769   if (FoundIndex == Add->getNumOperands())
4770     return None;
4771 
4772   // Create an add with everything but the specified operand.
4773   SmallVector<const SCEV *, 8> Ops;
4774   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4775     if (i != FoundIndex)
4776       Ops.push_back(Add->getOperand(i));
4777   const SCEV *Accum = getAddExpr(Ops);
4778 
4779   // The runtime checks will not be valid if the step amount is
4780   // varying inside the loop.
4781   if (!isLoopInvariant(Accum, L))
4782     return None;
4783 
4784   // *** Part2: Create the predicates
4785 
4786   // Analysis was successful: we have a phi-with-cast pattern for which we
4787   // can return an AddRec expression under the following predicates:
4788   //
4789   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4790   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4791   // P2: An Equal predicate that guarantees that
4792   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4793   // P3: An Equal predicate that guarantees that
4794   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4795   //
4796   // As we next prove, the above predicates guarantee that:
4797   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4798   //
4799   //
4800   // More formally, we want to prove that:
4801   //     Expr(i+1) = Start + (i+1) * Accum
4802   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4803   //
4804   // Given that:
4805   // 1) Expr(0) = Start
4806   // 2) Expr(1) = Start + Accum
4807   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4808   // 3) Induction hypothesis (step i):
4809   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4810   //
4811   // Proof:
4812   //  Expr(i+1) =
4813   //   = Start + (i+1)*Accum
4814   //   = (Start + i*Accum) + Accum
4815   //   = Expr(i) + Accum
4816   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4817   //                                                             :: from step i
4818   //
4819   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4820   //
4821   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4822   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4823   //     + Accum                                                     :: from P3
4824   //
4825   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4826   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4827   //
4828   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4829   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4830   //
4831   // By induction, the same applies to all iterations 1<=i<n:
4832   //
4833 
4834   // Create a truncated addrec for which we will add a no overflow check (P1).
4835   const SCEV *StartVal = getSCEV(StartValueV);
4836   const SCEV *PHISCEV =
4837       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4838                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4839 
4840   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4841   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4842   // will be constant.
4843   //
4844   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4845   // add P1.
4846   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4847     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4848         Signed ? SCEVWrapPredicate::IncrementNSSW
4849                : SCEVWrapPredicate::IncrementNUSW;
4850     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4851     Predicates.push_back(AddRecPred);
4852   }
4853 
4854   // Create the Equal Predicates P2,P3:
4855 
4856   // It is possible that the predicates P2 and/or P3 are computable at
4857   // compile time due to StartVal and/or Accum being constants.
4858   // If either one is, then we can check that now and escape if either P2
4859   // or P3 is false.
4860 
4861   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4862   // for each of StartVal and Accum
4863   auto getExtendedExpr = [&](const SCEV *Expr,
4864                              bool CreateSignExtend) -> const SCEV * {
4865     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4866     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4867     const SCEV *ExtendedExpr =
4868         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4869                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4870     return ExtendedExpr;
4871   };
4872 
4873   // Given:
4874   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4875   //               = getExtendedExpr(Expr)
4876   // Determine whether the predicate P: Expr == ExtendedExpr
4877   // is known to be false at compile time
4878   auto PredIsKnownFalse = [&](const SCEV *Expr,
4879                               const SCEV *ExtendedExpr) -> bool {
4880     return Expr != ExtendedExpr &&
4881            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4882   };
4883 
4884   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4885   if (PredIsKnownFalse(StartVal, StartExtended)) {
4886     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4887     return None;
4888   }
4889 
4890   // The Step is always Signed (because the overflow checks are either
4891   // NSSW or NUSW)
4892   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4893   if (PredIsKnownFalse(Accum, AccumExtended)) {
4894     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4895     return None;
4896   }
4897 
4898   auto AppendPredicate = [&](const SCEV *Expr,
4899                              const SCEV *ExtendedExpr) -> void {
4900     if (Expr != ExtendedExpr &&
4901         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4902       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4903       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4904       Predicates.push_back(Pred);
4905     }
4906   };
4907 
4908   AppendPredicate(StartVal, StartExtended);
4909   AppendPredicate(Accum, AccumExtended);
4910 
4911   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4912   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4913   // into NewAR if it will also add the runtime overflow checks specified in
4914   // Predicates.
4915   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4916 
4917   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4918       std::make_pair(NewAR, Predicates);
4919   // Remember the result of the analysis for this SCEV at this locayyytion.
4920   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4921   return PredRewrite;
4922 }
4923 
4924 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4925 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4926   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4927   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4928   if (!L)
4929     return None;
4930 
4931   // Check to see if we already analyzed this PHI.
4932   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4933   if (I != PredicatedSCEVRewrites.end()) {
4934     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4935         I->second;
4936     // Analysis was done before and failed to create an AddRec:
4937     if (Rewrite.first == SymbolicPHI)
4938       return None;
4939     // Analysis was done before and succeeded to create an AddRec under
4940     // a predicate:
4941     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4942     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4943     return Rewrite;
4944   }
4945 
4946   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4947     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4948 
4949   // Record in the cache that the analysis failed
4950   if (!Rewrite) {
4951     SmallVector<const SCEVPredicate *, 3> Predicates;
4952     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4953     return None;
4954   }
4955 
4956   return Rewrite;
4957 }
4958 
4959 // FIXME: This utility is currently required because the Rewriter currently
4960 // does not rewrite this expression:
4961 // {0, +, (sext ix (trunc iy to ix) to iy)}
4962 // into {0, +, %step},
4963 // even when the following Equal predicate exists:
4964 // "%step == (sext ix (trunc iy to ix) to iy)".
4965 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4966     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4967   if (AR1 == AR2)
4968     return true;
4969 
4970   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4971     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4972         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4973       return false;
4974     return true;
4975   };
4976 
4977   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4978       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4979     return false;
4980   return true;
4981 }
4982 
4983 /// A helper function for createAddRecFromPHI to handle simple cases.
4984 ///
4985 /// This function tries to find an AddRec expression for the simplest (yet most
4986 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4987 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4988 /// technique for finding the AddRec expression.
4989 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4990                                                       Value *BEValueV,
4991                                                       Value *StartValueV) {
4992   const Loop *L = LI.getLoopFor(PN->getParent());
4993   assert(L && L->getHeader() == PN->getParent());
4994   assert(BEValueV && StartValueV);
4995 
4996   auto BO = MatchBinaryOp(BEValueV, DT);
4997   if (!BO)
4998     return nullptr;
4999 
5000   if (BO->Opcode != Instruction::Add)
5001     return nullptr;
5002 
5003   const SCEV *Accum = nullptr;
5004   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5005     Accum = getSCEV(BO->RHS);
5006   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5007     Accum = getSCEV(BO->LHS);
5008 
5009   if (!Accum)
5010     return nullptr;
5011 
5012   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5013   if (BO->IsNUW)
5014     Flags = setFlags(Flags, SCEV::FlagNUW);
5015   if (BO->IsNSW)
5016     Flags = setFlags(Flags, SCEV::FlagNSW);
5017 
5018   const SCEV *StartVal = getSCEV(StartValueV);
5019   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5020 
5021   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5022 
5023   // We can add Flags to the post-inc expression only if we
5024   // know that it is *undefined behavior* for BEValueV to
5025   // overflow.
5026   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5027     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5028       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5029 
5030   return PHISCEV;
5031 }
5032 
5033 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5034   const Loop *L = LI.getLoopFor(PN->getParent());
5035   if (!L || L->getHeader() != PN->getParent())
5036     return nullptr;
5037 
5038   // The loop may have multiple entrances or multiple exits; we can analyze
5039   // this phi as an addrec if it has a unique entry value and a unique
5040   // backedge value.
5041   Value *BEValueV = nullptr, *StartValueV = nullptr;
5042   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5043     Value *V = PN->getIncomingValue(i);
5044     if (L->contains(PN->getIncomingBlock(i))) {
5045       if (!BEValueV) {
5046         BEValueV = V;
5047       } else if (BEValueV != V) {
5048         BEValueV = nullptr;
5049         break;
5050       }
5051     } else if (!StartValueV) {
5052       StartValueV = V;
5053     } else if (StartValueV != V) {
5054       StartValueV = nullptr;
5055       break;
5056     }
5057   }
5058   if (!BEValueV || !StartValueV)
5059     return nullptr;
5060 
5061   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5062          "PHI node already processed?");
5063 
5064   // First, try to find AddRec expression without creating a fictituos symbolic
5065   // value for PN.
5066   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5067     return S;
5068 
5069   // Handle PHI node value symbolically.
5070   const SCEV *SymbolicName = getUnknown(PN);
5071   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5072 
5073   // Using this symbolic name for the PHI, analyze the value coming around
5074   // the back-edge.
5075   const SCEV *BEValue = getSCEV(BEValueV);
5076 
5077   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5078   // has a special value for the first iteration of the loop.
5079 
5080   // If the value coming around the backedge is an add with the symbolic
5081   // value we just inserted, then we found a simple induction variable!
5082   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5083     // If there is a single occurrence of the symbolic value, replace it
5084     // with a recurrence.
5085     unsigned FoundIndex = Add->getNumOperands();
5086     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5087       if (Add->getOperand(i) == SymbolicName)
5088         if (FoundIndex == e) {
5089           FoundIndex = i;
5090           break;
5091         }
5092 
5093     if (FoundIndex != Add->getNumOperands()) {
5094       // Create an add with everything but the specified operand.
5095       SmallVector<const SCEV *, 8> Ops;
5096       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5097         if (i != FoundIndex)
5098           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5099                                                              L, *this));
5100       const SCEV *Accum = getAddExpr(Ops);
5101 
5102       // This is not a valid addrec if the step amount is varying each
5103       // loop iteration, but is not itself an addrec in this loop.
5104       if (isLoopInvariant(Accum, L) ||
5105           (isa<SCEVAddRecExpr>(Accum) &&
5106            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5107         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5108 
5109         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5110           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5111             if (BO->IsNUW)
5112               Flags = setFlags(Flags, SCEV::FlagNUW);
5113             if (BO->IsNSW)
5114               Flags = setFlags(Flags, SCEV::FlagNSW);
5115           }
5116         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5117           // If the increment is an inbounds GEP, then we know the address
5118           // space cannot be wrapped around. We cannot make any guarantee
5119           // about signed or unsigned overflow because pointers are
5120           // unsigned but we may have a negative index from the base
5121           // pointer. We can guarantee that no unsigned wrap occurs if the
5122           // indices form a positive value.
5123           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5124             Flags = setFlags(Flags, SCEV::FlagNW);
5125 
5126             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5127             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5128               Flags = setFlags(Flags, SCEV::FlagNUW);
5129           }
5130 
5131           // We cannot transfer nuw and nsw flags from subtraction
5132           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5133           // for instance.
5134         }
5135 
5136         const SCEV *StartVal = getSCEV(StartValueV);
5137         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5138 
5139         // Okay, for the entire analysis of this edge we assumed the PHI
5140         // to be symbolic.  We now need to go back and purge all of the
5141         // entries for the scalars that use the symbolic expression.
5142         forgetSymbolicName(PN, SymbolicName);
5143         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5144 
5145         // We can add Flags to the post-inc expression only if we
5146         // know that it is *undefined behavior* for BEValueV to
5147         // overflow.
5148         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5149           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5150             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5151 
5152         return PHISCEV;
5153       }
5154     }
5155   } else {
5156     // Otherwise, this could be a loop like this:
5157     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5158     // In this case, j = {1,+,1}  and BEValue is j.
5159     // Because the other in-value of i (0) fits the evolution of BEValue
5160     // i really is an addrec evolution.
5161     //
5162     // We can generalize this saying that i is the shifted value of BEValue
5163     // by one iteration:
5164     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5165     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5166     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5167     if (Shifted != getCouldNotCompute() &&
5168         Start != getCouldNotCompute()) {
5169       const SCEV *StartVal = getSCEV(StartValueV);
5170       if (Start == StartVal) {
5171         // Okay, for the entire analysis of this edge we assumed the PHI
5172         // to be symbolic.  We now need to go back and purge all of the
5173         // entries for the scalars that use the symbolic expression.
5174         forgetSymbolicName(PN, SymbolicName);
5175         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5176         return Shifted;
5177       }
5178     }
5179   }
5180 
5181   // Remove the temporary PHI node SCEV that has been inserted while intending
5182   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5183   // as it will prevent later (possibly simpler) SCEV expressions to be added
5184   // to the ValueExprMap.
5185   eraseValueFromMap(PN);
5186 
5187   return nullptr;
5188 }
5189 
5190 // Checks if the SCEV S is available at BB.  S is considered available at BB
5191 // if S can be materialized at BB without introducing a fault.
5192 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5193                                BasicBlock *BB) {
5194   struct CheckAvailable {
5195     bool TraversalDone = false;
5196     bool Available = true;
5197 
5198     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5199     BasicBlock *BB = nullptr;
5200     DominatorTree &DT;
5201 
5202     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5203       : L(L), BB(BB), DT(DT) {}
5204 
5205     bool setUnavailable() {
5206       TraversalDone = true;
5207       Available = false;
5208       return false;
5209     }
5210 
5211     bool follow(const SCEV *S) {
5212       switch (S->getSCEVType()) {
5213       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5214       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5215         // These expressions are available if their operand(s) is/are.
5216         return true;
5217 
5218       case scAddRecExpr: {
5219         // We allow add recurrences that are on the loop BB is in, or some
5220         // outer loop.  This guarantees availability because the value of the
5221         // add recurrence at BB is simply the "current" value of the induction
5222         // variable.  We can relax this in the future; for instance an add
5223         // recurrence on a sibling dominating loop is also available at BB.
5224         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5225         if (L && (ARLoop == L || ARLoop->contains(L)))
5226           return true;
5227 
5228         return setUnavailable();
5229       }
5230 
5231       case scUnknown: {
5232         // For SCEVUnknown, we check for simple dominance.
5233         const auto *SU = cast<SCEVUnknown>(S);
5234         Value *V = SU->getValue();
5235 
5236         if (isa<Argument>(V))
5237           return false;
5238 
5239         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5240           return false;
5241 
5242         return setUnavailable();
5243       }
5244 
5245       case scUDivExpr:
5246       case scCouldNotCompute:
5247         // We do not try to smart about these at all.
5248         return setUnavailable();
5249       }
5250       llvm_unreachable("switch should be fully covered!");
5251     }
5252 
5253     bool isDone() { return TraversalDone; }
5254   };
5255 
5256   CheckAvailable CA(L, BB, DT);
5257   SCEVTraversal<CheckAvailable> ST(CA);
5258 
5259   ST.visitAll(S);
5260   return CA.Available;
5261 }
5262 
5263 // Try to match a control flow sequence that branches out at BI and merges back
5264 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5265 // match.
5266 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5267                           Value *&C, Value *&LHS, Value *&RHS) {
5268   C = BI->getCondition();
5269 
5270   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5271   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5272 
5273   if (!LeftEdge.isSingleEdge())
5274     return false;
5275 
5276   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5277 
5278   Use &LeftUse = Merge->getOperandUse(0);
5279   Use &RightUse = Merge->getOperandUse(1);
5280 
5281   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5282     LHS = LeftUse;
5283     RHS = RightUse;
5284     return true;
5285   }
5286 
5287   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5288     LHS = RightUse;
5289     RHS = LeftUse;
5290     return true;
5291   }
5292 
5293   return false;
5294 }
5295 
5296 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5297   auto IsReachable =
5298       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5299   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5300     const Loop *L = LI.getLoopFor(PN->getParent());
5301 
5302     // We don't want to break LCSSA, even in a SCEV expression tree.
5303     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5304       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5305         return nullptr;
5306 
5307     // Try to match
5308     //
5309     //  br %cond, label %left, label %right
5310     // left:
5311     //  br label %merge
5312     // right:
5313     //  br label %merge
5314     // merge:
5315     //  V = phi [ %x, %left ], [ %y, %right ]
5316     //
5317     // as "select %cond, %x, %y"
5318 
5319     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5320     assert(IDom && "At least the entry block should dominate PN");
5321 
5322     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5323     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5324 
5325     if (BI && BI->isConditional() &&
5326         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5327         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5328         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5329       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5330   }
5331 
5332   return nullptr;
5333 }
5334 
5335 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5336   if (const SCEV *S = createAddRecFromPHI(PN))
5337     return S;
5338 
5339   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5340     return S;
5341 
5342   // If the PHI has a single incoming value, follow that value, unless the
5343   // PHI's incoming blocks are in a different loop, in which case doing so
5344   // risks breaking LCSSA form. Instcombine would normally zap these, but
5345   // it doesn't have DominatorTree information, so it may miss cases.
5346   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5347     if (LI.replacementPreservesLCSSAForm(PN, V))
5348       return getSCEV(V);
5349 
5350   // If it's not a loop phi, we can't handle it yet.
5351   return getUnknown(PN);
5352 }
5353 
5354 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5355                                                       Value *Cond,
5356                                                       Value *TrueVal,
5357                                                       Value *FalseVal) {
5358   // Handle "constant" branch or select. This can occur for instance when a
5359   // loop pass transforms an inner loop and moves on to process the outer loop.
5360   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5361     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5362 
5363   // Try to match some simple smax or umax patterns.
5364   auto *ICI = dyn_cast<ICmpInst>(Cond);
5365   if (!ICI)
5366     return getUnknown(I);
5367 
5368   Value *LHS = ICI->getOperand(0);
5369   Value *RHS = ICI->getOperand(1);
5370 
5371   switch (ICI->getPredicate()) {
5372   case ICmpInst::ICMP_SLT:
5373   case ICmpInst::ICMP_SLE:
5374     std::swap(LHS, RHS);
5375     LLVM_FALLTHROUGH;
5376   case ICmpInst::ICMP_SGT:
5377   case ICmpInst::ICMP_SGE:
5378     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5379     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5380     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5381       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5382       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5383       const SCEV *LA = getSCEV(TrueVal);
5384       const SCEV *RA = getSCEV(FalseVal);
5385       const SCEV *LDiff = getMinusSCEV(LA, LS);
5386       const SCEV *RDiff = getMinusSCEV(RA, RS);
5387       if (LDiff == RDiff)
5388         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5389       LDiff = getMinusSCEV(LA, RS);
5390       RDiff = getMinusSCEV(RA, LS);
5391       if (LDiff == RDiff)
5392         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5393     }
5394     break;
5395   case ICmpInst::ICMP_ULT:
5396   case ICmpInst::ICMP_ULE:
5397     std::swap(LHS, RHS);
5398     LLVM_FALLTHROUGH;
5399   case ICmpInst::ICMP_UGT:
5400   case ICmpInst::ICMP_UGE:
5401     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5402     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5403     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5404       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5405       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5406       const SCEV *LA = getSCEV(TrueVal);
5407       const SCEV *RA = getSCEV(FalseVal);
5408       const SCEV *LDiff = getMinusSCEV(LA, LS);
5409       const SCEV *RDiff = getMinusSCEV(RA, RS);
5410       if (LDiff == RDiff)
5411         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5412       LDiff = getMinusSCEV(LA, RS);
5413       RDiff = getMinusSCEV(RA, LS);
5414       if (LDiff == RDiff)
5415         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5416     }
5417     break;
5418   case ICmpInst::ICMP_NE:
5419     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5420     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5421         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5422       const SCEV *One = getOne(I->getType());
5423       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5424       const SCEV *LA = getSCEV(TrueVal);
5425       const SCEV *RA = getSCEV(FalseVal);
5426       const SCEV *LDiff = getMinusSCEV(LA, LS);
5427       const SCEV *RDiff = getMinusSCEV(RA, One);
5428       if (LDiff == RDiff)
5429         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5430     }
5431     break;
5432   case ICmpInst::ICMP_EQ:
5433     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5434     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5435         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5436       const SCEV *One = getOne(I->getType());
5437       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5438       const SCEV *LA = getSCEV(TrueVal);
5439       const SCEV *RA = getSCEV(FalseVal);
5440       const SCEV *LDiff = getMinusSCEV(LA, One);
5441       const SCEV *RDiff = getMinusSCEV(RA, LS);
5442       if (LDiff == RDiff)
5443         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5444     }
5445     break;
5446   default:
5447     break;
5448   }
5449 
5450   return getUnknown(I);
5451 }
5452 
5453 /// Expand GEP instructions into add and multiply operations. This allows them
5454 /// to be analyzed by regular SCEV code.
5455 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5456   // Don't attempt to analyze GEPs over unsized objects.
5457   if (!GEP->getSourceElementType()->isSized())
5458     return getUnknown(GEP);
5459 
5460   SmallVector<const SCEV *, 4> IndexExprs;
5461   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5462     IndexExprs.push_back(getSCEV(*Index));
5463   return getGEPExpr(GEP, IndexExprs);
5464 }
5465 
5466 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5467   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5468     return C->getAPInt().countTrailingZeros();
5469 
5470   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5471     return std::min(GetMinTrailingZeros(T->getOperand()),
5472                     (uint32_t)getTypeSizeInBits(T->getType()));
5473 
5474   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5475     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5476     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5477                ? getTypeSizeInBits(E->getType())
5478                : OpRes;
5479   }
5480 
5481   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5482     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5483     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5484                ? getTypeSizeInBits(E->getType())
5485                : OpRes;
5486   }
5487 
5488   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5489     // The result is the min of all operands results.
5490     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5491     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5492       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5493     return MinOpRes;
5494   }
5495 
5496   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5497     // The result is the sum of all operands results.
5498     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5499     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5500     for (unsigned i = 1, e = M->getNumOperands();
5501          SumOpRes != BitWidth && i != e; ++i)
5502       SumOpRes =
5503           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5504     return SumOpRes;
5505   }
5506 
5507   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5508     // The result is the min of all operands results.
5509     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5510     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5511       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5512     return MinOpRes;
5513   }
5514 
5515   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5516     // The result is the min of all operands results.
5517     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5518     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5519       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5520     return MinOpRes;
5521   }
5522 
5523   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5524     // The result is the min of all operands results.
5525     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5526     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5527       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5528     return MinOpRes;
5529   }
5530 
5531   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5532     // For a SCEVUnknown, ask ValueTracking.
5533     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5534     return Known.countMinTrailingZeros();
5535   }
5536 
5537   // SCEVUDivExpr
5538   return 0;
5539 }
5540 
5541 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5542   auto I = MinTrailingZerosCache.find(S);
5543   if (I != MinTrailingZerosCache.end())
5544     return I->second;
5545 
5546   uint32_t Result = GetMinTrailingZerosImpl(S);
5547   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5548   assert(InsertPair.second && "Should insert a new key");
5549   return InsertPair.first->second;
5550 }
5551 
5552 /// Helper method to assign a range to V from metadata present in the IR.
5553 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5554   if (Instruction *I = dyn_cast<Instruction>(V))
5555     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5556       return getConstantRangeFromMetadata(*MD);
5557 
5558   return None;
5559 }
5560 
5561 /// Determine the range for a particular SCEV.  If SignHint is
5562 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5563 /// with a "cleaner" unsigned (resp. signed) representation.
5564 const ConstantRange &
5565 ScalarEvolution::getRangeRef(const SCEV *S,
5566                              ScalarEvolution::RangeSignHint SignHint) {
5567   DenseMap<const SCEV *, ConstantRange> &Cache =
5568       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5569                                                        : SignedRanges;
5570 
5571   // See if we've computed this range already.
5572   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5573   if (I != Cache.end())
5574     return I->second;
5575 
5576   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5577     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5578 
5579   unsigned BitWidth = getTypeSizeInBits(S->getType());
5580   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5581 
5582   // If the value has known zeros, the maximum value will have those known zeros
5583   // as well.
5584   uint32_t TZ = GetMinTrailingZeros(S);
5585   if (TZ != 0) {
5586     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5587       ConservativeResult =
5588           ConstantRange(APInt::getMinValue(BitWidth),
5589                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5590     else
5591       ConservativeResult = ConstantRange(
5592           APInt::getSignedMinValue(BitWidth),
5593           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5594   }
5595 
5596   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5597     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5598     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5599       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5600     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5601   }
5602 
5603   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5604     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5605     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5606       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5607     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5608   }
5609 
5610   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5611     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5612     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5613       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5614     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5615   }
5616 
5617   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5618     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5619     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5620       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5621     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5622   }
5623 
5624   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5625     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5626     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5627     return setRange(UDiv, SignHint,
5628                     ConservativeResult.intersectWith(X.udiv(Y)));
5629   }
5630 
5631   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5632     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5633     return setRange(ZExt, SignHint,
5634                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5635   }
5636 
5637   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5638     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5639     return setRange(SExt, SignHint,
5640                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5641   }
5642 
5643   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5644     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5645     return setRange(Trunc, SignHint,
5646                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5647   }
5648 
5649   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5650     // If there's no unsigned wrap, the value will never be less than its
5651     // initial value.
5652     if (AddRec->hasNoUnsignedWrap())
5653       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5654         if (!C->getValue()->isZero())
5655           ConservativeResult = ConservativeResult.intersectWith(
5656               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5657 
5658     // If there's no signed wrap, and all the operands have the same sign or
5659     // zero, the value won't ever change sign.
5660     if (AddRec->hasNoSignedWrap()) {
5661       bool AllNonNeg = true;
5662       bool AllNonPos = true;
5663       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5664         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5665         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5666       }
5667       if (AllNonNeg)
5668         ConservativeResult = ConservativeResult.intersectWith(
5669           ConstantRange(APInt(BitWidth, 0),
5670                         APInt::getSignedMinValue(BitWidth)));
5671       else if (AllNonPos)
5672         ConservativeResult = ConservativeResult.intersectWith(
5673           ConstantRange(APInt::getSignedMinValue(BitWidth),
5674                         APInt(BitWidth, 1)));
5675     }
5676 
5677     // TODO: non-affine addrec
5678     if (AddRec->isAffine()) {
5679       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5680       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5681           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5682         auto RangeFromAffine = getRangeForAffineAR(
5683             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5684             BitWidth);
5685         if (!RangeFromAffine.isFullSet())
5686           ConservativeResult =
5687               ConservativeResult.intersectWith(RangeFromAffine);
5688 
5689         auto RangeFromFactoring = getRangeViaFactoring(
5690             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5691             BitWidth);
5692         if (!RangeFromFactoring.isFullSet())
5693           ConservativeResult =
5694               ConservativeResult.intersectWith(RangeFromFactoring);
5695       }
5696     }
5697 
5698     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5699   }
5700 
5701   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5702     // Check if the IR explicitly contains !range metadata.
5703     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5704     if (MDRange.hasValue())
5705       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5706 
5707     // Split here to avoid paying the compile-time cost of calling both
5708     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5709     // if needed.
5710     const DataLayout &DL = getDataLayout();
5711     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5712       // For a SCEVUnknown, ask ValueTracking.
5713       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5714       if (Known.One != ~Known.Zero + 1)
5715         ConservativeResult =
5716             ConservativeResult.intersectWith(ConstantRange(Known.One,
5717                                                            ~Known.Zero + 1));
5718     } else {
5719       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5720              "generalize as needed!");
5721       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5722       if (NS > 1)
5723         ConservativeResult = ConservativeResult.intersectWith(
5724             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5725                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5726     }
5727 
5728     // A range of Phi is a subset of union of all ranges of its input.
5729     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5730       // Make sure that we do not run over cycled Phis.
5731       if (PendingPhiRanges.insert(Phi).second) {
5732         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5733         for (auto &Op : Phi->operands()) {
5734           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5735           RangeFromOps = RangeFromOps.unionWith(OpRange);
5736           // No point to continue if we already have a full set.
5737           if (RangeFromOps.isFullSet())
5738             break;
5739         }
5740         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5741         bool Erased = PendingPhiRanges.erase(Phi);
5742         assert(Erased && "Failed to erase Phi properly?");
5743         (void) Erased;
5744       }
5745     }
5746 
5747     return setRange(U, SignHint, std::move(ConservativeResult));
5748   }
5749 
5750   return setRange(S, SignHint, std::move(ConservativeResult));
5751 }
5752 
5753 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5754 // values that the expression can take. Initially, the expression has a value
5755 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5756 // argument defines if we treat Step as signed or unsigned.
5757 static ConstantRange getRangeForAffineARHelper(APInt Step,
5758                                                const ConstantRange &StartRange,
5759                                                const APInt &MaxBECount,
5760                                                unsigned BitWidth, bool Signed) {
5761   // If either Step or MaxBECount is 0, then the expression won't change, and we
5762   // just need to return the initial range.
5763   if (Step == 0 || MaxBECount == 0)
5764     return StartRange;
5765 
5766   // If we don't know anything about the initial value (i.e. StartRange is
5767   // FullRange), then we don't know anything about the final range either.
5768   // Return FullRange.
5769   if (StartRange.isFullSet())
5770     return ConstantRange(BitWidth, /* isFullSet = */ true);
5771 
5772   // If Step is signed and negative, then we use its absolute value, but we also
5773   // note that we're moving in the opposite direction.
5774   bool Descending = Signed && Step.isNegative();
5775 
5776   if (Signed)
5777     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5778     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5779     // This equations hold true due to the well-defined wrap-around behavior of
5780     // APInt.
5781     Step = Step.abs();
5782 
5783   // Check if Offset is more than full span of BitWidth. If it is, the
5784   // expression is guaranteed to overflow.
5785   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5786     return ConstantRange(BitWidth, /* isFullSet = */ true);
5787 
5788   // Offset is by how much the expression can change. Checks above guarantee no
5789   // overflow here.
5790   APInt Offset = Step * MaxBECount;
5791 
5792   // Minimum value of the final range will match the minimal value of StartRange
5793   // if the expression is increasing and will be decreased by Offset otherwise.
5794   // Maximum value of the final range will match the maximal value of StartRange
5795   // if the expression is decreasing and will be increased by Offset otherwise.
5796   APInt StartLower = StartRange.getLower();
5797   APInt StartUpper = StartRange.getUpper() - 1;
5798   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5799                                    : (StartUpper + std::move(Offset));
5800 
5801   // It's possible that the new minimum/maximum value will fall into the initial
5802   // range (due to wrap around). This means that the expression can take any
5803   // value in this bitwidth, and we have to return full range.
5804   if (StartRange.contains(MovedBoundary))
5805     return ConstantRange(BitWidth, /* isFullSet = */ true);
5806 
5807   APInt NewLower =
5808       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5809   APInt NewUpper =
5810       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5811   NewUpper += 1;
5812 
5813   // If we end up with full range, return a proper full range.
5814   if (NewLower == NewUpper)
5815     return ConstantRange(BitWidth, /* isFullSet = */ true);
5816 
5817   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5818   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5819 }
5820 
5821 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5822                                                    const SCEV *Step,
5823                                                    const SCEV *MaxBECount,
5824                                                    unsigned BitWidth) {
5825   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5826          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5827          "Precondition!");
5828 
5829   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5830   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5831 
5832   // First, consider step signed.
5833   ConstantRange StartSRange = getSignedRange(Start);
5834   ConstantRange StepSRange = getSignedRange(Step);
5835 
5836   // If Step can be both positive and negative, we need to find ranges for the
5837   // maximum absolute step values in both directions and union them.
5838   ConstantRange SR =
5839       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5840                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5841   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5842                                               StartSRange, MaxBECountValue,
5843                                               BitWidth, /* Signed = */ true));
5844 
5845   // Next, consider step unsigned.
5846   ConstantRange UR = getRangeForAffineARHelper(
5847       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5848       MaxBECountValue, BitWidth, /* Signed = */ false);
5849 
5850   // Finally, intersect signed and unsigned ranges.
5851   return SR.intersectWith(UR);
5852 }
5853 
5854 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5855                                                     const SCEV *Step,
5856                                                     const SCEV *MaxBECount,
5857                                                     unsigned BitWidth) {
5858   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5859   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5860 
5861   struct SelectPattern {
5862     Value *Condition = nullptr;
5863     APInt TrueValue;
5864     APInt FalseValue;
5865 
5866     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5867                            const SCEV *S) {
5868       Optional<unsigned> CastOp;
5869       APInt Offset(BitWidth, 0);
5870 
5871       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5872              "Should be!");
5873 
5874       // Peel off a constant offset:
5875       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5876         // In the future we could consider being smarter here and handle
5877         // {Start+Step,+,Step} too.
5878         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5879           return;
5880 
5881         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5882         S = SA->getOperand(1);
5883       }
5884 
5885       // Peel off a cast operation
5886       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5887         CastOp = SCast->getSCEVType();
5888         S = SCast->getOperand();
5889       }
5890 
5891       using namespace llvm::PatternMatch;
5892 
5893       auto *SU = dyn_cast<SCEVUnknown>(S);
5894       const APInt *TrueVal, *FalseVal;
5895       if (!SU ||
5896           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5897                                           m_APInt(FalseVal)))) {
5898         Condition = nullptr;
5899         return;
5900       }
5901 
5902       TrueValue = *TrueVal;
5903       FalseValue = *FalseVal;
5904 
5905       // Re-apply the cast we peeled off earlier
5906       if (CastOp.hasValue())
5907         switch (*CastOp) {
5908         default:
5909           llvm_unreachable("Unknown SCEV cast type!");
5910 
5911         case scTruncate:
5912           TrueValue = TrueValue.trunc(BitWidth);
5913           FalseValue = FalseValue.trunc(BitWidth);
5914           break;
5915         case scZeroExtend:
5916           TrueValue = TrueValue.zext(BitWidth);
5917           FalseValue = FalseValue.zext(BitWidth);
5918           break;
5919         case scSignExtend:
5920           TrueValue = TrueValue.sext(BitWidth);
5921           FalseValue = FalseValue.sext(BitWidth);
5922           break;
5923         }
5924 
5925       // Re-apply the constant offset we peeled off earlier
5926       TrueValue += Offset;
5927       FalseValue += Offset;
5928     }
5929 
5930     bool isRecognized() { return Condition != nullptr; }
5931   };
5932 
5933   SelectPattern StartPattern(*this, BitWidth, Start);
5934   if (!StartPattern.isRecognized())
5935     return ConstantRange(BitWidth, /* isFullSet = */ true);
5936 
5937   SelectPattern StepPattern(*this, BitWidth, Step);
5938   if (!StepPattern.isRecognized())
5939     return ConstantRange(BitWidth, /* isFullSet = */ true);
5940 
5941   if (StartPattern.Condition != StepPattern.Condition) {
5942     // We don't handle this case today; but we could, by considering four
5943     // possibilities below instead of two. I'm not sure if there are cases where
5944     // that will help over what getRange already does, though.
5945     return ConstantRange(BitWidth, /* isFullSet = */ true);
5946   }
5947 
5948   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5949   // construct arbitrary general SCEV expressions here.  This function is called
5950   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5951   // say) can end up caching a suboptimal value.
5952 
5953   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5954   // C2352 and C2512 (otherwise it isn't needed).
5955 
5956   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5957   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5958   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5959   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5960 
5961   ConstantRange TrueRange =
5962       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5963   ConstantRange FalseRange =
5964       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5965 
5966   return TrueRange.unionWith(FalseRange);
5967 }
5968 
5969 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5970   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5971   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5972 
5973   // Return early if there are no flags to propagate to the SCEV.
5974   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5975   if (BinOp->hasNoUnsignedWrap())
5976     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5977   if (BinOp->hasNoSignedWrap())
5978     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5979   if (Flags == SCEV::FlagAnyWrap)
5980     return SCEV::FlagAnyWrap;
5981 
5982   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5983 }
5984 
5985 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5986   // Here we check that I is in the header of the innermost loop containing I,
5987   // since we only deal with instructions in the loop header. The actual loop we
5988   // need to check later will come from an add recurrence, but getting that
5989   // requires computing the SCEV of the operands, which can be expensive. This
5990   // check we can do cheaply to rule out some cases early.
5991   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5992   if (InnermostContainingLoop == nullptr ||
5993       InnermostContainingLoop->getHeader() != I->getParent())
5994     return false;
5995 
5996   // Only proceed if we can prove that I does not yield poison.
5997   if (!programUndefinedIfFullPoison(I))
5998     return false;
5999 
6000   // At this point we know that if I is executed, then it does not wrap
6001   // according to at least one of NSW or NUW. If I is not executed, then we do
6002   // not know if the calculation that I represents would wrap. Multiple
6003   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6004   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6005   // derived from other instructions that map to the same SCEV. We cannot make
6006   // that guarantee for cases where I is not executed. So we need to find the
6007   // loop that I is considered in relation to and prove that I is executed for
6008   // every iteration of that loop. That implies that the value that I
6009   // calculates does not wrap anywhere in the loop, so then we can apply the
6010   // flags to the SCEV.
6011   //
6012   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6013   // from different loops, so that we know which loop to prove that I is
6014   // executed in.
6015   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6016     // I could be an extractvalue from a call to an overflow intrinsic.
6017     // TODO: We can do better here in some cases.
6018     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6019       return false;
6020     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6021     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6022       bool AllOtherOpsLoopInvariant = true;
6023       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6024            ++OtherOpIndex) {
6025         if (OtherOpIndex != OpIndex) {
6026           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6027           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6028             AllOtherOpsLoopInvariant = false;
6029             break;
6030           }
6031         }
6032       }
6033       if (AllOtherOpsLoopInvariant &&
6034           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6035         return true;
6036     }
6037   }
6038   return false;
6039 }
6040 
6041 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6042   // If we know that \c I can never be poison period, then that's enough.
6043   if (isSCEVExprNeverPoison(I))
6044     return true;
6045 
6046   // For an add recurrence specifically, we assume that infinite loops without
6047   // side effects are undefined behavior, and then reason as follows:
6048   //
6049   // If the add recurrence is poison in any iteration, it is poison on all
6050   // future iterations (since incrementing poison yields poison). If the result
6051   // of the add recurrence is fed into the loop latch condition and the loop
6052   // does not contain any throws or exiting blocks other than the latch, we now
6053   // have the ability to "choose" whether the backedge is taken or not (by
6054   // choosing a sufficiently evil value for the poison feeding into the branch)
6055   // for every iteration including and after the one in which \p I first became
6056   // poison.  There are two possibilities (let's call the iteration in which \p
6057   // I first became poison as K):
6058   //
6059   //  1. In the set of iterations including and after K, the loop body executes
6060   //     no side effects.  In this case executing the backege an infinte number
6061   //     of times will yield undefined behavior.
6062   //
6063   //  2. In the set of iterations including and after K, the loop body executes
6064   //     at least one side effect.  In this case, that specific instance of side
6065   //     effect is control dependent on poison, which also yields undefined
6066   //     behavior.
6067 
6068   auto *ExitingBB = L->getExitingBlock();
6069   auto *LatchBB = L->getLoopLatch();
6070   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6071     return false;
6072 
6073   SmallPtrSet<const Instruction *, 16> Pushed;
6074   SmallVector<const Instruction *, 8> PoisonStack;
6075 
6076   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6077   // things that are known to be fully poison under that assumption go on the
6078   // PoisonStack.
6079   Pushed.insert(I);
6080   PoisonStack.push_back(I);
6081 
6082   bool LatchControlDependentOnPoison = false;
6083   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6084     const Instruction *Poison = PoisonStack.pop_back_val();
6085 
6086     for (auto *PoisonUser : Poison->users()) {
6087       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6088         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6089           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6090       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6091         assert(BI->isConditional() && "Only possibility!");
6092         if (BI->getParent() == LatchBB) {
6093           LatchControlDependentOnPoison = true;
6094           break;
6095         }
6096       }
6097     }
6098   }
6099 
6100   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6101 }
6102 
6103 ScalarEvolution::LoopProperties
6104 ScalarEvolution::getLoopProperties(const Loop *L) {
6105   using LoopProperties = ScalarEvolution::LoopProperties;
6106 
6107   auto Itr = LoopPropertiesCache.find(L);
6108   if (Itr == LoopPropertiesCache.end()) {
6109     auto HasSideEffects = [](Instruction *I) {
6110       if (auto *SI = dyn_cast<StoreInst>(I))
6111         return !SI->isSimple();
6112 
6113       return I->mayHaveSideEffects();
6114     };
6115 
6116     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6117                          /*HasNoSideEffects*/ true};
6118 
6119     for (auto *BB : L->getBlocks())
6120       for (auto &I : *BB) {
6121         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6122           LP.HasNoAbnormalExits = false;
6123         if (HasSideEffects(&I))
6124           LP.HasNoSideEffects = false;
6125         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6126           break; // We're already as pessimistic as we can get.
6127       }
6128 
6129     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6130     assert(InsertPair.second && "We just checked!");
6131     Itr = InsertPair.first;
6132   }
6133 
6134   return Itr->second;
6135 }
6136 
6137 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6138   if (!isSCEVable(V->getType()))
6139     return getUnknown(V);
6140 
6141   if (Instruction *I = dyn_cast<Instruction>(V)) {
6142     // Don't attempt to analyze instructions in blocks that aren't
6143     // reachable. Such instructions don't matter, and they aren't required
6144     // to obey basic rules for definitions dominating uses which this
6145     // analysis depends on.
6146     if (!DT.isReachableFromEntry(I->getParent()))
6147       return getUnknown(UndefValue::get(V->getType()));
6148   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6149     return getConstant(CI);
6150   else if (isa<ConstantPointerNull>(V))
6151     return getZero(V->getType());
6152   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6153     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6154   else if (!isa<ConstantExpr>(V))
6155     return getUnknown(V);
6156 
6157   Operator *U = cast<Operator>(V);
6158   if (auto BO = MatchBinaryOp(U, DT)) {
6159     switch (BO->Opcode) {
6160     case Instruction::Add: {
6161       // The simple thing to do would be to just call getSCEV on both operands
6162       // and call getAddExpr with the result. However if we're looking at a
6163       // bunch of things all added together, this can be quite inefficient,
6164       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6165       // Instead, gather up all the operands and make a single getAddExpr call.
6166       // LLVM IR canonical form means we need only traverse the left operands.
6167       SmallVector<const SCEV *, 4> AddOps;
6168       do {
6169         if (BO->Op) {
6170           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6171             AddOps.push_back(OpSCEV);
6172             break;
6173           }
6174 
6175           // If a NUW or NSW flag can be applied to the SCEV for this
6176           // addition, then compute the SCEV for this addition by itself
6177           // with a separate call to getAddExpr. We need to do that
6178           // instead of pushing the operands of the addition onto AddOps,
6179           // since the flags are only known to apply to this particular
6180           // addition - they may not apply to other additions that can be
6181           // formed with operands from AddOps.
6182           const SCEV *RHS = getSCEV(BO->RHS);
6183           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6184           if (Flags != SCEV::FlagAnyWrap) {
6185             const SCEV *LHS = getSCEV(BO->LHS);
6186             if (BO->Opcode == Instruction::Sub)
6187               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6188             else
6189               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6190             break;
6191           }
6192         }
6193 
6194         if (BO->Opcode == Instruction::Sub)
6195           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6196         else
6197           AddOps.push_back(getSCEV(BO->RHS));
6198 
6199         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6200         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6201                        NewBO->Opcode != Instruction::Sub)) {
6202           AddOps.push_back(getSCEV(BO->LHS));
6203           break;
6204         }
6205         BO = NewBO;
6206       } while (true);
6207 
6208       return getAddExpr(AddOps);
6209     }
6210 
6211     case Instruction::Mul: {
6212       SmallVector<const SCEV *, 4> MulOps;
6213       do {
6214         if (BO->Op) {
6215           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6216             MulOps.push_back(OpSCEV);
6217             break;
6218           }
6219 
6220           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6221           if (Flags != SCEV::FlagAnyWrap) {
6222             MulOps.push_back(
6223                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6224             break;
6225           }
6226         }
6227 
6228         MulOps.push_back(getSCEV(BO->RHS));
6229         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6230         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6231           MulOps.push_back(getSCEV(BO->LHS));
6232           break;
6233         }
6234         BO = NewBO;
6235       } while (true);
6236 
6237       return getMulExpr(MulOps);
6238     }
6239     case Instruction::UDiv:
6240       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6241     case Instruction::URem:
6242       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6243     case Instruction::Sub: {
6244       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6245       if (BO->Op)
6246         Flags = getNoWrapFlagsFromUB(BO->Op);
6247       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6248     }
6249     case Instruction::And:
6250       // For an expression like x&255 that merely masks off the high bits,
6251       // use zext(trunc(x)) as the SCEV expression.
6252       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6253         if (CI->isZero())
6254           return getSCEV(BO->RHS);
6255         if (CI->isMinusOne())
6256           return getSCEV(BO->LHS);
6257         const APInt &A = CI->getValue();
6258 
6259         // Instcombine's ShrinkDemandedConstant may strip bits out of
6260         // constants, obscuring what would otherwise be a low-bits mask.
6261         // Use computeKnownBits to compute what ShrinkDemandedConstant
6262         // knew about to reconstruct a low-bits mask value.
6263         unsigned LZ = A.countLeadingZeros();
6264         unsigned TZ = A.countTrailingZeros();
6265         unsigned BitWidth = A.getBitWidth();
6266         KnownBits Known(BitWidth);
6267         computeKnownBits(BO->LHS, Known, getDataLayout(),
6268                          0, &AC, nullptr, &DT);
6269 
6270         APInt EffectiveMask =
6271             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6272         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6273           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6274           const SCEV *LHS = getSCEV(BO->LHS);
6275           const SCEV *ShiftedLHS = nullptr;
6276           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6277             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6278               // For an expression like (x * 8) & 8, simplify the multiply.
6279               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6280               unsigned GCD = std::min(MulZeros, TZ);
6281               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6282               SmallVector<const SCEV*, 4> MulOps;
6283               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6284               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6285               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6286               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6287             }
6288           }
6289           if (!ShiftedLHS)
6290             ShiftedLHS = getUDivExpr(LHS, MulCount);
6291           return getMulExpr(
6292               getZeroExtendExpr(
6293                   getTruncateExpr(ShiftedLHS,
6294                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6295                   BO->LHS->getType()),
6296               MulCount);
6297         }
6298       }
6299       break;
6300 
6301     case Instruction::Or:
6302       // If the RHS of the Or is a constant, we may have something like:
6303       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6304       // optimizations will transparently handle this case.
6305       //
6306       // In order for this transformation to be safe, the LHS must be of the
6307       // form X*(2^n) and the Or constant must be less than 2^n.
6308       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6309         const SCEV *LHS = getSCEV(BO->LHS);
6310         const APInt &CIVal = CI->getValue();
6311         if (GetMinTrailingZeros(LHS) >=
6312             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6313           // Build a plain add SCEV.
6314           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6315           // If the LHS of the add was an addrec and it has no-wrap flags,
6316           // transfer the no-wrap flags, since an or won't introduce a wrap.
6317           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6318             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6319             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6320                 OldAR->getNoWrapFlags());
6321           }
6322           return S;
6323         }
6324       }
6325       break;
6326 
6327     case Instruction::Xor:
6328       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6329         // If the RHS of xor is -1, then this is a not operation.
6330         if (CI->isMinusOne())
6331           return getNotSCEV(getSCEV(BO->LHS));
6332 
6333         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6334         // This is a variant of the check for xor with -1, and it handles
6335         // the case where instcombine has trimmed non-demanded bits out
6336         // of an xor with -1.
6337         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6338           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6339             if (LBO->getOpcode() == Instruction::And &&
6340                 LCI->getValue() == CI->getValue())
6341               if (const SCEVZeroExtendExpr *Z =
6342                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6343                 Type *UTy = BO->LHS->getType();
6344                 const SCEV *Z0 = Z->getOperand();
6345                 Type *Z0Ty = Z0->getType();
6346                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6347 
6348                 // If C is a low-bits mask, the zero extend is serving to
6349                 // mask off the high bits. Complement the operand and
6350                 // re-apply the zext.
6351                 if (CI->getValue().isMask(Z0TySize))
6352                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6353 
6354                 // If C is a single bit, it may be in the sign-bit position
6355                 // before the zero-extend. In this case, represent the xor
6356                 // using an add, which is equivalent, and re-apply the zext.
6357                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6358                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6359                     Trunc.isSignMask())
6360                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6361                                            UTy);
6362               }
6363       }
6364       break;
6365 
6366     case Instruction::Shl:
6367       // Turn shift left of a constant amount into a multiply.
6368       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6369         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6370 
6371         // If the shift count is not less than the bitwidth, the result of
6372         // the shift is undefined. Don't try to analyze it, because the
6373         // resolution chosen here may differ from the resolution chosen in
6374         // other parts of the compiler.
6375         if (SA->getValue().uge(BitWidth))
6376           break;
6377 
6378         // It is currently not resolved how to interpret NSW for left
6379         // shift by BitWidth - 1, so we avoid applying flags in that
6380         // case. Remove this check (or this comment) once the situation
6381         // is resolved. See
6382         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6383         // and http://reviews.llvm.org/D8890 .
6384         auto Flags = SCEV::FlagAnyWrap;
6385         if (BO->Op && SA->getValue().ult(BitWidth - 1))
6386           Flags = getNoWrapFlagsFromUB(BO->Op);
6387 
6388         Constant *X = ConstantInt::get(
6389             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6390         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6391       }
6392       break;
6393 
6394     case Instruction::AShr: {
6395       // AShr X, C, where C is a constant.
6396       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6397       if (!CI)
6398         break;
6399 
6400       Type *OuterTy = BO->LHS->getType();
6401       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6402       // If the shift count is not less than the bitwidth, the result of
6403       // the shift is undefined. Don't try to analyze it, because the
6404       // resolution chosen here may differ from the resolution chosen in
6405       // other parts of the compiler.
6406       if (CI->getValue().uge(BitWidth))
6407         break;
6408 
6409       if (CI->isZero())
6410         return getSCEV(BO->LHS); // shift by zero --> noop
6411 
6412       uint64_t AShrAmt = CI->getZExtValue();
6413       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6414 
6415       Operator *L = dyn_cast<Operator>(BO->LHS);
6416       if (L && L->getOpcode() == Instruction::Shl) {
6417         // X = Shl A, n
6418         // Y = AShr X, m
6419         // Both n and m are constant.
6420 
6421         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6422         if (L->getOperand(1) == BO->RHS)
6423           // For a two-shift sext-inreg, i.e. n = m,
6424           // use sext(trunc(x)) as the SCEV expression.
6425           return getSignExtendExpr(
6426               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6427 
6428         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6429         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6430           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6431           if (ShlAmt > AShrAmt) {
6432             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6433             // expression. We already checked that ShlAmt < BitWidth, so
6434             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6435             // ShlAmt - AShrAmt < Amt.
6436             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6437                                             ShlAmt - AShrAmt);
6438             return getSignExtendExpr(
6439                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6440                 getConstant(Mul)), OuterTy);
6441           }
6442         }
6443       }
6444       break;
6445     }
6446     }
6447   }
6448 
6449   switch (U->getOpcode()) {
6450   case Instruction::Trunc:
6451     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6452 
6453   case Instruction::ZExt:
6454     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6455 
6456   case Instruction::SExt:
6457     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6458       // The NSW flag of a subtract does not always survive the conversion to
6459       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6460       // more likely to preserve NSW and allow later AddRec optimisations.
6461       //
6462       // NOTE: This is effectively duplicating this logic from getSignExtend:
6463       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6464       // but by that point the NSW information has potentially been lost.
6465       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6466         Type *Ty = U->getType();
6467         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6468         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6469         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6470       }
6471     }
6472     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6473 
6474   case Instruction::BitCast:
6475     // BitCasts are no-op casts so we just eliminate the cast.
6476     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6477       return getSCEV(U->getOperand(0));
6478     break;
6479 
6480   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6481   // lead to pointer expressions which cannot safely be expanded to GEPs,
6482   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6483   // simplifying integer expressions.
6484 
6485   case Instruction::GetElementPtr:
6486     return createNodeForGEP(cast<GEPOperator>(U));
6487 
6488   case Instruction::PHI:
6489     return createNodeForPHI(cast<PHINode>(U));
6490 
6491   case Instruction::Select:
6492     // U can also be a select constant expr, which let fall through.  Since
6493     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6494     // constant expressions cannot have instructions as operands, we'd have
6495     // returned getUnknown for a select constant expressions anyway.
6496     if (isa<Instruction>(U))
6497       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6498                                       U->getOperand(1), U->getOperand(2));
6499     break;
6500 
6501   case Instruction::Call:
6502   case Instruction::Invoke:
6503     if (Value *RV = CallSite(U).getReturnedArgOperand())
6504       return getSCEV(RV);
6505     break;
6506   }
6507 
6508   return getUnknown(V);
6509 }
6510 
6511 //===----------------------------------------------------------------------===//
6512 //                   Iteration Count Computation Code
6513 //
6514 
6515 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6516   if (!ExitCount)
6517     return 0;
6518 
6519   ConstantInt *ExitConst = ExitCount->getValue();
6520 
6521   // Guard against huge trip counts.
6522   if (ExitConst->getValue().getActiveBits() > 32)
6523     return 0;
6524 
6525   // In case of integer overflow, this returns 0, which is correct.
6526   return ((unsigned)ExitConst->getZExtValue()) + 1;
6527 }
6528 
6529 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6530   if (BasicBlock *ExitingBB = L->getExitingBlock())
6531     return getSmallConstantTripCount(L, ExitingBB);
6532 
6533   // No trip count information for multiple exits.
6534   return 0;
6535 }
6536 
6537 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6538                                                     BasicBlock *ExitingBlock) {
6539   assert(ExitingBlock && "Must pass a non-null exiting block!");
6540   assert(L->isLoopExiting(ExitingBlock) &&
6541          "Exiting block must actually branch out of the loop!");
6542   const SCEVConstant *ExitCount =
6543       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6544   return getConstantTripCount(ExitCount);
6545 }
6546 
6547 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6548   const auto *MaxExitCount =
6549       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6550   return getConstantTripCount(MaxExitCount);
6551 }
6552 
6553 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6554   if (BasicBlock *ExitingBB = L->getExitingBlock())
6555     return getSmallConstantTripMultiple(L, ExitingBB);
6556 
6557   // No trip multiple information for multiple exits.
6558   return 0;
6559 }
6560 
6561 /// Returns the largest constant divisor of the trip count of this loop as a
6562 /// normal unsigned value, if possible. This means that the actual trip count is
6563 /// always a multiple of the returned value (don't forget the trip count could
6564 /// very well be zero as well!).
6565 ///
6566 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6567 /// multiple of a constant (which is also the case if the trip count is simply
6568 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6569 /// if the trip count is very large (>= 2^32).
6570 ///
6571 /// As explained in the comments for getSmallConstantTripCount, this assumes
6572 /// that control exits the loop via ExitingBlock.
6573 unsigned
6574 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6575                                               BasicBlock *ExitingBlock) {
6576   assert(ExitingBlock && "Must pass a non-null exiting block!");
6577   assert(L->isLoopExiting(ExitingBlock) &&
6578          "Exiting block must actually branch out of the loop!");
6579   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6580   if (ExitCount == getCouldNotCompute())
6581     return 1;
6582 
6583   // Get the trip count from the BE count by adding 1.
6584   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6585 
6586   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6587   if (!TC)
6588     // Attempt to factor more general cases. Returns the greatest power of
6589     // two divisor. If overflow happens, the trip count expression is still
6590     // divisible by the greatest power of 2 divisor returned.
6591     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6592 
6593   ConstantInt *Result = TC->getValue();
6594 
6595   // Guard against huge trip counts (this requires checking
6596   // for zero to handle the case where the trip count == -1 and the
6597   // addition wraps).
6598   if (!Result || Result->getValue().getActiveBits() > 32 ||
6599       Result->getValue().getActiveBits() == 0)
6600     return 1;
6601 
6602   return (unsigned)Result->getZExtValue();
6603 }
6604 
6605 /// Get the expression for the number of loop iterations for which this loop is
6606 /// guaranteed not to exit via ExitingBlock. Otherwise return
6607 /// SCEVCouldNotCompute.
6608 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6609                                           BasicBlock *ExitingBlock) {
6610   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6611 }
6612 
6613 const SCEV *
6614 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6615                                                  SCEVUnionPredicate &Preds) {
6616   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6617 }
6618 
6619 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6620   return getBackedgeTakenInfo(L).getExact(L, this);
6621 }
6622 
6623 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6624 /// known never to be less than the actual backedge taken count.
6625 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6626   return getBackedgeTakenInfo(L).getMax(this);
6627 }
6628 
6629 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6630   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6631 }
6632 
6633 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6634 static void
6635 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6636   BasicBlock *Header = L->getHeader();
6637 
6638   // Push all Loop-header PHIs onto the Worklist stack.
6639   for (PHINode &PN : Header->phis())
6640     Worklist.push_back(&PN);
6641 }
6642 
6643 const ScalarEvolution::BackedgeTakenInfo &
6644 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6645   auto &BTI = getBackedgeTakenInfo(L);
6646   if (BTI.hasFullInfo())
6647     return BTI;
6648 
6649   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6650 
6651   if (!Pair.second)
6652     return Pair.first->second;
6653 
6654   BackedgeTakenInfo Result =
6655       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6656 
6657   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6658 }
6659 
6660 const ScalarEvolution::BackedgeTakenInfo &
6661 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6662   // Initially insert an invalid entry for this loop. If the insertion
6663   // succeeds, proceed to actually compute a backedge-taken count and
6664   // update the value. The temporary CouldNotCompute value tells SCEV
6665   // code elsewhere that it shouldn't attempt to request a new
6666   // backedge-taken count, which could result in infinite recursion.
6667   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6668       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6669   if (!Pair.second)
6670     return Pair.first->second;
6671 
6672   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6673   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6674   // must be cleared in this scope.
6675   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6676 
6677   // In product build, there are no usage of statistic.
6678   (void)NumTripCountsComputed;
6679   (void)NumTripCountsNotComputed;
6680 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6681   const SCEV *BEExact = Result.getExact(L, this);
6682   if (BEExact != getCouldNotCompute()) {
6683     assert(isLoopInvariant(BEExact, L) &&
6684            isLoopInvariant(Result.getMax(this), L) &&
6685            "Computed backedge-taken count isn't loop invariant for loop!");
6686     ++NumTripCountsComputed;
6687   }
6688   else if (Result.getMax(this) == getCouldNotCompute() &&
6689            isa<PHINode>(L->getHeader()->begin())) {
6690     // Only count loops that have phi nodes as not being computable.
6691     ++NumTripCountsNotComputed;
6692   }
6693 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6694 
6695   // Now that we know more about the trip count for this loop, forget any
6696   // existing SCEV values for PHI nodes in this loop since they are only
6697   // conservative estimates made without the benefit of trip count
6698   // information. This is similar to the code in forgetLoop, except that
6699   // it handles SCEVUnknown PHI nodes specially.
6700   if (Result.hasAnyInfo()) {
6701     SmallVector<Instruction *, 16> Worklist;
6702     PushLoopPHIs(L, Worklist);
6703 
6704     SmallPtrSet<Instruction *, 8> Discovered;
6705     while (!Worklist.empty()) {
6706       Instruction *I = Worklist.pop_back_val();
6707 
6708       ValueExprMapType::iterator It =
6709         ValueExprMap.find_as(static_cast<Value *>(I));
6710       if (It != ValueExprMap.end()) {
6711         const SCEV *Old = It->second;
6712 
6713         // SCEVUnknown for a PHI either means that it has an unrecognized
6714         // structure, or it's a PHI that's in the progress of being computed
6715         // by createNodeForPHI.  In the former case, additional loop trip
6716         // count information isn't going to change anything. In the later
6717         // case, createNodeForPHI will perform the necessary updates on its
6718         // own when it gets to that point.
6719         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6720           eraseValueFromMap(It->first);
6721           forgetMemoizedResults(Old);
6722         }
6723         if (PHINode *PN = dyn_cast<PHINode>(I))
6724           ConstantEvolutionLoopExitValue.erase(PN);
6725       }
6726 
6727       // Since we don't need to invalidate anything for correctness and we're
6728       // only invalidating to make SCEV's results more precise, we get to stop
6729       // early to avoid invalidating too much.  This is especially important in
6730       // cases like:
6731       //
6732       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6733       // loop0:
6734       //   %pn0 = phi
6735       //   ...
6736       // loop1:
6737       //   %pn1 = phi
6738       //   ...
6739       //
6740       // where both loop0 and loop1's backedge taken count uses the SCEV
6741       // expression for %v.  If we don't have the early stop below then in cases
6742       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6743       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6744       // count for loop1, effectively nullifying SCEV's trip count cache.
6745       for (auto *U : I->users())
6746         if (auto *I = dyn_cast<Instruction>(U)) {
6747           auto *LoopForUser = LI.getLoopFor(I->getParent());
6748           if (LoopForUser && L->contains(LoopForUser) &&
6749               Discovered.insert(I).second)
6750             Worklist.push_back(I);
6751         }
6752     }
6753   }
6754 
6755   // Re-lookup the insert position, since the call to
6756   // computeBackedgeTakenCount above could result in a
6757   // recusive call to getBackedgeTakenInfo (on a different
6758   // loop), which would invalidate the iterator computed
6759   // earlier.
6760   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6761 }
6762 
6763 void ScalarEvolution::forgetLoop(const Loop *L) {
6764   // Drop any stored trip count value.
6765   auto RemoveLoopFromBackedgeMap =
6766       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6767         auto BTCPos = Map.find(L);
6768         if (BTCPos != Map.end()) {
6769           BTCPos->second.clear();
6770           Map.erase(BTCPos);
6771         }
6772       };
6773 
6774   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6775   SmallVector<Instruction *, 32> Worklist;
6776   SmallPtrSet<Instruction *, 16> Visited;
6777 
6778   // Iterate over all the loops and sub-loops to drop SCEV information.
6779   while (!LoopWorklist.empty()) {
6780     auto *CurrL = LoopWorklist.pop_back_val();
6781 
6782     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6783     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6784 
6785     // Drop information about predicated SCEV rewrites for this loop.
6786     for (auto I = PredicatedSCEVRewrites.begin();
6787          I != PredicatedSCEVRewrites.end();) {
6788       std::pair<const SCEV *, const Loop *> Entry = I->first;
6789       if (Entry.second == CurrL)
6790         PredicatedSCEVRewrites.erase(I++);
6791       else
6792         ++I;
6793     }
6794 
6795     auto LoopUsersItr = LoopUsers.find(CurrL);
6796     if (LoopUsersItr != LoopUsers.end()) {
6797       for (auto *S : LoopUsersItr->second)
6798         forgetMemoizedResults(S);
6799       LoopUsers.erase(LoopUsersItr);
6800     }
6801 
6802     // Drop information about expressions based on loop-header PHIs.
6803     PushLoopPHIs(CurrL, Worklist);
6804 
6805     while (!Worklist.empty()) {
6806       Instruction *I = Worklist.pop_back_val();
6807       if (!Visited.insert(I).second)
6808         continue;
6809 
6810       ValueExprMapType::iterator It =
6811           ValueExprMap.find_as(static_cast<Value *>(I));
6812       if (It != ValueExprMap.end()) {
6813         eraseValueFromMap(It->first);
6814         forgetMemoizedResults(It->second);
6815         if (PHINode *PN = dyn_cast<PHINode>(I))
6816           ConstantEvolutionLoopExitValue.erase(PN);
6817       }
6818 
6819       PushDefUseChildren(I, Worklist);
6820     }
6821 
6822     LoopPropertiesCache.erase(CurrL);
6823     // Forget all contained loops too, to avoid dangling entries in the
6824     // ValuesAtScopes map.
6825     LoopWorklist.append(CurrL->begin(), CurrL->end());
6826   }
6827 }
6828 
6829 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6830   while (Loop *Parent = L->getParentLoop())
6831     L = Parent;
6832   forgetLoop(L);
6833 }
6834 
6835 void ScalarEvolution::forgetValue(Value *V) {
6836   Instruction *I = dyn_cast<Instruction>(V);
6837   if (!I) return;
6838 
6839   // Drop information about expressions based on loop-header PHIs.
6840   SmallVector<Instruction *, 16> Worklist;
6841   Worklist.push_back(I);
6842 
6843   SmallPtrSet<Instruction *, 8> Visited;
6844   while (!Worklist.empty()) {
6845     I = Worklist.pop_back_val();
6846     if (!Visited.insert(I).second)
6847       continue;
6848 
6849     ValueExprMapType::iterator It =
6850       ValueExprMap.find_as(static_cast<Value *>(I));
6851     if (It != ValueExprMap.end()) {
6852       eraseValueFromMap(It->first);
6853       forgetMemoizedResults(It->second);
6854       if (PHINode *PN = dyn_cast<PHINode>(I))
6855         ConstantEvolutionLoopExitValue.erase(PN);
6856     }
6857 
6858     PushDefUseChildren(I, Worklist);
6859   }
6860 }
6861 
6862 /// Get the exact loop backedge taken count considering all loop exits. A
6863 /// computable result can only be returned for loops with all exiting blocks
6864 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6865 /// is never skipped. This is a valid assumption as long as the loop exits via
6866 /// that test. For precise results, it is the caller's responsibility to specify
6867 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6868 const SCEV *
6869 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6870                                              SCEVUnionPredicate *Preds) const {
6871   // If any exits were not computable, the loop is not computable.
6872   if (!isComplete() || ExitNotTaken.empty())
6873     return SE->getCouldNotCompute();
6874 
6875   const BasicBlock *Latch = L->getLoopLatch();
6876   // All exiting blocks we have collected must dominate the only backedge.
6877   if (!Latch)
6878     return SE->getCouldNotCompute();
6879 
6880   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6881   // count is simply a minimum out of all these calculated exit counts.
6882   SmallVector<const SCEV *, 2> Ops;
6883   for (auto &ENT : ExitNotTaken) {
6884     const SCEV *BECount = ENT.ExactNotTaken;
6885     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6886     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6887            "We should only have known counts for exiting blocks that dominate "
6888            "latch!");
6889 
6890     Ops.push_back(BECount);
6891 
6892     if (Preds && !ENT.hasAlwaysTruePredicate())
6893       Preds->add(ENT.Predicate.get());
6894 
6895     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6896            "Predicate should be always true!");
6897   }
6898 
6899   return SE->getUMinFromMismatchedTypes(Ops);
6900 }
6901 
6902 /// Get the exact not taken count for this loop exit.
6903 const SCEV *
6904 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6905                                              ScalarEvolution *SE) const {
6906   for (auto &ENT : ExitNotTaken)
6907     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6908       return ENT.ExactNotTaken;
6909 
6910   return SE->getCouldNotCompute();
6911 }
6912 
6913 /// getMax - Get the max backedge taken count for the loop.
6914 const SCEV *
6915 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6916   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6917     return !ENT.hasAlwaysTruePredicate();
6918   };
6919 
6920   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6921     return SE->getCouldNotCompute();
6922 
6923   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6924          "No point in having a non-constant max backedge taken count!");
6925   return getMax();
6926 }
6927 
6928 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6929   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6930     return !ENT.hasAlwaysTruePredicate();
6931   };
6932   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6933 }
6934 
6935 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6936                                                     ScalarEvolution *SE) const {
6937   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6938       SE->hasOperand(getMax(), S))
6939     return true;
6940 
6941   for (auto &ENT : ExitNotTaken)
6942     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6943         SE->hasOperand(ENT.ExactNotTaken, S))
6944       return true;
6945 
6946   return false;
6947 }
6948 
6949 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6950     : ExactNotTaken(E), MaxNotTaken(E) {
6951   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6952           isa<SCEVConstant>(MaxNotTaken)) &&
6953          "No point in having a non-constant max backedge taken count!");
6954 }
6955 
6956 ScalarEvolution::ExitLimit::ExitLimit(
6957     const SCEV *E, const SCEV *M, bool MaxOrZero,
6958     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6959     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6960   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6961           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6962          "Exact is not allowed to be less precise than Max");
6963   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6964           isa<SCEVConstant>(MaxNotTaken)) &&
6965          "No point in having a non-constant max backedge taken count!");
6966   for (auto *PredSet : PredSetList)
6967     for (auto *P : *PredSet)
6968       addPredicate(P);
6969 }
6970 
6971 ScalarEvolution::ExitLimit::ExitLimit(
6972     const SCEV *E, const SCEV *M, bool MaxOrZero,
6973     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6974     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6975   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6976           isa<SCEVConstant>(MaxNotTaken)) &&
6977          "No point in having a non-constant max backedge taken count!");
6978 }
6979 
6980 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6981                                       bool MaxOrZero)
6982     : ExitLimit(E, M, MaxOrZero, None) {
6983   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6984           isa<SCEVConstant>(MaxNotTaken)) &&
6985          "No point in having a non-constant max backedge taken count!");
6986 }
6987 
6988 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6989 /// computable exit into a persistent ExitNotTakenInfo array.
6990 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6991     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6992         ExitCounts,
6993     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6994     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6995   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6996 
6997   ExitNotTaken.reserve(ExitCounts.size());
6998   std::transform(
6999       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7000       [&](const EdgeExitInfo &EEI) {
7001         BasicBlock *ExitBB = EEI.first;
7002         const ExitLimit &EL = EEI.second;
7003         if (EL.Predicates.empty())
7004           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
7005 
7006         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7007         for (auto *Pred : EL.Predicates)
7008           Predicate->add(Pred);
7009 
7010         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
7011       });
7012   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7013          "No point in having a non-constant max backedge taken count!");
7014 }
7015 
7016 /// Invalidate this result and free the ExitNotTakenInfo array.
7017 void ScalarEvolution::BackedgeTakenInfo::clear() {
7018   ExitNotTaken.clear();
7019 }
7020 
7021 /// Compute the number of times the backedge of the specified loop will execute.
7022 ScalarEvolution::BackedgeTakenInfo
7023 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7024                                            bool AllowPredicates) {
7025   SmallVector<BasicBlock *, 8> ExitingBlocks;
7026   L->getExitingBlocks(ExitingBlocks);
7027 
7028   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7029 
7030   SmallVector<EdgeExitInfo, 4> ExitCounts;
7031   bool CouldComputeBECount = true;
7032   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7033   const SCEV *MustExitMaxBECount = nullptr;
7034   const SCEV *MayExitMaxBECount = nullptr;
7035   bool MustExitMaxOrZero = false;
7036 
7037   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7038   // and compute maxBECount.
7039   // Do a union of all the predicates here.
7040   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7041     BasicBlock *ExitBB = ExitingBlocks[i];
7042     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7043 
7044     assert((AllowPredicates || EL.Predicates.empty()) &&
7045            "Predicated exit limit when predicates are not allowed!");
7046 
7047     // 1. For each exit that can be computed, add an entry to ExitCounts.
7048     // CouldComputeBECount is true only if all exits can be computed.
7049     if (EL.ExactNotTaken == getCouldNotCompute())
7050       // We couldn't compute an exact value for this exit, so
7051       // we won't be able to compute an exact value for the loop.
7052       CouldComputeBECount = false;
7053     else
7054       ExitCounts.emplace_back(ExitBB, EL);
7055 
7056     // 2. Derive the loop's MaxBECount from each exit's max number of
7057     // non-exiting iterations. Partition the loop exits into two kinds:
7058     // LoopMustExits and LoopMayExits.
7059     //
7060     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7061     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7062     // MaxBECount is the minimum EL.MaxNotTaken of computable
7063     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7064     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7065     // computable EL.MaxNotTaken.
7066     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7067         DT.dominates(ExitBB, Latch)) {
7068       if (!MustExitMaxBECount) {
7069         MustExitMaxBECount = EL.MaxNotTaken;
7070         MustExitMaxOrZero = EL.MaxOrZero;
7071       } else {
7072         MustExitMaxBECount =
7073             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7074       }
7075     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7076       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7077         MayExitMaxBECount = EL.MaxNotTaken;
7078       else {
7079         MayExitMaxBECount =
7080             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7081       }
7082     }
7083   }
7084   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7085     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7086   // The loop backedge will be taken the maximum or zero times if there's
7087   // a single exit that must be taken the maximum or zero times.
7088   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7089   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7090                            MaxBECount, MaxOrZero);
7091 }
7092 
7093 ScalarEvolution::ExitLimit
7094 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7095                                       bool AllowPredicates) {
7096   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7097   // If our exiting block does not dominate the latch, then its connection with
7098   // loop's exit limit may be far from trivial.
7099   const BasicBlock *Latch = L->getLoopLatch();
7100   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7101     return getCouldNotCompute();
7102 
7103   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7104   Instruction *Term = ExitingBlock->getTerminator();
7105   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7106     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7107     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7108     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7109            "It should have one successor in loop and one exit block!");
7110     // Proceed to the next level to examine the exit condition expression.
7111     return computeExitLimitFromCond(
7112         L, BI->getCondition(), ExitIfTrue,
7113         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7114   }
7115 
7116   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7117     // For switch, make sure that there is a single exit from the loop.
7118     BasicBlock *Exit = nullptr;
7119     for (auto *SBB : successors(ExitingBlock))
7120       if (!L->contains(SBB)) {
7121         if (Exit) // Multiple exit successors.
7122           return getCouldNotCompute();
7123         Exit = SBB;
7124       }
7125     assert(Exit && "Exiting block must have at least one exit");
7126     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7127                                                 /*ControlsExit=*/IsOnlyExit);
7128   }
7129 
7130   return getCouldNotCompute();
7131 }
7132 
7133 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7134     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7135     bool ControlsExit, bool AllowPredicates) {
7136   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7137   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7138                                         ControlsExit, AllowPredicates);
7139 }
7140 
7141 Optional<ScalarEvolution::ExitLimit>
7142 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7143                                       bool ExitIfTrue, bool ControlsExit,
7144                                       bool AllowPredicates) {
7145   (void)this->L;
7146   (void)this->ExitIfTrue;
7147   (void)this->AllowPredicates;
7148 
7149   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7150          this->AllowPredicates == AllowPredicates &&
7151          "Variance in assumed invariant key components!");
7152   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7153   if (Itr == TripCountMap.end())
7154     return None;
7155   return Itr->second;
7156 }
7157 
7158 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7159                                              bool ExitIfTrue,
7160                                              bool ControlsExit,
7161                                              bool AllowPredicates,
7162                                              const ExitLimit &EL) {
7163   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7164          this->AllowPredicates == AllowPredicates &&
7165          "Variance in assumed invariant key components!");
7166 
7167   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7168   assert(InsertResult.second && "Expected successful insertion!");
7169   (void)InsertResult;
7170   (void)ExitIfTrue;
7171 }
7172 
7173 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7174     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7175     bool ControlsExit, bool AllowPredicates) {
7176 
7177   if (auto MaybeEL =
7178           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7179     return *MaybeEL;
7180 
7181   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7182                                               ControlsExit, AllowPredicates);
7183   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7184   return EL;
7185 }
7186 
7187 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7188     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7189     bool ControlsExit, bool AllowPredicates) {
7190   // Check if the controlling expression for this loop is an And or Or.
7191   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7192     if (BO->getOpcode() == Instruction::And) {
7193       // Recurse on the operands of the and.
7194       bool EitherMayExit = !ExitIfTrue;
7195       ExitLimit EL0 = computeExitLimitFromCondCached(
7196           Cache, L, BO->getOperand(0), ExitIfTrue,
7197           ControlsExit && !EitherMayExit, AllowPredicates);
7198       ExitLimit EL1 = computeExitLimitFromCondCached(
7199           Cache, L, BO->getOperand(1), ExitIfTrue,
7200           ControlsExit && !EitherMayExit, AllowPredicates);
7201       const SCEV *BECount = getCouldNotCompute();
7202       const SCEV *MaxBECount = getCouldNotCompute();
7203       if (EitherMayExit) {
7204         // Both conditions must be true for the loop to continue executing.
7205         // Choose the less conservative count.
7206         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7207             EL1.ExactNotTaken == getCouldNotCompute())
7208           BECount = getCouldNotCompute();
7209         else
7210           BECount =
7211               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7212         if (EL0.MaxNotTaken == getCouldNotCompute())
7213           MaxBECount = EL1.MaxNotTaken;
7214         else if (EL1.MaxNotTaken == getCouldNotCompute())
7215           MaxBECount = EL0.MaxNotTaken;
7216         else
7217           MaxBECount =
7218               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7219       } else {
7220         // Both conditions must be true at the same time for the loop to exit.
7221         // For now, be conservative.
7222         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7223           MaxBECount = EL0.MaxNotTaken;
7224         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7225           BECount = EL0.ExactNotTaken;
7226       }
7227 
7228       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7229       // to be more aggressive when computing BECount than when computing
7230       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7231       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7232       // to not.
7233       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7234           !isa<SCEVCouldNotCompute>(BECount))
7235         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7236 
7237       return ExitLimit(BECount, MaxBECount, false,
7238                        {&EL0.Predicates, &EL1.Predicates});
7239     }
7240     if (BO->getOpcode() == Instruction::Or) {
7241       // Recurse on the operands of the or.
7242       bool EitherMayExit = ExitIfTrue;
7243       ExitLimit EL0 = computeExitLimitFromCondCached(
7244           Cache, L, BO->getOperand(0), ExitIfTrue,
7245           ControlsExit && !EitherMayExit, AllowPredicates);
7246       ExitLimit EL1 = computeExitLimitFromCondCached(
7247           Cache, L, BO->getOperand(1), ExitIfTrue,
7248           ControlsExit && !EitherMayExit, AllowPredicates);
7249       const SCEV *BECount = getCouldNotCompute();
7250       const SCEV *MaxBECount = getCouldNotCompute();
7251       if (EitherMayExit) {
7252         // Both conditions must be false for the loop to continue executing.
7253         // Choose the less conservative count.
7254         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7255             EL1.ExactNotTaken == getCouldNotCompute())
7256           BECount = getCouldNotCompute();
7257         else
7258           BECount =
7259               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7260         if (EL0.MaxNotTaken == getCouldNotCompute())
7261           MaxBECount = EL1.MaxNotTaken;
7262         else if (EL1.MaxNotTaken == getCouldNotCompute())
7263           MaxBECount = EL0.MaxNotTaken;
7264         else
7265           MaxBECount =
7266               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7267       } else {
7268         // Both conditions must be false at the same time for the loop to exit.
7269         // For now, be conservative.
7270         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7271           MaxBECount = EL0.MaxNotTaken;
7272         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7273           BECount = EL0.ExactNotTaken;
7274       }
7275       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7276       // to be more aggressive when computing BECount than when computing
7277       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7278       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7279       // to not.
7280       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7281           !isa<SCEVCouldNotCompute>(BECount))
7282         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7283 
7284       return ExitLimit(BECount, MaxBECount, false,
7285                        {&EL0.Predicates, &EL1.Predicates});
7286     }
7287   }
7288 
7289   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7290   // Proceed to the next level to examine the icmp.
7291   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7292     ExitLimit EL =
7293         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7294     if (EL.hasFullInfo() || !AllowPredicates)
7295       return EL;
7296 
7297     // Try again, but use SCEV predicates this time.
7298     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7299                                     /*AllowPredicates=*/true);
7300   }
7301 
7302   // Check for a constant condition. These are normally stripped out by
7303   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7304   // preserve the CFG and is temporarily leaving constant conditions
7305   // in place.
7306   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7307     if (ExitIfTrue == !CI->getZExtValue())
7308       // The backedge is always taken.
7309       return getCouldNotCompute();
7310     else
7311       // The backedge is never taken.
7312       return getZero(CI->getType());
7313   }
7314 
7315   // If it's not an integer or pointer comparison then compute it the hard way.
7316   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7317 }
7318 
7319 ScalarEvolution::ExitLimit
7320 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7321                                           ICmpInst *ExitCond,
7322                                           bool ExitIfTrue,
7323                                           bool ControlsExit,
7324                                           bool AllowPredicates) {
7325   // If the condition was exit on true, convert the condition to exit on false
7326   ICmpInst::Predicate Pred;
7327   if (!ExitIfTrue)
7328     Pred = ExitCond->getPredicate();
7329   else
7330     Pred = ExitCond->getInversePredicate();
7331   const ICmpInst::Predicate OriginalPred = Pred;
7332 
7333   // Handle common loops like: for (X = "string"; *X; ++X)
7334   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7335     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7336       ExitLimit ItCnt =
7337         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7338       if (ItCnt.hasAnyInfo())
7339         return ItCnt;
7340     }
7341 
7342   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7343   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7344 
7345   // Try to evaluate any dependencies out of the loop.
7346   LHS = getSCEVAtScope(LHS, L);
7347   RHS = getSCEVAtScope(RHS, L);
7348 
7349   // At this point, we would like to compute how many iterations of the
7350   // loop the predicate will return true for these inputs.
7351   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7352     // If there is a loop-invariant, force it into the RHS.
7353     std::swap(LHS, RHS);
7354     Pred = ICmpInst::getSwappedPredicate(Pred);
7355   }
7356 
7357   // Simplify the operands before analyzing them.
7358   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7359 
7360   // If we have a comparison of a chrec against a constant, try to use value
7361   // ranges to answer this query.
7362   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7363     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7364       if (AddRec->getLoop() == L) {
7365         // Form the constant range.
7366         ConstantRange CompRange =
7367             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7368 
7369         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7370         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7371       }
7372 
7373   switch (Pred) {
7374   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7375     // Convert to: while (X-Y != 0)
7376     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7377                                 AllowPredicates);
7378     if (EL.hasAnyInfo()) return EL;
7379     break;
7380   }
7381   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7382     // Convert to: while (X-Y == 0)
7383     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7384     if (EL.hasAnyInfo()) return EL;
7385     break;
7386   }
7387   case ICmpInst::ICMP_SLT:
7388   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7389     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7390     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7391                                     AllowPredicates);
7392     if (EL.hasAnyInfo()) return EL;
7393     break;
7394   }
7395   case ICmpInst::ICMP_SGT:
7396   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7397     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7398     ExitLimit EL =
7399         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7400                             AllowPredicates);
7401     if (EL.hasAnyInfo()) return EL;
7402     break;
7403   }
7404   default:
7405     break;
7406   }
7407 
7408   auto *ExhaustiveCount =
7409       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7410 
7411   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7412     return ExhaustiveCount;
7413 
7414   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7415                                       ExitCond->getOperand(1), L, OriginalPred);
7416 }
7417 
7418 ScalarEvolution::ExitLimit
7419 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7420                                                       SwitchInst *Switch,
7421                                                       BasicBlock *ExitingBlock,
7422                                                       bool ControlsExit) {
7423   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7424 
7425   // Give up if the exit is the default dest of a switch.
7426   if (Switch->getDefaultDest() == ExitingBlock)
7427     return getCouldNotCompute();
7428 
7429   assert(L->contains(Switch->getDefaultDest()) &&
7430          "Default case must not exit the loop!");
7431   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7432   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7433 
7434   // while (X != Y) --> while (X-Y != 0)
7435   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7436   if (EL.hasAnyInfo())
7437     return EL;
7438 
7439   return getCouldNotCompute();
7440 }
7441 
7442 static ConstantInt *
7443 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7444                                 ScalarEvolution &SE) {
7445   const SCEV *InVal = SE.getConstant(C);
7446   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7447   assert(isa<SCEVConstant>(Val) &&
7448          "Evaluation of SCEV at constant didn't fold correctly?");
7449   return cast<SCEVConstant>(Val)->getValue();
7450 }
7451 
7452 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7453 /// compute the backedge execution count.
7454 ScalarEvolution::ExitLimit
7455 ScalarEvolution::computeLoadConstantCompareExitLimit(
7456   LoadInst *LI,
7457   Constant *RHS,
7458   const Loop *L,
7459   ICmpInst::Predicate predicate) {
7460   if (LI->isVolatile()) return getCouldNotCompute();
7461 
7462   // Check to see if the loaded pointer is a getelementptr of a global.
7463   // TODO: Use SCEV instead of manually grubbing with GEPs.
7464   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7465   if (!GEP) return getCouldNotCompute();
7466 
7467   // Make sure that it is really a constant global we are gepping, with an
7468   // initializer, and make sure the first IDX is really 0.
7469   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7470   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7471       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7472       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7473     return getCouldNotCompute();
7474 
7475   // Okay, we allow one non-constant index into the GEP instruction.
7476   Value *VarIdx = nullptr;
7477   std::vector<Constant*> Indexes;
7478   unsigned VarIdxNum = 0;
7479   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7480     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7481       Indexes.push_back(CI);
7482     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7483       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7484       VarIdx = GEP->getOperand(i);
7485       VarIdxNum = i-2;
7486       Indexes.push_back(nullptr);
7487     }
7488 
7489   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7490   if (!VarIdx)
7491     return getCouldNotCompute();
7492 
7493   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7494   // Check to see if X is a loop variant variable value now.
7495   const SCEV *Idx = getSCEV(VarIdx);
7496   Idx = getSCEVAtScope(Idx, L);
7497 
7498   // We can only recognize very limited forms of loop index expressions, in
7499   // particular, only affine AddRec's like {C1,+,C2}.
7500   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7501   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7502       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7503       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7504     return getCouldNotCompute();
7505 
7506   unsigned MaxSteps = MaxBruteForceIterations;
7507   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7508     ConstantInt *ItCst = ConstantInt::get(
7509                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7510     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7511 
7512     // Form the GEP offset.
7513     Indexes[VarIdxNum] = Val;
7514 
7515     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7516                                                          Indexes);
7517     if (!Result) break;  // Cannot compute!
7518 
7519     // Evaluate the condition for this iteration.
7520     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7521     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7522     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7523       ++NumArrayLenItCounts;
7524       return getConstant(ItCst);   // Found terminating iteration!
7525     }
7526   }
7527   return getCouldNotCompute();
7528 }
7529 
7530 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7531     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7532   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7533   if (!RHS)
7534     return getCouldNotCompute();
7535 
7536   const BasicBlock *Latch = L->getLoopLatch();
7537   if (!Latch)
7538     return getCouldNotCompute();
7539 
7540   const BasicBlock *Predecessor = L->getLoopPredecessor();
7541   if (!Predecessor)
7542     return getCouldNotCompute();
7543 
7544   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7545   // Return LHS in OutLHS and shift_opt in OutOpCode.
7546   auto MatchPositiveShift =
7547       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7548 
7549     using namespace PatternMatch;
7550 
7551     ConstantInt *ShiftAmt;
7552     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7553       OutOpCode = Instruction::LShr;
7554     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7555       OutOpCode = Instruction::AShr;
7556     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7557       OutOpCode = Instruction::Shl;
7558     else
7559       return false;
7560 
7561     return ShiftAmt->getValue().isStrictlyPositive();
7562   };
7563 
7564   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7565   //
7566   // loop:
7567   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7568   //   %iv.shifted = lshr i32 %iv, <positive constant>
7569   //
7570   // Return true on a successful match.  Return the corresponding PHI node (%iv
7571   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7572   auto MatchShiftRecurrence =
7573       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7574     Optional<Instruction::BinaryOps> PostShiftOpCode;
7575 
7576     {
7577       Instruction::BinaryOps OpC;
7578       Value *V;
7579 
7580       // If we encounter a shift instruction, "peel off" the shift operation,
7581       // and remember that we did so.  Later when we inspect %iv's backedge
7582       // value, we will make sure that the backedge value uses the same
7583       // operation.
7584       //
7585       // Note: the peeled shift operation does not have to be the same
7586       // instruction as the one feeding into the PHI's backedge value.  We only
7587       // really care about it being the same *kind* of shift instruction --
7588       // that's all that is required for our later inferences to hold.
7589       if (MatchPositiveShift(LHS, V, OpC)) {
7590         PostShiftOpCode = OpC;
7591         LHS = V;
7592       }
7593     }
7594 
7595     PNOut = dyn_cast<PHINode>(LHS);
7596     if (!PNOut || PNOut->getParent() != L->getHeader())
7597       return false;
7598 
7599     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7600     Value *OpLHS;
7601 
7602     return
7603         // The backedge value for the PHI node must be a shift by a positive
7604         // amount
7605         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7606 
7607         // of the PHI node itself
7608         OpLHS == PNOut &&
7609 
7610         // and the kind of shift should be match the kind of shift we peeled
7611         // off, if any.
7612         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7613   };
7614 
7615   PHINode *PN;
7616   Instruction::BinaryOps OpCode;
7617   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7618     return getCouldNotCompute();
7619 
7620   const DataLayout &DL = getDataLayout();
7621 
7622   // The key rationale for this optimization is that for some kinds of shift
7623   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7624   // within a finite number of iterations.  If the condition guarding the
7625   // backedge (in the sense that the backedge is taken if the condition is true)
7626   // is false for the value the shift recurrence stabilizes to, then we know
7627   // that the backedge is taken only a finite number of times.
7628 
7629   ConstantInt *StableValue = nullptr;
7630   switch (OpCode) {
7631   default:
7632     llvm_unreachable("Impossible case!");
7633 
7634   case Instruction::AShr: {
7635     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7636     // bitwidth(K) iterations.
7637     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7638     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7639                                        Predecessor->getTerminator(), &DT);
7640     auto *Ty = cast<IntegerType>(RHS->getType());
7641     if (Known.isNonNegative())
7642       StableValue = ConstantInt::get(Ty, 0);
7643     else if (Known.isNegative())
7644       StableValue = ConstantInt::get(Ty, -1, true);
7645     else
7646       return getCouldNotCompute();
7647 
7648     break;
7649   }
7650   case Instruction::LShr:
7651   case Instruction::Shl:
7652     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7653     // stabilize to 0 in at most bitwidth(K) iterations.
7654     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7655     break;
7656   }
7657 
7658   auto *Result =
7659       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7660   assert(Result->getType()->isIntegerTy(1) &&
7661          "Otherwise cannot be an operand to a branch instruction");
7662 
7663   if (Result->isZeroValue()) {
7664     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7665     const SCEV *UpperBound =
7666         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7667     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7668   }
7669 
7670   return getCouldNotCompute();
7671 }
7672 
7673 /// Return true if we can constant fold an instruction of the specified type,
7674 /// assuming that all operands were constants.
7675 static bool CanConstantFold(const Instruction *I) {
7676   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7677       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7678       isa<LoadInst>(I))
7679     return true;
7680 
7681   if (const CallInst *CI = dyn_cast<CallInst>(I))
7682     if (const Function *F = CI->getCalledFunction())
7683       return canConstantFoldCallTo(CI, F);
7684   return false;
7685 }
7686 
7687 /// Determine whether this instruction can constant evolve within this loop
7688 /// assuming its operands can all constant evolve.
7689 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7690   // An instruction outside of the loop can't be derived from a loop PHI.
7691   if (!L->contains(I)) return false;
7692 
7693   if (isa<PHINode>(I)) {
7694     // We don't currently keep track of the control flow needed to evaluate
7695     // PHIs, so we cannot handle PHIs inside of loops.
7696     return L->getHeader() == I->getParent();
7697   }
7698 
7699   // If we won't be able to constant fold this expression even if the operands
7700   // are constants, bail early.
7701   return CanConstantFold(I);
7702 }
7703 
7704 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7705 /// recursing through each instruction operand until reaching a loop header phi.
7706 static PHINode *
7707 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7708                                DenseMap<Instruction *, PHINode *> &PHIMap,
7709                                unsigned Depth) {
7710   if (Depth > MaxConstantEvolvingDepth)
7711     return nullptr;
7712 
7713   // Otherwise, we can evaluate this instruction if all of its operands are
7714   // constant or derived from a PHI node themselves.
7715   PHINode *PHI = nullptr;
7716   for (Value *Op : UseInst->operands()) {
7717     if (isa<Constant>(Op)) continue;
7718 
7719     Instruction *OpInst = dyn_cast<Instruction>(Op);
7720     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7721 
7722     PHINode *P = dyn_cast<PHINode>(OpInst);
7723     if (!P)
7724       // If this operand is already visited, reuse the prior result.
7725       // We may have P != PHI if this is the deepest point at which the
7726       // inconsistent paths meet.
7727       P = PHIMap.lookup(OpInst);
7728     if (!P) {
7729       // Recurse and memoize the results, whether a phi is found or not.
7730       // This recursive call invalidates pointers into PHIMap.
7731       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7732       PHIMap[OpInst] = P;
7733     }
7734     if (!P)
7735       return nullptr;  // Not evolving from PHI
7736     if (PHI && PHI != P)
7737       return nullptr;  // Evolving from multiple different PHIs.
7738     PHI = P;
7739   }
7740   // This is a expression evolving from a constant PHI!
7741   return PHI;
7742 }
7743 
7744 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7745 /// in the loop that V is derived from.  We allow arbitrary operations along the
7746 /// way, but the operands of an operation must either be constants or a value
7747 /// derived from a constant PHI.  If this expression does not fit with these
7748 /// constraints, return null.
7749 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7750   Instruction *I = dyn_cast<Instruction>(V);
7751   if (!I || !canConstantEvolve(I, L)) return nullptr;
7752 
7753   if (PHINode *PN = dyn_cast<PHINode>(I))
7754     return PN;
7755 
7756   // Record non-constant instructions contained by the loop.
7757   DenseMap<Instruction *, PHINode *> PHIMap;
7758   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7759 }
7760 
7761 /// EvaluateExpression - Given an expression that passes the
7762 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7763 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7764 /// reason, return null.
7765 static Constant *EvaluateExpression(Value *V, const Loop *L,
7766                                     DenseMap<Instruction *, Constant *> &Vals,
7767                                     const DataLayout &DL,
7768                                     const TargetLibraryInfo *TLI) {
7769   // Convenient constant check, but redundant for recursive calls.
7770   if (Constant *C = dyn_cast<Constant>(V)) return C;
7771   Instruction *I = dyn_cast<Instruction>(V);
7772   if (!I) return nullptr;
7773 
7774   if (Constant *C = Vals.lookup(I)) return C;
7775 
7776   // An instruction inside the loop depends on a value outside the loop that we
7777   // weren't given a mapping for, or a value such as a call inside the loop.
7778   if (!canConstantEvolve(I, L)) return nullptr;
7779 
7780   // An unmapped PHI can be due to a branch or another loop inside this loop,
7781   // or due to this not being the initial iteration through a loop where we
7782   // couldn't compute the evolution of this particular PHI last time.
7783   if (isa<PHINode>(I)) return nullptr;
7784 
7785   std::vector<Constant*> Operands(I->getNumOperands());
7786 
7787   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7788     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7789     if (!Operand) {
7790       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7791       if (!Operands[i]) return nullptr;
7792       continue;
7793     }
7794     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7795     Vals[Operand] = C;
7796     if (!C) return nullptr;
7797     Operands[i] = C;
7798   }
7799 
7800   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7801     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7802                                            Operands[1], DL, TLI);
7803   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7804     if (!LI->isVolatile())
7805       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7806   }
7807   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7808 }
7809 
7810 
7811 // If every incoming value to PN except the one for BB is a specific Constant,
7812 // return that, else return nullptr.
7813 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7814   Constant *IncomingVal = nullptr;
7815 
7816   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7817     if (PN->getIncomingBlock(i) == BB)
7818       continue;
7819 
7820     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7821     if (!CurrentVal)
7822       return nullptr;
7823 
7824     if (IncomingVal != CurrentVal) {
7825       if (IncomingVal)
7826         return nullptr;
7827       IncomingVal = CurrentVal;
7828     }
7829   }
7830 
7831   return IncomingVal;
7832 }
7833 
7834 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7835 /// in the header of its containing loop, we know the loop executes a
7836 /// constant number of times, and the PHI node is just a recurrence
7837 /// involving constants, fold it.
7838 Constant *
7839 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7840                                                    const APInt &BEs,
7841                                                    const Loop *L) {
7842   auto I = ConstantEvolutionLoopExitValue.find(PN);
7843   if (I != ConstantEvolutionLoopExitValue.end())
7844     return I->second;
7845 
7846   if (BEs.ugt(MaxBruteForceIterations))
7847     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7848 
7849   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7850 
7851   DenseMap<Instruction *, Constant *> CurrentIterVals;
7852   BasicBlock *Header = L->getHeader();
7853   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7854 
7855   BasicBlock *Latch = L->getLoopLatch();
7856   if (!Latch)
7857     return nullptr;
7858 
7859   for (PHINode &PHI : Header->phis()) {
7860     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7861       CurrentIterVals[&PHI] = StartCST;
7862   }
7863   if (!CurrentIterVals.count(PN))
7864     return RetVal = nullptr;
7865 
7866   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7867 
7868   // Execute the loop symbolically to determine the exit value.
7869   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7870          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7871 
7872   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7873   unsigned IterationNum = 0;
7874   const DataLayout &DL = getDataLayout();
7875   for (; ; ++IterationNum) {
7876     if (IterationNum == NumIterations)
7877       return RetVal = CurrentIterVals[PN];  // Got exit value!
7878 
7879     // Compute the value of the PHIs for the next iteration.
7880     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7881     DenseMap<Instruction *, Constant *> NextIterVals;
7882     Constant *NextPHI =
7883         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7884     if (!NextPHI)
7885       return nullptr;        // Couldn't evaluate!
7886     NextIterVals[PN] = NextPHI;
7887 
7888     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7889 
7890     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7891     // cease to be able to evaluate one of them or if they stop evolving,
7892     // because that doesn't necessarily prevent us from computing PN.
7893     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7894     for (const auto &I : CurrentIterVals) {
7895       PHINode *PHI = dyn_cast<PHINode>(I.first);
7896       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7897       PHIsToCompute.emplace_back(PHI, I.second);
7898     }
7899     // We use two distinct loops because EvaluateExpression may invalidate any
7900     // iterators into CurrentIterVals.
7901     for (const auto &I : PHIsToCompute) {
7902       PHINode *PHI = I.first;
7903       Constant *&NextPHI = NextIterVals[PHI];
7904       if (!NextPHI) {   // Not already computed.
7905         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7906         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7907       }
7908       if (NextPHI != I.second)
7909         StoppedEvolving = false;
7910     }
7911 
7912     // If all entries in CurrentIterVals == NextIterVals then we can stop
7913     // iterating, the loop can't continue to change.
7914     if (StoppedEvolving)
7915       return RetVal = CurrentIterVals[PN];
7916 
7917     CurrentIterVals.swap(NextIterVals);
7918   }
7919 }
7920 
7921 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7922                                                           Value *Cond,
7923                                                           bool ExitWhen) {
7924   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7925   if (!PN) return getCouldNotCompute();
7926 
7927   // If the loop is canonicalized, the PHI will have exactly two entries.
7928   // That's the only form we support here.
7929   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7930 
7931   DenseMap<Instruction *, Constant *> CurrentIterVals;
7932   BasicBlock *Header = L->getHeader();
7933   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7934 
7935   BasicBlock *Latch = L->getLoopLatch();
7936   assert(Latch && "Should follow from NumIncomingValues == 2!");
7937 
7938   for (PHINode &PHI : Header->phis()) {
7939     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7940       CurrentIterVals[&PHI] = StartCST;
7941   }
7942   if (!CurrentIterVals.count(PN))
7943     return getCouldNotCompute();
7944 
7945   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7946   // the loop symbolically to determine when the condition gets a value of
7947   // "ExitWhen".
7948   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7949   const DataLayout &DL = getDataLayout();
7950   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7951     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7952         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7953 
7954     // Couldn't symbolically evaluate.
7955     if (!CondVal) return getCouldNotCompute();
7956 
7957     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7958       ++NumBruteForceTripCountsComputed;
7959       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7960     }
7961 
7962     // Update all the PHI nodes for the next iteration.
7963     DenseMap<Instruction *, Constant *> NextIterVals;
7964 
7965     // Create a list of which PHIs we need to compute. We want to do this before
7966     // calling EvaluateExpression on them because that may invalidate iterators
7967     // into CurrentIterVals.
7968     SmallVector<PHINode *, 8> PHIsToCompute;
7969     for (const auto &I : CurrentIterVals) {
7970       PHINode *PHI = dyn_cast<PHINode>(I.first);
7971       if (!PHI || PHI->getParent() != Header) continue;
7972       PHIsToCompute.push_back(PHI);
7973     }
7974     for (PHINode *PHI : PHIsToCompute) {
7975       Constant *&NextPHI = NextIterVals[PHI];
7976       if (NextPHI) continue;    // Already computed!
7977 
7978       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7979       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7980     }
7981     CurrentIterVals.swap(NextIterVals);
7982   }
7983 
7984   // Too many iterations were needed to evaluate.
7985   return getCouldNotCompute();
7986 }
7987 
7988 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7989   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7990       ValuesAtScopes[V];
7991   // Check to see if we've folded this expression at this loop before.
7992   for (auto &LS : Values)
7993     if (LS.first == L)
7994       return LS.second ? LS.second : V;
7995 
7996   Values.emplace_back(L, nullptr);
7997 
7998   // Otherwise compute it.
7999   const SCEV *C = computeSCEVAtScope(V, L);
8000   for (auto &LS : reverse(ValuesAtScopes[V]))
8001     if (LS.first == L) {
8002       LS.second = C;
8003       break;
8004     }
8005   return C;
8006 }
8007 
8008 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8009 /// will return Constants for objects which aren't represented by a
8010 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8011 /// Returns NULL if the SCEV isn't representable as a Constant.
8012 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8013   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
8014     case scCouldNotCompute:
8015     case scAddRecExpr:
8016       break;
8017     case scConstant:
8018       return cast<SCEVConstant>(V)->getValue();
8019     case scUnknown:
8020       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8021     case scSignExtend: {
8022       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8023       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8024         return ConstantExpr::getSExt(CastOp, SS->getType());
8025       break;
8026     }
8027     case scZeroExtend: {
8028       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8029       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8030         return ConstantExpr::getZExt(CastOp, SZ->getType());
8031       break;
8032     }
8033     case scTruncate: {
8034       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8035       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8036         return ConstantExpr::getTrunc(CastOp, ST->getType());
8037       break;
8038     }
8039     case scAddExpr: {
8040       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8041       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8042         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8043           unsigned AS = PTy->getAddressSpace();
8044           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8045           C = ConstantExpr::getBitCast(C, DestPtrTy);
8046         }
8047         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8048           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8049           if (!C2) return nullptr;
8050 
8051           // First pointer!
8052           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8053             unsigned AS = C2->getType()->getPointerAddressSpace();
8054             std::swap(C, C2);
8055             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8056             // The offsets have been converted to bytes.  We can add bytes to an
8057             // i8* by GEP with the byte count in the first index.
8058             C = ConstantExpr::getBitCast(C, DestPtrTy);
8059           }
8060 
8061           // Don't bother trying to sum two pointers. We probably can't
8062           // statically compute a load that results from it anyway.
8063           if (C2->getType()->isPointerTy())
8064             return nullptr;
8065 
8066           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8067             if (PTy->getElementType()->isStructTy())
8068               C2 = ConstantExpr::getIntegerCast(
8069                   C2, Type::getInt32Ty(C->getContext()), true);
8070             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8071           } else
8072             C = ConstantExpr::getAdd(C, C2);
8073         }
8074         return C;
8075       }
8076       break;
8077     }
8078     case scMulExpr: {
8079       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8080       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8081         // Don't bother with pointers at all.
8082         if (C->getType()->isPointerTy()) return nullptr;
8083         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8084           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8085           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8086           C = ConstantExpr::getMul(C, C2);
8087         }
8088         return C;
8089       }
8090       break;
8091     }
8092     case scUDivExpr: {
8093       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8094       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8095         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8096           if (LHS->getType() == RHS->getType())
8097             return ConstantExpr::getUDiv(LHS, RHS);
8098       break;
8099     }
8100     case scSMaxExpr:
8101     case scUMaxExpr:
8102       break; // TODO: smax, umax.
8103   }
8104   return nullptr;
8105 }
8106 
8107 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8108   if (isa<SCEVConstant>(V)) return V;
8109 
8110   // If this instruction is evolved from a constant-evolving PHI, compute the
8111   // exit value from the loop without using SCEVs.
8112   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8113     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8114       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8115         const Loop *LI = this->LI[I->getParent()];
8116         // Looking for loop exit value.
8117         if (LI && LI->getParentLoop() == L &&
8118             PN->getParent() == LI->getHeader()) {
8119           // Okay, there is no closed form solution for the PHI node.  Check
8120           // to see if the loop that contains it has a known backedge-taken
8121           // count.  If so, we may be able to force computation of the exit
8122           // value.
8123           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8124           if (const SCEVConstant *BTCC =
8125                 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8126 
8127             // This trivial case can show up in some degenerate cases where
8128             // the incoming IR has not yet been fully simplified.
8129             if (BTCC->getValue()->isZero()) {
8130               Value *InitValue = nullptr;
8131               bool MultipleInitValues = false;
8132               for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8133                 if (!LI->contains(PN->getIncomingBlock(i))) {
8134                   if (!InitValue)
8135                     InitValue = PN->getIncomingValue(i);
8136                   else if (InitValue != PN->getIncomingValue(i)) {
8137                     MultipleInitValues = true;
8138                     break;
8139                   }
8140                 }
8141                 if (!MultipleInitValues && InitValue)
8142                   return getSCEV(InitValue);
8143               }
8144             }
8145             // Okay, we know how many times the containing loop executes.  If
8146             // this is a constant evolving PHI node, get the final value at
8147             // the specified iteration number.
8148             Constant *RV =
8149                 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8150             if (RV) return getSCEV(RV);
8151           }
8152         }
8153       }
8154 
8155       // Okay, this is an expression that we cannot symbolically evaluate
8156       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8157       // the arguments into constants, and if so, try to constant propagate the
8158       // result.  This is particularly useful for computing loop exit values.
8159       if (CanConstantFold(I)) {
8160         SmallVector<Constant *, 4> Operands;
8161         bool MadeImprovement = false;
8162         for (Value *Op : I->operands()) {
8163           if (Constant *C = dyn_cast<Constant>(Op)) {
8164             Operands.push_back(C);
8165             continue;
8166           }
8167 
8168           // If any of the operands is non-constant and if they are
8169           // non-integer and non-pointer, don't even try to analyze them
8170           // with scev techniques.
8171           if (!isSCEVable(Op->getType()))
8172             return V;
8173 
8174           const SCEV *OrigV = getSCEV(Op);
8175           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8176           MadeImprovement |= OrigV != OpV;
8177 
8178           Constant *C = BuildConstantFromSCEV(OpV);
8179           if (!C) return V;
8180           if (C->getType() != Op->getType())
8181             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8182                                                               Op->getType(),
8183                                                               false),
8184                                       C, Op->getType());
8185           Operands.push_back(C);
8186         }
8187 
8188         // Check to see if getSCEVAtScope actually made an improvement.
8189         if (MadeImprovement) {
8190           Constant *C = nullptr;
8191           const DataLayout &DL = getDataLayout();
8192           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8193             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8194                                                 Operands[1], DL, &TLI);
8195           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8196             if (!LI->isVolatile())
8197               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8198           } else
8199             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8200           if (!C) return V;
8201           return getSCEV(C);
8202         }
8203       }
8204     }
8205 
8206     // This is some other type of SCEVUnknown, just return it.
8207     return V;
8208   }
8209 
8210   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8211     // Avoid performing the look-up in the common case where the specified
8212     // expression has no loop-variant portions.
8213     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8214       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8215       if (OpAtScope != Comm->getOperand(i)) {
8216         // Okay, at least one of these operands is loop variant but might be
8217         // foldable.  Build a new instance of the folded commutative expression.
8218         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8219                                             Comm->op_begin()+i);
8220         NewOps.push_back(OpAtScope);
8221 
8222         for (++i; i != e; ++i) {
8223           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8224           NewOps.push_back(OpAtScope);
8225         }
8226         if (isa<SCEVAddExpr>(Comm))
8227           return getAddExpr(NewOps);
8228         if (isa<SCEVMulExpr>(Comm))
8229           return getMulExpr(NewOps);
8230         if (isa<SCEVSMaxExpr>(Comm))
8231           return getSMaxExpr(NewOps);
8232         if (isa<SCEVUMaxExpr>(Comm))
8233           return getUMaxExpr(NewOps);
8234         llvm_unreachable("Unknown commutative SCEV type!");
8235       }
8236     }
8237     // If we got here, all operands are loop invariant.
8238     return Comm;
8239   }
8240 
8241   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8242     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8243     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8244     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8245       return Div;   // must be loop invariant
8246     return getUDivExpr(LHS, RHS);
8247   }
8248 
8249   // If this is a loop recurrence for a loop that does not contain L, then we
8250   // are dealing with the final value computed by the loop.
8251   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8252     // First, attempt to evaluate each operand.
8253     // Avoid performing the look-up in the common case where the specified
8254     // expression has no loop-variant portions.
8255     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8256       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8257       if (OpAtScope == AddRec->getOperand(i))
8258         continue;
8259 
8260       // Okay, at least one of these operands is loop variant but might be
8261       // foldable.  Build a new instance of the folded commutative expression.
8262       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8263                                           AddRec->op_begin()+i);
8264       NewOps.push_back(OpAtScope);
8265       for (++i; i != e; ++i)
8266         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8267 
8268       const SCEV *FoldedRec =
8269         getAddRecExpr(NewOps, AddRec->getLoop(),
8270                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8271       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8272       // The addrec may be folded to a nonrecurrence, for example, if the
8273       // induction variable is multiplied by zero after constant folding. Go
8274       // ahead and return the folded value.
8275       if (!AddRec)
8276         return FoldedRec;
8277       break;
8278     }
8279 
8280     // If the scope is outside the addrec's loop, evaluate it by using the
8281     // loop exit value of the addrec.
8282     if (!AddRec->getLoop()->contains(L)) {
8283       // To evaluate this recurrence, we need to know how many times the AddRec
8284       // loop iterates.  Compute this now.
8285       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8286       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8287 
8288       // Then, evaluate the AddRec.
8289       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8290     }
8291 
8292     return AddRec;
8293   }
8294 
8295   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8296     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8297     if (Op == Cast->getOperand())
8298       return Cast;  // must be loop invariant
8299     return getZeroExtendExpr(Op, Cast->getType());
8300   }
8301 
8302   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8303     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8304     if (Op == Cast->getOperand())
8305       return Cast;  // must be loop invariant
8306     return getSignExtendExpr(Op, Cast->getType());
8307   }
8308 
8309   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8310     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8311     if (Op == Cast->getOperand())
8312       return Cast;  // must be loop invariant
8313     return getTruncateExpr(Op, Cast->getType());
8314   }
8315 
8316   llvm_unreachable("Unknown SCEV type!");
8317 }
8318 
8319 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8320   return getSCEVAtScope(getSCEV(V), L);
8321 }
8322 
8323 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8324   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8325     return stripInjectiveFunctions(ZExt->getOperand());
8326   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8327     return stripInjectiveFunctions(SExt->getOperand());
8328   return S;
8329 }
8330 
8331 /// Finds the minimum unsigned root of the following equation:
8332 ///
8333 ///     A * X = B (mod N)
8334 ///
8335 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8336 /// A and B isn't important.
8337 ///
8338 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8339 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8340                                                ScalarEvolution &SE) {
8341   uint32_t BW = A.getBitWidth();
8342   assert(BW == SE.getTypeSizeInBits(B->getType()));
8343   assert(A != 0 && "A must be non-zero.");
8344 
8345   // 1. D = gcd(A, N)
8346   //
8347   // The gcd of A and N may have only one prime factor: 2. The number of
8348   // trailing zeros in A is its multiplicity
8349   uint32_t Mult2 = A.countTrailingZeros();
8350   // D = 2^Mult2
8351 
8352   // 2. Check if B is divisible by D.
8353   //
8354   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8355   // is not less than multiplicity of this prime factor for D.
8356   if (SE.GetMinTrailingZeros(B) < Mult2)
8357     return SE.getCouldNotCompute();
8358 
8359   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8360   // modulo (N / D).
8361   //
8362   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8363   // (N / D) in general. The inverse itself always fits into BW bits, though,
8364   // so we immediately truncate it.
8365   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8366   APInt Mod(BW + 1, 0);
8367   Mod.setBit(BW - Mult2);  // Mod = N / D
8368   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8369 
8370   // 4. Compute the minimum unsigned root of the equation:
8371   // I * (B / D) mod (N / D)
8372   // To simplify the computation, we factor out the divide by D:
8373   // (I * B mod N) / D
8374   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8375   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8376 }
8377 
8378 /// For a given quadratic addrec, generate coefficients of the corresponding
8379 /// quadratic equation, multiplied by a common value to ensure that they are
8380 /// integers.
8381 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8382 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8383 /// were multiplied by, and BitWidth is the bit width of the original addrec
8384 /// coefficients.
8385 /// This function returns None if the addrec coefficients are not compile-
8386 /// time constants.
8387 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8388 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8389   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8390   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8391   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8392   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8393   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8394                     << *AddRec << '\n');
8395 
8396   // We currently can only solve this if the coefficients are constants.
8397   if (!LC || !MC || !NC) {
8398     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8399     return None;
8400   }
8401 
8402   APInt L = LC->getAPInt();
8403   APInt M = MC->getAPInt();
8404   APInt N = NC->getAPInt();
8405   assert(!N.isNullValue() && "This is not a quadratic addrec");
8406 
8407   unsigned BitWidth = LC->getAPInt().getBitWidth();
8408   unsigned NewWidth = BitWidth + 1;
8409   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8410                     << BitWidth << '\n');
8411   // The sign-extension (as opposed to a zero-extension) here matches the
8412   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8413   N = N.sext(NewWidth);
8414   M = M.sext(NewWidth);
8415   L = L.sext(NewWidth);
8416 
8417   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8418   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8419   //   L+M, L+2M+N, L+3M+3N, ...
8420   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8421   //
8422   // The equation Acc = 0 is then
8423   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8424   // In a quadratic form it becomes:
8425   //   N n^2 + (2M-N) n + 2L = 0.
8426 
8427   APInt A = N;
8428   APInt B = 2 * M - A;
8429   APInt C = 2 * L;
8430   APInt T = APInt(NewWidth, 2);
8431   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8432                     << "x + " << C << ", coeff bw: " << NewWidth
8433                     << ", multiplied by " << T << '\n');
8434   return std::make_tuple(A, B, C, T, BitWidth);
8435 }
8436 
8437 /// Helper function to compare optional APInts:
8438 /// (a) if X and Y both exist, return min(X, Y),
8439 /// (b) if neither X nor Y exist, return None,
8440 /// (c) if exactly one of X and Y exists, return that value.
8441 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8442   if (X.hasValue() && Y.hasValue()) {
8443     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8444     APInt XW = X->sextOrSelf(W);
8445     APInt YW = Y->sextOrSelf(W);
8446     return XW.slt(YW) ? *X : *Y;
8447   }
8448   if (!X.hasValue() && !Y.hasValue())
8449     return None;
8450   return X.hasValue() ? *X : *Y;
8451 }
8452 
8453 /// Helper function to truncate an optional APInt to a given BitWidth.
8454 /// When solving addrec-related equations, it is preferable to return a value
8455 /// that has the same bit width as the original addrec's coefficients. If the
8456 /// solution fits in the original bit width, truncate it (except for i1).
8457 /// Returning a value of a different bit width may inhibit some optimizations.
8458 ///
8459 /// In general, a solution to a quadratic equation generated from an addrec
8460 /// may require BW+1 bits, where BW is the bit width of the addrec's
8461 /// coefficients. The reason is that the coefficients of the quadratic
8462 /// equation are BW+1 bits wide (to avoid truncation when converting from
8463 /// the addrec to the equation).
8464 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8465   if (!X.hasValue())
8466     return None;
8467   unsigned W = X->getBitWidth();
8468   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8469     return X->trunc(BitWidth);
8470   return X;
8471 }
8472 
8473 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8474 /// iterations. The values L, M, N are assumed to be signed, and they
8475 /// should all have the same bit widths.
8476 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8477 /// where BW is the bit width of the addrec's coefficients.
8478 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8479 /// returned as such, otherwise the bit width of the returned value may
8480 /// be greater than BW.
8481 ///
8482 /// This function returns None if
8483 /// (a) the addrec coefficients are not constant, or
8484 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8485 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8486 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8487 static Optional<APInt>
8488 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8489   APInt A, B, C, M;
8490   unsigned BitWidth;
8491   auto T = GetQuadraticEquation(AddRec);
8492   if (!T.hasValue())
8493     return None;
8494 
8495   std::tie(A, B, C, M, BitWidth) = *T;
8496   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8497   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8498   if (!X.hasValue())
8499     return None;
8500 
8501   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8502   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8503   if (!V->isZero())
8504     return None;
8505 
8506   return TruncIfPossible(X, BitWidth);
8507 }
8508 
8509 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8510 /// iterations. The values M, N are assumed to be signed, and they
8511 /// should all have the same bit widths.
8512 /// Find the least n such that c(n) does not belong to the given range,
8513 /// while c(n-1) does.
8514 ///
8515 /// This function returns None if
8516 /// (a) the addrec coefficients are not constant, or
8517 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8518 ///     bounds of the range.
8519 static Optional<APInt>
8520 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8521                           const ConstantRange &Range, ScalarEvolution &SE) {
8522   assert(AddRec->getOperand(0)->isZero() &&
8523          "Starting value of addrec should be 0");
8524   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8525                     << Range << ", addrec " << *AddRec << '\n');
8526   // This case is handled in getNumIterationsInRange. Here we can assume that
8527   // we start in the range.
8528   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8529          "Addrec's initial value should be in range");
8530 
8531   APInt A, B, C, M;
8532   unsigned BitWidth;
8533   auto T = GetQuadraticEquation(AddRec);
8534   if (!T.hasValue())
8535     return None;
8536 
8537   // Be careful about the return value: there can be two reasons for not
8538   // returning an actual number. First, if no solutions to the equations
8539   // were found, and second, if the solutions don't leave the given range.
8540   // The first case means that the actual solution is "unknown", the second
8541   // means that it's known, but not valid. If the solution is unknown, we
8542   // cannot make any conclusions.
8543   // Return a pair: the optional solution and a flag indicating if the
8544   // solution was found.
8545   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8546     // Solve for signed overflow and unsigned overflow, pick the lower
8547     // solution.
8548     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8549                       << Bound << " (before multiplying by " << M << ")\n");
8550     Bound *= M; // The quadratic equation multiplier.
8551 
8552     Optional<APInt> SO = None;
8553     if (BitWidth > 1) {
8554       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8555                            "signed overflow\n");
8556       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8557     }
8558     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8559                          "unsigned overflow\n");
8560     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8561                                                               BitWidth+1);
8562 
8563     auto LeavesRange = [&] (const APInt &X) {
8564       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8565       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8566       if (Range.contains(V0->getValue()))
8567         return false;
8568       // X should be at least 1, so X-1 is non-negative.
8569       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8570       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8571       if (Range.contains(V1->getValue()))
8572         return true;
8573       return false;
8574     };
8575 
8576     // If SolveQuadraticEquationWrap returns None, it means that there can
8577     // be a solution, but the function failed to find it. We cannot treat it
8578     // as "no solution".
8579     if (!SO.hasValue() || !UO.hasValue())
8580       return { None, false };
8581 
8582     // Check the smaller value first to see if it leaves the range.
8583     // At this point, both SO and UO must have values.
8584     Optional<APInt> Min = MinOptional(SO, UO);
8585     if (LeavesRange(*Min))
8586       return { Min, true };
8587     Optional<APInt> Max = Min == SO ? UO : SO;
8588     if (LeavesRange(*Max))
8589       return { Max, true };
8590 
8591     // Solutions were found, but were eliminated, hence the "true".
8592     return { None, true };
8593   };
8594 
8595   std::tie(A, B, C, M, BitWidth) = *T;
8596   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8597   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8598   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8599   auto SL = SolveForBoundary(Lower);
8600   auto SU = SolveForBoundary(Upper);
8601   // If any of the solutions was unknown, no meaninigful conclusions can
8602   // be made.
8603   if (!SL.second || !SU.second)
8604     return None;
8605 
8606   // Claim: The correct solution is not some value between Min and Max.
8607   //
8608   // Justification: Assuming that Min and Max are different values, one of
8609   // them is when the first signed overflow happens, the other is when the
8610   // first unsigned overflow happens. Crossing the range boundary is only
8611   // possible via an overflow (treating 0 as a special case of it, modeling
8612   // an overflow as crossing k*2^W for some k).
8613   //
8614   // The interesting case here is when Min was eliminated as an invalid
8615   // solution, but Max was not. The argument is that if there was another
8616   // overflow between Min and Max, it would also have been eliminated if
8617   // it was considered.
8618   //
8619   // For a given boundary, it is possible to have two overflows of the same
8620   // type (signed/unsigned) without having the other type in between: this
8621   // can happen when the vertex of the parabola is between the iterations
8622   // corresponding to the overflows. This is only possible when the two
8623   // overflows cross k*2^W for the same k. In such case, if the second one
8624   // left the range (and was the first one to do so), the first overflow
8625   // would have to enter the range, which would mean that either we had left
8626   // the range before or that we started outside of it. Both of these cases
8627   // are contradictions.
8628   //
8629   // Claim: In the case where SolveForBoundary returns None, the correct
8630   // solution is not some value between the Max for this boundary and the
8631   // Min of the other boundary.
8632   //
8633   // Justification: Assume that we had such Max_A and Min_B corresponding
8634   // to range boundaries A and B and such that Max_A < Min_B. If there was
8635   // a solution between Max_A and Min_B, it would have to be caused by an
8636   // overflow corresponding to either A or B. It cannot correspond to B,
8637   // since Min_B is the first occurrence of such an overflow. If it
8638   // corresponded to A, it would have to be either a signed or an unsigned
8639   // overflow that is larger than both eliminated overflows for A. But
8640   // between the eliminated overflows and this overflow, the values would
8641   // cover the entire value space, thus crossing the other boundary, which
8642   // is a contradiction.
8643 
8644   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8645 }
8646 
8647 ScalarEvolution::ExitLimit
8648 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8649                               bool AllowPredicates) {
8650 
8651   // This is only used for loops with a "x != y" exit test. The exit condition
8652   // is now expressed as a single expression, V = x-y. So the exit test is
8653   // effectively V != 0.  We know and take advantage of the fact that this
8654   // expression only being used in a comparison by zero context.
8655 
8656   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8657   // If the value is a constant
8658   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8659     // If the value is already zero, the branch will execute zero times.
8660     if (C->getValue()->isZero()) return C;
8661     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8662   }
8663 
8664   const SCEVAddRecExpr *AddRec =
8665       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8666 
8667   if (!AddRec && AllowPredicates)
8668     // Try to make this an AddRec using runtime tests, in the first X
8669     // iterations of this loop, where X is the SCEV expression found by the
8670     // algorithm below.
8671     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8672 
8673   if (!AddRec || AddRec->getLoop() != L)
8674     return getCouldNotCompute();
8675 
8676   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8677   // the quadratic equation to solve it.
8678   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8679     // We can only use this value if the chrec ends up with an exact zero
8680     // value at this index.  When solving for "X*X != 5", for example, we
8681     // should not accept a root of 2.
8682     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8683       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8684       return ExitLimit(R, R, false, Predicates);
8685     }
8686     return getCouldNotCompute();
8687   }
8688 
8689   // Otherwise we can only handle this if it is affine.
8690   if (!AddRec->isAffine())
8691     return getCouldNotCompute();
8692 
8693   // If this is an affine expression, the execution count of this branch is
8694   // the minimum unsigned root of the following equation:
8695   //
8696   //     Start + Step*N = 0 (mod 2^BW)
8697   //
8698   // equivalent to:
8699   //
8700   //             Step*N = -Start (mod 2^BW)
8701   //
8702   // where BW is the common bit width of Start and Step.
8703 
8704   // Get the initial value for the loop.
8705   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8706   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8707 
8708   // For now we handle only constant steps.
8709   //
8710   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8711   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8712   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8713   // We have not yet seen any such cases.
8714   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8715   if (!StepC || StepC->getValue()->isZero())
8716     return getCouldNotCompute();
8717 
8718   // For positive steps (counting up until unsigned overflow):
8719   //   N = -Start/Step (as unsigned)
8720   // For negative steps (counting down to zero):
8721   //   N = Start/-Step
8722   // First compute the unsigned distance from zero in the direction of Step.
8723   bool CountDown = StepC->getAPInt().isNegative();
8724   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8725 
8726   // Handle unitary steps, which cannot wraparound.
8727   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8728   //   N = Distance (as unsigned)
8729   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8730     APInt MaxBECount = getUnsignedRangeMax(Distance);
8731 
8732     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8733     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8734     // case, and see if we can improve the bound.
8735     //
8736     // Explicitly handling this here is necessary because getUnsignedRange
8737     // isn't context-sensitive; it doesn't know that we only care about the
8738     // range inside the loop.
8739     const SCEV *Zero = getZero(Distance->getType());
8740     const SCEV *One = getOne(Distance->getType());
8741     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8742     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8743       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8744       // as "unsigned_max(Distance + 1) - 1".
8745       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8746       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8747     }
8748     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8749   }
8750 
8751   // If the condition controls loop exit (the loop exits only if the expression
8752   // is true) and the addition is no-wrap we can use unsigned divide to
8753   // compute the backedge count.  In this case, the step may not divide the
8754   // distance, but we don't care because if the condition is "missed" the loop
8755   // will have undefined behavior due to wrapping.
8756   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8757       loopHasNoAbnormalExits(AddRec->getLoop())) {
8758     const SCEV *Exact =
8759         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8760     const SCEV *Max =
8761         Exact == getCouldNotCompute()
8762             ? Exact
8763             : getConstant(getUnsignedRangeMax(Exact));
8764     return ExitLimit(Exact, Max, false, Predicates);
8765   }
8766 
8767   // Solve the general equation.
8768   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8769                                                getNegativeSCEV(Start), *this);
8770   const SCEV *M = E == getCouldNotCompute()
8771                       ? E
8772                       : getConstant(getUnsignedRangeMax(E));
8773   return ExitLimit(E, M, false, Predicates);
8774 }
8775 
8776 ScalarEvolution::ExitLimit
8777 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8778   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8779   // handle them yet except for the trivial case.  This could be expanded in the
8780   // future as needed.
8781 
8782   // If the value is a constant, check to see if it is known to be non-zero
8783   // already.  If so, the backedge will execute zero times.
8784   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8785     if (!C->getValue()->isZero())
8786       return getZero(C->getType());
8787     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8788   }
8789 
8790   // We could implement others, but I really doubt anyone writes loops like
8791   // this, and if they did, they would already be constant folded.
8792   return getCouldNotCompute();
8793 }
8794 
8795 std::pair<BasicBlock *, BasicBlock *>
8796 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8797   // If the block has a unique predecessor, then there is no path from the
8798   // predecessor to the block that does not go through the direct edge
8799   // from the predecessor to the block.
8800   if (BasicBlock *Pred = BB->getSinglePredecessor())
8801     return {Pred, BB};
8802 
8803   // A loop's header is defined to be a block that dominates the loop.
8804   // If the header has a unique predecessor outside the loop, it must be
8805   // a block that has exactly one successor that can reach the loop.
8806   if (Loop *L = LI.getLoopFor(BB))
8807     return {L->getLoopPredecessor(), L->getHeader()};
8808 
8809   return {nullptr, nullptr};
8810 }
8811 
8812 /// SCEV structural equivalence is usually sufficient for testing whether two
8813 /// expressions are equal, however for the purposes of looking for a condition
8814 /// guarding a loop, it can be useful to be a little more general, since a
8815 /// front-end may have replicated the controlling expression.
8816 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8817   // Quick check to see if they are the same SCEV.
8818   if (A == B) return true;
8819 
8820   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8821     // Not all instructions that are "identical" compute the same value.  For
8822     // instance, two distinct alloca instructions allocating the same type are
8823     // identical and do not read memory; but compute distinct values.
8824     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8825   };
8826 
8827   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8828   // two different instructions with the same value. Check for this case.
8829   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8830     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8831       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8832         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8833           if (ComputesEqualValues(AI, BI))
8834             return true;
8835 
8836   // Otherwise assume they may have a different value.
8837   return false;
8838 }
8839 
8840 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8841                                            const SCEV *&LHS, const SCEV *&RHS,
8842                                            unsigned Depth) {
8843   bool Changed = false;
8844   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8845   // '0 != 0'.
8846   auto TrivialCase = [&](bool TriviallyTrue) {
8847     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8848     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8849     return true;
8850   };
8851   // If we hit the max recursion limit bail out.
8852   if (Depth >= 3)
8853     return false;
8854 
8855   // Canonicalize a constant to the right side.
8856   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8857     // Check for both operands constant.
8858     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8859       if (ConstantExpr::getICmp(Pred,
8860                                 LHSC->getValue(),
8861                                 RHSC->getValue())->isNullValue())
8862         return TrivialCase(false);
8863       else
8864         return TrivialCase(true);
8865     }
8866     // Otherwise swap the operands to put the constant on the right.
8867     std::swap(LHS, RHS);
8868     Pred = ICmpInst::getSwappedPredicate(Pred);
8869     Changed = true;
8870   }
8871 
8872   // If we're comparing an addrec with a value which is loop-invariant in the
8873   // addrec's loop, put the addrec on the left. Also make a dominance check,
8874   // as both operands could be addrecs loop-invariant in each other's loop.
8875   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8876     const Loop *L = AR->getLoop();
8877     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8878       std::swap(LHS, RHS);
8879       Pred = ICmpInst::getSwappedPredicate(Pred);
8880       Changed = true;
8881     }
8882   }
8883 
8884   // If there's a constant operand, canonicalize comparisons with boundary
8885   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8886   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8887     const APInt &RA = RC->getAPInt();
8888 
8889     bool SimplifiedByConstantRange = false;
8890 
8891     if (!ICmpInst::isEquality(Pred)) {
8892       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8893       if (ExactCR.isFullSet())
8894         return TrivialCase(true);
8895       else if (ExactCR.isEmptySet())
8896         return TrivialCase(false);
8897 
8898       APInt NewRHS;
8899       CmpInst::Predicate NewPred;
8900       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8901           ICmpInst::isEquality(NewPred)) {
8902         // We were able to convert an inequality to an equality.
8903         Pred = NewPred;
8904         RHS = getConstant(NewRHS);
8905         Changed = SimplifiedByConstantRange = true;
8906       }
8907     }
8908 
8909     if (!SimplifiedByConstantRange) {
8910       switch (Pred) {
8911       default:
8912         break;
8913       case ICmpInst::ICMP_EQ:
8914       case ICmpInst::ICMP_NE:
8915         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8916         if (!RA)
8917           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8918             if (const SCEVMulExpr *ME =
8919                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8920               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8921                   ME->getOperand(0)->isAllOnesValue()) {
8922                 RHS = AE->getOperand(1);
8923                 LHS = ME->getOperand(1);
8924                 Changed = true;
8925               }
8926         break;
8927 
8928 
8929         // The "Should have been caught earlier!" messages refer to the fact
8930         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8931         // should have fired on the corresponding cases, and canonicalized the
8932         // check to trivial case.
8933 
8934       case ICmpInst::ICMP_UGE:
8935         assert(!RA.isMinValue() && "Should have been caught earlier!");
8936         Pred = ICmpInst::ICMP_UGT;
8937         RHS = getConstant(RA - 1);
8938         Changed = true;
8939         break;
8940       case ICmpInst::ICMP_ULE:
8941         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8942         Pred = ICmpInst::ICMP_ULT;
8943         RHS = getConstant(RA + 1);
8944         Changed = true;
8945         break;
8946       case ICmpInst::ICMP_SGE:
8947         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8948         Pred = ICmpInst::ICMP_SGT;
8949         RHS = getConstant(RA - 1);
8950         Changed = true;
8951         break;
8952       case ICmpInst::ICMP_SLE:
8953         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8954         Pred = ICmpInst::ICMP_SLT;
8955         RHS = getConstant(RA + 1);
8956         Changed = true;
8957         break;
8958       }
8959     }
8960   }
8961 
8962   // Check for obvious equality.
8963   if (HasSameValue(LHS, RHS)) {
8964     if (ICmpInst::isTrueWhenEqual(Pred))
8965       return TrivialCase(true);
8966     if (ICmpInst::isFalseWhenEqual(Pred))
8967       return TrivialCase(false);
8968   }
8969 
8970   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8971   // adding or subtracting 1 from one of the operands.
8972   switch (Pred) {
8973   case ICmpInst::ICMP_SLE:
8974     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8975       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8976                        SCEV::FlagNSW);
8977       Pred = ICmpInst::ICMP_SLT;
8978       Changed = true;
8979     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8980       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8981                        SCEV::FlagNSW);
8982       Pred = ICmpInst::ICMP_SLT;
8983       Changed = true;
8984     }
8985     break;
8986   case ICmpInst::ICMP_SGE:
8987     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8988       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8989                        SCEV::FlagNSW);
8990       Pred = ICmpInst::ICMP_SGT;
8991       Changed = true;
8992     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8993       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8994                        SCEV::FlagNSW);
8995       Pred = ICmpInst::ICMP_SGT;
8996       Changed = true;
8997     }
8998     break;
8999   case ICmpInst::ICMP_ULE:
9000     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9001       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9002                        SCEV::FlagNUW);
9003       Pred = ICmpInst::ICMP_ULT;
9004       Changed = true;
9005     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9006       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9007       Pred = ICmpInst::ICMP_ULT;
9008       Changed = true;
9009     }
9010     break;
9011   case ICmpInst::ICMP_UGE:
9012     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9013       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9014       Pred = ICmpInst::ICMP_UGT;
9015       Changed = true;
9016     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9017       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9018                        SCEV::FlagNUW);
9019       Pred = ICmpInst::ICMP_UGT;
9020       Changed = true;
9021     }
9022     break;
9023   default:
9024     break;
9025   }
9026 
9027   // TODO: More simplifications are possible here.
9028 
9029   // Recursively simplify until we either hit a recursion limit or nothing
9030   // changes.
9031   if (Changed)
9032     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9033 
9034   return Changed;
9035 }
9036 
9037 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9038   return getSignedRangeMax(S).isNegative();
9039 }
9040 
9041 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9042   return getSignedRangeMin(S).isStrictlyPositive();
9043 }
9044 
9045 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9046   return !getSignedRangeMin(S).isNegative();
9047 }
9048 
9049 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9050   return !getSignedRangeMax(S).isStrictlyPositive();
9051 }
9052 
9053 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9054   return isKnownNegative(S) || isKnownPositive(S);
9055 }
9056 
9057 std::pair<const SCEV *, const SCEV *>
9058 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9059   // Compute SCEV on entry of loop L.
9060   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9061   if (Start == getCouldNotCompute())
9062     return { Start, Start };
9063   // Compute post increment SCEV for loop L.
9064   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9065   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9066   return { Start, PostInc };
9067 }
9068 
9069 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9070                                           const SCEV *LHS, const SCEV *RHS) {
9071   // First collect all loops.
9072   SmallPtrSet<const Loop *, 8> LoopsUsed;
9073   getUsedLoops(LHS, LoopsUsed);
9074   getUsedLoops(RHS, LoopsUsed);
9075 
9076   if (LoopsUsed.empty())
9077     return false;
9078 
9079   // Domination relationship must be a linear order on collected loops.
9080 #ifndef NDEBUG
9081   for (auto *L1 : LoopsUsed)
9082     for (auto *L2 : LoopsUsed)
9083       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9084               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9085              "Domination relationship is not a linear order");
9086 #endif
9087 
9088   const Loop *MDL =
9089       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9090                         [&](const Loop *L1, const Loop *L2) {
9091          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9092        });
9093 
9094   // Get init and post increment value for LHS.
9095   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9096   // if LHS contains unknown non-invariant SCEV then bail out.
9097   if (SplitLHS.first == getCouldNotCompute())
9098     return false;
9099   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9100   // Get init and post increment value for RHS.
9101   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9102   // if RHS contains unknown non-invariant SCEV then bail out.
9103   if (SplitRHS.first == getCouldNotCompute())
9104     return false;
9105   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9106   // It is possible that init SCEV contains an invariant load but it does
9107   // not dominate MDL and is not available at MDL loop entry, so we should
9108   // check it here.
9109   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9110       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9111     return false;
9112 
9113   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9114          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9115                                      SplitRHS.second);
9116 }
9117 
9118 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9119                                        const SCEV *LHS, const SCEV *RHS) {
9120   // Canonicalize the inputs first.
9121   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9122 
9123   if (isKnownViaInduction(Pred, LHS, RHS))
9124     return true;
9125 
9126   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9127     return true;
9128 
9129   // Otherwise see what can be done with some simple reasoning.
9130   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9131 }
9132 
9133 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9134                                               const SCEVAddRecExpr *LHS,
9135                                               const SCEV *RHS) {
9136   const Loop *L = LHS->getLoop();
9137   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9138          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9139 }
9140 
9141 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9142                                            ICmpInst::Predicate Pred,
9143                                            bool &Increasing) {
9144   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9145 
9146 #ifndef NDEBUG
9147   // Verify an invariant: inverting the predicate should turn a monotonically
9148   // increasing change to a monotonically decreasing one, and vice versa.
9149   bool IncreasingSwapped;
9150   bool ResultSwapped = isMonotonicPredicateImpl(
9151       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9152 
9153   assert(Result == ResultSwapped && "should be able to analyze both!");
9154   if (ResultSwapped)
9155     assert(Increasing == !IncreasingSwapped &&
9156            "monotonicity should flip as we flip the predicate");
9157 #endif
9158 
9159   return Result;
9160 }
9161 
9162 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9163                                                ICmpInst::Predicate Pred,
9164                                                bool &Increasing) {
9165 
9166   // A zero step value for LHS means the induction variable is essentially a
9167   // loop invariant value. We don't really depend on the predicate actually
9168   // flipping from false to true (for increasing predicates, and the other way
9169   // around for decreasing predicates), all we care about is that *if* the
9170   // predicate changes then it only changes from false to true.
9171   //
9172   // A zero step value in itself is not very useful, but there may be places
9173   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9174   // as general as possible.
9175 
9176   switch (Pred) {
9177   default:
9178     return false; // Conservative answer
9179 
9180   case ICmpInst::ICMP_UGT:
9181   case ICmpInst::ICMP_UGE:
9182   case ICmpInst::ICMP_ULT:
9183   case ICmpInst::ICMP_ULE:
9184     if (!LHS->hasNoUnsignedWrap())
9185       return false;
9186 
9187     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9188     return true;
9189 
9190   case ICmpInst::ICMP_SGT:
9191   case ICmpInst::ICMP_SGE:
9192   case ICmpInst::ICMP_SLT:
9193   case ICmpInst::ICMP_SLE: {
9194     if (!LHS->hasNoSignedWrap())
9195       return false;
9196 
9197     const SCEV *Step = LHS->getStepRecurrence(*this);
9198 
9199     if (isKnownNonNegative(Step)) {
9200       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9201       return true;
9202     }
9203 
9204     if (isKnownNonPositive(Step)) {
9205       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9206       return true;
9207     }
9208 
9209     return false;
9210   }
9211 
9212   }
9213 
9214   llvm_unreachable("switch has default clause!");
9215 }
9216 
9217 bool ScalarEvolution::isLoopInvariantPredicate(
9218     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9219     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9220     const SCEV *&InvariantRHS) {
9221 
9222   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9223   if (!isLoopInvariant(RHS, L)) {
9224     if (!isLoopInvariant(LHS, L))
9225       return false;
9226 
9227     std::swap(LHS, RHS);
9228     Pred = ICmpInst::getSwappedPredicate(Pred);
9229   }
9230 
9231   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9232   if (!ArLHS || ArLHS->getLoop() != L)
9233     return false;
9234 
9235   bool Increasing;
9236   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9237     return false;
9238 
9239   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9240   // true as the loop iterates, and the backedge is control dependent on
9241   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9242   //
9243   //   * if the predicate was false in the first iteration then the predicate
9244   //     is never evaluated again, since the loop exits without taking the
9245   //     backedge.
9246   //   * if the predicate was true in the first iteration then it will
9247   //     continue to be true for all future iterations since it is
9248   //     monotonically increasing.
9249   //
9250   // For both the above possibilities, we can replace the loop varying
9251   // predicate with its value on the first iteration of the loop (which is
9252   // loop invariant).
9253   //
9254   // A similar reasoning applies for a monotonically decreasing predicate, by
9255   // replacing true with false and false with true in the above two bullets.
9256 
9257   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9258 
9259   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9260     return false;
9261 
9262   InvariantPred = Pred;
9263   InvariantLHS = ArLHS->getStart();
9264   InvariantRHS = RHS;
9265   return true;
9266 }
9267 
9268 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9269     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9270   if (HasSameValue(LHS, RHS))
9271     return ICmpInst::isTrueWhenEqual(Pred);
9272 
9273   // This code is split out from isKnownPredicate because it is called from
9274   // within isLoopEntryGuardedByCond.
9275 
9276   auto CheckRanges =
9277       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9278     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9279         .contains(RangeLHS);
9280   };
9281 
9282   // The check at the top of the function catches the case where the values are
9283   // known to be equal.
9284   if (Pred == CmpInst::ICMP_EQ)
9285     return false;
9286 
9287   if (Pred == CmpInst::ICMP_NE)
9288     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9289            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9290            isKnownNonZero(getMinusSCEV(LHS, RHS));
9291 
9292   if (CmpInst::isSigned(Pred))
9293     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9294 
9295   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9296 }
9297 
9298 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9299                                                     const SCEV *LHS,
9300                                                     const SCEV *RHS) {
9301   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9302   // Return Y via OutY.
9303   auto MatchBinaryAddToConst =
9304       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9305              SCEV::NoWrapFlags ExpectedFlags) {
9306     const SCEV *NonConstOp, *ConstOp;
9307     SCEV::NoWrapFlags FlagsPresent;
9308 
9309     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9310         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9311       return false;
9312 
9313     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9314     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9315   };
9316 
9317   APInt C;
9318 
9319   switch (Pred) {
9320   default:
9321     break;
9322 
9323   case ICmpInst::ICMP_SGE:
9324     std::swap(LHS, RHS);
9325     LLVM_FALLTHROUGH;
9326   case ICmpInst::ICMP_SLE:
9327     // X s<= (X + C)<nsw> if C >= 0
9328     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9329       return true;
9330 
9331     // (X + C)<nsw> s<= X if C <= 0
9332     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9333         !C.isStrictlyPositive())
9334       return true;
9335     break;
9336 
9337   case ICmpInst::ICMP_SGT:
9338     std::swap(LHS, RHS);
9339     LLVM_FALLTHROUGH;
9340   case ICmpInst::ICMP_SLT:
9341     // X s< (X + C)<nsw> if C > 0
9342     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9343         C.isStrictlyPositive())
9344       return true;
9345 
9346     // (X + C)<nsw> s< X if C < 0
9347     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9348       return true;
9349     break;
9350   }
9351 
9352   return false;
9353 }
9354 
9355 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9356                                                    const SCEV *LHS,
9357                                                    const SCEV *RHS) {
9358   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9359     return false;
9360 
9361   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9362   // the stack can result in exponential time complexity.
9363   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9364 
9365   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9366   //
9367   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9368   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9369   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9370   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9371   // use isKnownPredicate later if needed.
9372   return isKnownNonNegative(RHS) &&
9373          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9374          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9375 }
9376 
9377 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9378                                         ICmpInst::Predicate Pred,
9379                                         const SCEV *LHS, const SCEV *RHS) {
9380   // No need to even try if we know the module has no guards.
9381   if (!HasGuards)
9382     return false;
9383 
9384   return any_of(*BB, [&](Instruction &I) {
9385     using namespace llvm::PatternMatch;
9386 
9387     Value *Condition;
9388     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9389                          m_Value(Condition))) &&
9390            isImpliedCond(Pred, LHS, RHS, Condition, false);
9391   });
9392 }
9393 
9394 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9395 /// protected by a conditional between LHS and RHS.  This is used to
9396 /// to eliminate casts.
9397 bool
9398 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9399                                              ICmpInst::Predicate Pred,
9400                                              const SCEV *LHS, const SCEV *RHS) {
9401   // Interpret a null as meaning no loop, where there is obviously no guard
9402   // (interprocedural conditions notwithstanding).
9403   if (!L) return true;
9404 
9405   if (VerifyIR)
9406     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9407            "This cannot be done on broken IR!");
9408 
9409 
9410   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9411     return true;
9412 
9413   BasicBlock *Latch = L->getLoopLatch();
9414   if (!Latch)
9415     return false;
9416 
9417   BranchInst *LoopContinuePredicate =
9418     dyn_cast<BranchInst>(Latch->getTerminator());
9419   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9420       isImpliedCond(Pred, LHS, RHS,
9421                     LoopContinuePredicate->getCondition(),
9422                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9423     return true;
9424 
9425   // We don't want more than one activation of the following loops on the stack
9426   // -- that can lead to O(n!) time complexity.
9427   if (WalkingBEDominatingConds)
9428     return false;
9429 
9430   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9431 
9432   // See if we can exploit a trip count to prove the predicate.
9433   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9434   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9435   if (LatchBECount != getCouldNotCompute()) {
9436     // We know that Latch branches back to the loop header exactly
9437     // LatchBECount times.  This means the backdege condition at Latch is
9438     // equivalent to  "{0,+,1} u< LatchBECount".
9439     Type *Ty = LatchBECount->getType();
9440     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9441     const SCEV *LoopCounter =
9442       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9443     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9444                       LatchBECount))
9445       return true;
9446   }
9447 
9448   // Check conditions due to any @llvm.assume intrinsics.
9449   for (auto &AssumeVH : AC.assumptions()) {
9450     if (!AssumeVH)
9451       continue;
9452     auto *CI = cast<CallInst>(AssumeVH);
9453     if (!DT.dominates(CI, Latch->getTerminator()))
9454       continue;
9455 
9456     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9457       return true;
9458   }
9459 
9460   // If the loop is not reachable from the entry block, we risk running into an
9461   // infinite loop as we walk up into the dom tree.  These loops do not matter
9462   // anyway, so we just return a conservative answer when we see them.
9463   if (!DT.isReachableFromEntry(L->getHeader()))
9464     return false;
9465 
9466   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9467     return true;
9468 
9469   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9470        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9471     assert(DTN && "should reach the loop header before reaching the root!");
9472 
9473     BasicBlock *BB = DTN->getBlock();
9474     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9475       return true;
9476 
9477     BasicBlock *PBB = BB->getSinglePredecessor();
9478     if (!PBB)
9479       continue;
9480 
9481     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9482     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9483       continue;
9484 
9485     Value *Condition = ContinuePredicate->getCondition();
9486 
9487     // If we have an edge `E` within the loop body that dominates the only
9488     // latch, the condition guarding `E` also guards the backedge.  This
9489     // reasoning works only for loops with a single latch.
9490 
9491     BasicBlockEdge DominatingEdge(PBB, BB);
9492     if (DominatingEdge.isSingleEdge()) {
9493       // We're constructively (and conservatively) enumerating edges within the
9494       // loop body that dominate the latch.  The dominator tree better agree
9495       // with us on this:
9496       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9497 
9498       if (isImpliedCond(Pred, LHS, RHS, Condition,
9499                         BB != ContinuePredicate->getSuccessor(0)))
9500         return true;
9501     }
9502   }
9503 
9504   return false;
9505 }
9506 
9507 bool
9508 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9509                                           ICmpInst::Predicate Pred,
9510                                           const SCEV *LHS, const SCEV *RHS) {
9511   // Interpret a null as meaning no loop, where there is obviously no guard
9512   // (interprocedural conditions notwithstanding).
9513   if (!L) return false;
9514 
9515   if (VerifyIR)
9516     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9517            "This cannot be done on broken IR!");
9518 
9519   // Both LHS and RHS must be available at loop entry.
9520   assert(isAvailableAtLoopEntry(LHS, L) &&
9521          "LHS is not available at Loop Entry");
9522   assert(isAvailableAtLoopEntry(RHS, L) &&
9523          "RHS is not available at Loop Entry");
9524 
9525   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9526     return true;
9527 
9528   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9529   // the facts (a >= b && a != b) separately. A typical situation is when the
9530   // non-strict comparison is known from ranges and non-equality is known from
9531   // dominating predicates. If we are proving strict comparison, we always try
9532   // to prove non-equality and non-strict comparison separately.
9533   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9534   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9535   bool ProvedNonStrictComparison = false;
9536   bool ProvedNonEquality = false;
9537 
9538   if (ProvingStrictComparison) {
9539     ProvedNonStrictComparison =
9540         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9541     ProvedNonEquality =
9542         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9543     if (ProvedNonStrictComparison && ProvedNonEquality)
9544       return true;
9545   }
9546 
9547   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9548   auto ProveViaGuard = [&](BasicBlock *Block) {
9549     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9550       return true;
9551     if (ProvingStrictComparison) {
9552       if (!ProvedNonStrictComparison)
9553         ProvedNonStrictComparison =
9554             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9555       if (!ProvedNonEquality)
9556         ProvedNonEquality =
9557             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9558       if (ProvedNonStrictComparison && ProvedNonEquality)
9559         return true;
9560     }
9561     return false;
9562   };
9563 
9564   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9565   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9566     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9567       return true;
9568     if (ProvingStrictComparison) {
9569       if (!ProvedNonStrictComparison)
9570         ProvedNonStrictComparison =
9571             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9572       if (!ProvedNonEquality)
9573         ProvedNonEquality =
9574             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9575       if (ProvedNonStrictComparison && ProvedNonEquality)
9576         return true;
9577     }
9578     return false;
9579   };
9580 
9581   // Starting at the loop predecessor, climb up the predecessor chain, as long
9582   // as there are predecessors that can be found that have unique successors
9583   // leading to the original header.
9584   for (std::pair<BasicBlock *, BasicBlock *>
9585          Pair(L->getLoopPredecessor(), L->getHeader());
9586        Pair.first;
9587        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9588 
9589     if (ProveViaGuard(Pair.first))
9590       return true;
9591 
9592     BranchInst *LoopEntryPredicate =
9593       dyn_cast<BranchInst>(Pair.first->getTerminator());
9594     if (!LoopEntryPredicate ||
9595         LoopEntryPredicate->isUnconditional())
9596       continue;
9597 
9598     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9599                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9600       return true;
9601   }
9602 
9603   // Check conditions due to any @llvm.assume intrinsics.
9604   for (auto &AssumeVH : AC.assumptions()) {
9605     if (!AssumeVH)
9606       continue;
9607     auto *CI = cast<CallInst>(AssumeVH);
9608     if (!DT.dominates(CI, L->getHeader()))
9609       continue;
9610 
9611     if (ProveViaCond(CI->getArgOperand(0), false))
9612       return true;
9613   }
9614 
9615   return false;
9616 }
9617 
9618 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9619                                     const SCEV *LHS, const SCEV *RHS,
9620                                     Value *FoundCondValue,
9621                                     bool Inverse) {
9622   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9623     return false;
9624 
9625   auto ClearOnExit =
9626       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9627 
9628   // Recursively handle And and Or conditions.
9629   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9630     if (BO->getOpcode() == Instruction::And) {
9631       if (!Inverse)
9632         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9633                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9634     } else if (BO->getOpcode() == Instruction::Or) {
9635       if (Inverse)
9636         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9637                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9638     }
9639   }
9640 
9641   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9642   if (!ICI) return false;
9643 
9644   // Now that we found a conditional branch that dominates the loop or controls
9645   // the loop latch. Check to see if it is the comparison we are looking for.
9646   ICmpInst::Predicate FoundPred;
9647   if (Inverse)
9648     FoundPred = ICI->getInversePredicate();
9649   else
9650     FoundPred = ICI->getPredicate();
9651 
9652   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9653   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9654 
9655   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9656 }
9657 
9658 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9659                                     const SCEV *RHS,
9660                                     ICmpInst::Predicate FoundPred,
9661                                     const SCEV *FoundLHS,
9662                                     const SCEV *FoundRHS) {
9663   // Balance the types.
9664   if (getTypeSizeInBits(LHS->getType()) <
9665       getTypeSizeInBits(FoundLHS->getType())) {
9666     if (CmpInst::isSigned(Pred)) {
9667       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9668       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9669     } else {
9670       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9671       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9672     }
9673   } else if (getTypeSizeInBits(LHS->getType()) >
9674       getTypeSizeInBits(FoundLHS->getType())) {
9675     if (CmpInst::isSigned(FoundPred)) {
9676       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9677       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9678     } else {
9679       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9680       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9681     }
9682   }
9683 
9684   // Canonicalize the query to match the way instcombine will have
9685   // canonicalized the comparison.
9686   if (SimplifyICmpOperands(Pred, LHS, RHS))
9687     if (LHS == RHS)
9688       return CmpInst::isTrueWhenEqual(Pred);
9689   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9690     if (FoundLHS == FoundRHS)
9691       return CmpInst::isFalseWhenEqual(FoundPred);
9692 
9693   // Check to see if we can make the LHS or RHS match.
9694   if (LHS == FoundRHS || RHS == FoundLHS) {
9695     if (isa<SCEVConstant>(RHS)) {
9696       std::swap(FoundLHS, FoundRHS);
9697       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9698     } else {
9699       std::swap(LHS, RHS);
9700       Pred = ICmpInst::getSwappedPredicate(Pred);
9701     }
9702   }
9703 
9704   // Check whether the found predicate is the same as the desired predicate.
9705   if (FoundPred == Pred)
9706     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9707 
9708   // Check whether swapping the found predicate makes it the same as the
9709   // desired predicate.
9710   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9711     if (isa<SCEVConstant>(RHS))
9712       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9713     else
9714       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9715                                    RHS, LHS, FoundLHS, FoundRHS);
9716   }
9717 
9718   // Unsigned comparison is the same as signed comparison when both the operands
9719   // are non-negative.
9720   if (CmpInst::isUnsigned(FoundPred) &&
9721       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9722       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9723     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9724 
9725   // Check if we can make progress by sharpening ranges.
9726   if (FoundPred == ICmpInst::ICMP_NE &&
9727       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9728 
9729     const SCEVConstant *C = nullptr;
9730     const SCEV *V = nullptr;
9731 
9732     if (isa<SCEVConstant>(FoundLHS)) {
9733       C = cast<SCEVConstant>(FoundLHS);
9734       V = FoundRHS;
9735     } else {
9736       C = cast<SCEVConstant>(FoundRHS);
9737       V = FoundLHS;
9738     }
9739 
9740     // The guarding predicate tells us that C != V. If the known range
9741     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9742     // range we consider has to correspond to same signedness as the
9743     // predicate we're interested in folding.
9744 
9745     APInt Min = ICmpInst::isSigned(Pred) ?
9746         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9747 
9748     if (Min == C->getAPInt()) {
9749       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9750       // This is true even if (Min + 1) wraps around -- in case of
9751       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9752 
9753       APInt SharperMin = Min + 1;
9754 
9755       switch (Pred) {
9756         case ICmpInst::ICMP_SGE:
9757         case ICmpInst::ICMP_UGE:
9758           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9759           // RHS, we're done.
9760           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9761                                     getConstant(SharperMin)))
9762             return true;
9763           LLVM_FALLTHROUGH;
9764 
9765         case ICmpInst::ICMP_SGT:
9766         case ICmpInst::ICMP_UGT:
9767           // We know from the range information that (V `Pred` Min ||
9768           // V == Min).  We know from the guarding condition that !(V
9769           // == Min).  This gives us
9770           //
9771           //       V `Pred` Min || V == Min && !(V == Min)
9772           //   =>  V `Pred` Min
9773           //
9774           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9775 
9776           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9777             return true;
9778           LLVM_FALLTHROUGH;
9779 
9780         default:
9781           // No change
9782           break;
9783       }
9784     }
9785   }
9786 
9787   // Check whether the actual condition is beyond sufficient.
9788   if (FoundPred == ICmpInst::ICMP_EQ)
9789     if (ICmpInst::isTrueWhenEqual(Pred))
9790       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9791         return true;
9792   if (Pred == ICmpInst::ICMP_NE)
9793     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9794       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9795         return true;
9796 
9797   // Otherwise assume the worst.
9798   return false;
9799 }
9800 
9801 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9802                                      const SCEV *&L, const SCEV *&R,
9803                                      SCEV::NoWrapFlags &Flags) {
9804   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9805   if (!AE || AE->getNumOperands() != 2)
9806     return false;
9807 
9808   L = AE->getOperand(0);
9809   R = AE->getOperand(1);
9810   Flags = AE->getNoWrapFlags();
9811   return true;
9812 }
9813 
9814 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9815                                                            const SCEV *Less) {
9816   // We avoid subtracting expressions here because this function is usually
9817   // fairly deep in the call stack (i.e. is called many times).
9818 
9819   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9820     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9821     const auto *MAR = cast<SCEVAddRecExpr>(More);
9822 
9823     if (LAR->getLoop() != MAR->getLoop())
9824       return None;
9825 
9826     // We look at affine expressions only; not for correctness but to keep
9827     // getStepRecurrence cheap.
9828     if (!LAR->isAffine() || !MAR->isAffine())
9829       return None;
9830 
9831     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9832       return None;
9833 
9834     Less = LAR->getStart();
9835     More = MAR->getStart();
9836 
9837     // fall through
9838   }
9839 
9840   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9841     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9842     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9843     return M - L;
9844   }
9845 
9846   SCEV::NoWrapFlags Flags;
9847   const SCEV *LLess = nullptr, *RLess = nullptr;
9848   const SCEV *LMore = nullptr, *RMore = nullptr;
9849   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9850   // Compare (X + C1) vs X.
9851   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9852     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9853       if (RLess == More)
9854         return -(C1->getAPInt());
9855 
9856   // Compare X vs (X + C2).
9857   if (splitBinaryAdd(More, LMore, RMore, Flags))
9858     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9859       if (RMore == Less)
9860         return C2->getAPInt();
9861 
9862   // Compare (X + C1) vs (X + C2).
9863   if (C1 && C2 && RLess == RMore)
9864     return C2->getAPInt() - C1->getAPInt();
9865 
9866   return None;
9867 }
9868 
9869 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9870     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9871     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9872   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9873     return false;
9874 
9875   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9876   if (!AddRecLHS)
9877     return false;
9878 
9879   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9880   if (!AddRecFoundLHS)
9881     return false;
9882 
9883   // We'd like to let SCEV reason about control dependencies, so we constrain
9884   // both the inequalities to be about add recurrences on the same loop.  This
9885   // way we can use isLoopEntryGuardedByCond later.
9886 
9887   const Loop *L = AddRecFoundLHS->getLoop();
9888   if (L != AddRecLHS->getLoop())
9889     return false;
9890 
9891   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9892   //
9893   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9894   //                                                                  ... (2)
9895   //
9896   // Informal proof for (2), assuming (1) [*]:
9897   //
9898   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9899   //
9900   // Then
9901   //
9902   //       FoundLHS s< FoundRHS s< INT_MIN - C
9903   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9904   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9905   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9906   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9907   // <=>  FoundLHS + C s< FoundRHS + C
9908   //
9909   // [*]: (1) can be proved by ruling out overflow.
9910   //
9911   // [**]: This can be proved by analyzing all the four possibilities:
9912   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9913   //    (A s>= 0, B s>= 0).
9914   //
9915   // Note:
9916   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9917   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9918   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9919   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9920   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9921   // C)".
9922 
9923   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9924   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9925   if (!LDiff || !RDiff || *LDiff != *RDiff)
9926     return false;
9927 
9928   if (LDiff->isMinValue())
9929     return true;
9930 
9931   APInt FoundRHSLimit;
9932 
9933   if (Pred == CmpInst::ICMP_ULT) {
9934     FoundRHSLimit = -(*RDiff);
9935   } else {
9936     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9937     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9938   }
9939 
9940   // Try to prove (1) or (2), as needed.
9941   return isAvailableAtLoopEntry(FoundRHS, L) &&
9942          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9943                                   getConstant(FoundRHSLimit));
9944 }
9945 
9946 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9947                                         const SCEV *LHS, const SCEV *RHS,
9948                                         const SCEV *FoundLHS,
9949                                         const SCEV *FoundRHS, unsigned Depth) {
9950   const PHINode *LPhi = nullptr, *RPhi = nullptr;
9951 
9952   auto ClearOnExit = make_scope_exit([&]() {
9953     if (LPhi) {
9954       bool Erased = PendingMerges.erase(LPhi);
9955       assert(Erased && "Failed to erase LPhi!");
9956       (void)Erased;
9957     }
9958     if (RPhi) {
9959       bool Erased = PendingMerges.erase(RPhi);
9960       assert(Erased && "Failed to erase RPhi!");
9961       (void)Erased;
9962     }
9963   });
9964 
9965   // Find respective Phis and check that they are not being pending.
9966   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9967     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9968       if (!PendingMerges.insert(Phi).second)
9969         return false;
9970       LPhi = Phi;
9971     }
9972   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9973     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9974       // If we detect a loop of Phi nodes being processed by this method, for
9975       // example:
9976       //
9977       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9978       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9979       //
9980       // we don't want to deal with a case that complex, so return conservative
9981       // answer false.
9982       if (!PendingMerges.insert(Phi).second)
9983         return false;
9984       RPhi = Phi;
9985     }
9986 
9987   // If none of LHS, RHS is a Phi, nothing to do here.
9988   if (!LPhi && !RPhi)
9989     return false;
9990 
9991   // If there is a SCEVUnknown Phi we are interested in, make it left.
9992   if (!LPhi) {
9993     std::swap(LHS, RHS);
9994     std::swap(FoundLHS, FoundRHS);
9995     std::swap(LPhi, RPhi);
9996     Pred = ICmpInst::getSwappedPredicate(Pred);
9997   }
9998 
9999   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10000   const BasicBlock *LBB = LPhi->getParent();
10001   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10002 
10003   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10004     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10005            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10006            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10007   };
10008 
10009   if (RPhi && RPhi->getParent() == LBB) {
10010     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10011     // If we compare two Phis from the same block, and for each entry block
10012     // the predicate is true for incoming values from this block, then the
10013     // predicate is also true for the Phis.
10014     for (const BasicBlock *IncBB : predecessors(LBB)) {
10015       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10016       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10017       if (!ProvedEasily(L, R))
10018         return false;
10019     }
10020   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10021     // Case two: RHS is also a Phi from the same basic block, and it is an
10022     // AddRec. It means that there is a loop which has both AddRec and Unknown
10023     // PHIs, for it we can compare incoming values of AddRec from above the loop
10024     // and latch with their respective incoming values of LPhi.
10025     // TODO: Generalize to handle loops with many inputs in a header.
10026     if (LPhi->getNumIncomingValues() != 2) return false;
10027 
10028     auto *RLoop = RAR->getLoop();
10029     auto *Predecessor = RLoop->getLoopPredecessor();
10030     assert(Predecessor && "Loop with AddRec with no predecessor?");
10031     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10032     if (!ProvedEasily(L1, RAR->getStart()))
10033       return false;
10034     auto *Latch = RLoop->getLoopLatch();
10035     assert(Latch && "Loop with AddRec with no latch?");
10036     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10037     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10038       return false;
10039   } else {
10040     // In all other cases go over inputs of LHS and compare each of them to RHS,
10041     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10042     // At this point RHS is either a non-Phi, or it is a Phi from some block
10043     // different from LBB.
10044     for (const BasicBlock *IncBB : predecessors(LBB)) {
10045       // Check that RHS is available in this block.
10046       if (!dominates(RHS, IncBB))
10047         return false;
10048       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10049       if (!ProvedEasily(L, RHS))
10050         return false;
10051     }
10052   }
10053   return true;
10054 }
10055 
10056 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10057                                             const SCEV *LHS, const SCEV *RHS,
10058                                             const SCEV *FoundLHS,
10059                                             const SCEV *FoundRHS) {
10060   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10061     return true;
10062 
10063   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10064     return true;
10065 
10066   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10067                                      FoundLHS, FoundRHS) ||
10068          // ~x < ~y --> x > y
10069          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10070                                      getNotSCEV(FoundRHS),
10071                                      getNotSCEV(FoundLHS));
10072 }
10073 
10074 /// If Expr computes ~A, return A else return nullptr
10075 static const SCEV *MatchNotExpr(const SCEV *Expr) {
10076   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
10077   if (!Add || Add->getNumOperands() != 2 ||
10078       !Add->getOperand(0)->isAllOnesValue())
10079     return nullptr;
10080 
10081   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
10082   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
10083       !AddRHS->getOperand(0)->isAllOnesValue())
10084     return nullptr;
10085 
10086   return AddRHS->getOperand(1);
10087 }
10088 
10089 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
10090 template<typename MaxExprType>
10091 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
10092                               const SCEV *Candidate) {
10093   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
10094   if (!MaxExpr) return false;
10095 
10096   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
10097 }
10098 
10099 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
10100 template<typename MaxExprType>
10101 static bool IsMinConsistingOf(ScalarEvolution &SE,
10102                               const SCEV *MaybeMinExpr,
10103                               const SCEV *Candidate) {
10104   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
10105   if (!MaybeMaxExpr)
10106     return false;
10107 
10108   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
10109 }
10110 
10111 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10112                                            ICmpInst::Predicate Pred,
10113                                            const SCEV *LHS, const SCEV *RHS) {
10114   // If both sides are affine addrecs for the same loop, with equal
10115   // steps, and we know the recurrences don't wrap, then we only
10116   // need to check the predicate on the starting values.
10117 
10118   if (!ICmpInst::isRelational(Pred))
10119     return false;
10120 
10121   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10122   if (!LAR)
10123     return false;
10124   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10125   if (!RAR)
10126     return false;
10127   if (LAR->getLoop() != RAR->getLoop())
10128     return false;
10129   if (!LAR->isAffine() || !RAR->isAffine())
10130     return false;
10131 
10132   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10133     return false;
10134 
10135   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10136                          SCEV::FlagNSW : SCEV::FlagNUW;
10137   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10138     return false;
10139 
10140   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10141 }
10142 
10143 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10144 /// expression?
10145 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10146                                         ICmpInst::Predicate Pred,
10147                                         const SCEV *LHS, const SCEV *RHS) {
10148   switch (Pred) {
10149   default:
10150     return false;
10151 
10152   case ICmpInst::ICMP_SGE:
10153     std::swap(LHS, RHS);
10154     LLVM_FALLTHROUGH;
10155   case ICmpInst::ICMP_SLE:
10156     return
10157       // min(A, ...) <= A
10158       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
10159       // A <= max(A, ...)
10160       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10161 
10162   case ICmpInst::ICMP_UGE:
10163     std::swap(LHS, RHS);
10164     LLVM_FALLTHROUGH;
10165   case ICmpInst::ICMP_ULE:
10166     return
10167       // min(A, ...) <= A
10168       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
10169       // A <= max(A, ...)
10170       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10171   }
10172 
10173   llvm_unreachable("covered switch fell through?!");
10174 }
10175 
10176 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10177                                              const SCEV *LHS, const SCEV *RHS,
10178                                              const SCEV *FoundLHS,
10179                                              const SCEV *FoundRHS,
10180                                              unsigned Depth) {
10181   assert(getTypeSizeInBits(LHS->getType()) ==
10182              getTypeSizeInBits(RHS->getType()) &&
10183          "LHS and RHS have different sizes?");
10184   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10185              getTypeSizeInBits(FoundRHS->getType()) &&
10186          "FoundLHS and FoundRHS have different sizes?");
10187   // We want to avoid hurting the compile time with analysis of too big trees.
10188   if (Depth > MaxSCEVOperationsImplicationDepth)
10189     return false;
10190   // We only want to work with ICMP_SGT comparison so far.
10191   // TODO: Extend to ICMP_UGT?
10192   if (Pred == ICmpInst::ICMP_SLT) {
10193     Pred = ICmpInst::ICMP_SGT;
10194     std::swap(LHS, RHS);
10195     std::swap(FoundLHS, FoundRHS);
10196   }
10197   if (Pred != ICmpInst::ICMP_SGT)
10198     return false;
10199 
10200   auto GetOpFromSExt = [&](const SCEV *S) {
10201     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10202       return Ext->getOperand();
10203     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10204     // the constant in some cases.
10205     return S;
10206   };
10207 
10208   // Acquire values from extensions.
10209   auto *OrigLHS = LHS;
10210   auto *OrigFoundLHS = FoundLHS;
10211   LHS = GetOpFromSExt(LHS);
10212   FoundLHS = GetOpFromSExt(FoundLHS);
10213 
10214   // Is the SGT predicate can be proved trivially or using the found context.
10215   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10216     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10217            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10218                                   FoundRHS, Depth + 1);
10219   };
10220 
10221   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10222     // We want to avoid creation of any new non-constant SCEV. Since we are
10223     // going to compare the operands to RHS, we should be certain that we don't
10224     // need any size extensions for this. So let's decline all cases when the
10225     // sizes of types of LHS and RHS do not match.
10226     // TODO: Maybe try to get RHS from sext to catch more cases?
10227     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10228       return false;
10229 
10230     // Should not overflow.
10231     if (!LHSAddExpr->hasNoSignedWrap())
10232       return false;
10233 
10234     auto *LL = LHSAddExpr->getOperand(0);
10235     auto *LR = LHSAddExpr->getOperand(1);
10236     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
10237 
10238     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10239     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10240       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10241     };
10242     // Try to prove the following rule:
10243     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10244     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10245     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10246       return true;
10247   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10248     Value *LL, *LR;
10249     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10250 
10251     using namespace llvm::PatternMatch;
10252 
10253     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10254       // Rules for division.
10255       // We are going to perform some comparisons with Denominator and its
10256       // derivative expressions. In general case, creating a SCEV for it may
10257       // lead to a complex analysis of the entire graph, and in particular it
10258       // can request trip count recalculation for the same loop. This would
10259       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10260       // this, we only want to create SCEVs that are constants in this section.
10261       // So we bail if Denominator is not a constant.
10262       if (!isa<ConstantInt>(LR))
10263         return false;
10264 
10265       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10266 
10267       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10268       // then a SCEV for the numerator already exists and matches with FoundLHS.
10269       auto *Numerator = getExistingSCEV(LL);
10270       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10271         return false;
10272 
10273       // Make sure that the numerator matches with FoundLHS and the denominator
10274       // is positive.
10275       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10276         return false;
10277 
10278       auto *DTy = Denominator->getType();
10279       auto *FRHSTy = FoundRHS->getType();
10280       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10281         // One of types is a pointer and another one is not. We cannot extend
10282         // them properly to a wider type, so let us just reject this case.
10283         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10284         // to avoid this check.
10285         return false;
10286 
10287       // Given that:
10288       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10289       auto *WTy = getWiderType(DTy, FRHSTy);
10290       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10291       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10292 
10293       // Try to prove the following rule:
10294       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10295       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10296       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10297       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10298       if (isKnownNonPositive(RHS) &&
10299           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10300         return true;
10301 
10302       // Try to prove the following rule:
10303       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10304       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10305       // If we divide it by Denominator > 2, then:
10306       // 1. If FoundLHS is negative, then the result is 0.
10307       // 2. If FoundLHS is non-negative, then the result is non-negative.
10308       // Anyways, the result is non-negative.
10309       auto *MinusOne = getNegativeSCEV(getOne(WTy));
10310       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10311       if (isKnownNegative(RHS) &&
10312           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10313         return true;
10314     }
10315   }
10316 
10317   // If our expression contained SCEVUnknown Phis, and we split it down and now
10318   // need to prove something for them, try to prove the predicate for every
10319   // possible incoming values of those Phis.
10320   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10321     return true;
10322 
10323   return false;
10324 }
10325 
10326 bool
10327 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10328                                            const SCEV *LHS, const SCEV *RHS) {
10329   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10330          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10331          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10332          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10333 }
10334 
10335 bool
10336 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10337                                              const SCEV *LHS, const SCEV *RHS,
10338                                              const SCEV *FoundLHS,
10339                                              const SCEV *FoundRHS) {
10340   switch (Pred) {
10341   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10342   case ICmpInst::ICMP_EQ:
10343   case ICmpInst::ICMP_NE:
10344     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10345       return true;
10346     break;
10347   case ICmpInst::ICMP_SLT:
10348   case ICmpInst::ICMP_SLE:
10349     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10350         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10351       return true;
10352     break;
10353   case ICmpInst::ICMP_SGT:
10354   case ICmpInst::ICMP_SGE:
10355     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10356         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10357       return true;
10358     break;
10359   case ICmpInst::ICMP_ULT:
10360   case ICmpInst::ICMP_ULE:
10361     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10362         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10363       return true;
10364     break;
10365   case ICmpInst::ICMP_UGT:
10366   case ICmpInst::ICMP_UGE:
10367     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10368         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10369       return true;
10370     break;
10371   }
10372 
10373   // Maybe it can be proved via operations?
10374   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10375     return true;
10376 
10377   return false;
10378 }
10379 
10380 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10381                                                      const SCEV *LHS,
10382                                                      const SCEV *RHS,
10383                                                      const SCEV *FoundLHS,
10384                                                      const SCEV *FoundRHS) {
10385   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10386     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10387     // reduce the compile time impact of this optimization.
10388     return false;
10389 
10390   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10391   if (!Addend)
10392     return false;
10393 
10394   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10395 
10396   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10397   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10398   ConstantRange FoundLHSRange =
10399       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10400 
10401   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10402   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10403 
10404   // We can also compute the range of values for `LHS` that satisfy the
10405   // consequent, "`LHS` `Pred` `RHS`":
10406   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10407   ConstantRange SatisfyingLHSRange =
10408       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10409 
10410   // The antecedent implies the consequent if every value of `LHS` that
10411   // satisfies the antecedent also satisfies the consequent.
10412   return SatisfyingLHSRange.contains(LHSRange);
10413 }
10414 
10415 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10416                                          bool IsSigned, bool NoWrap) {
10417   assert(isKnownPositive(Stride) && "Positive stride expected!");
10418 
10419   if (NoWrap) return false;
10420 
10421   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10422   const SCEV *One = getOne(Stride->getType());
10423 
10424   if (IsSigned) {
10425     APInt MaxRHS = getSignedRangeMax(RHS);
10426     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10427     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10428 
10429     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10430     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10431   }
10432 
10433   APInt MaxRHS = getUnsignedRangeMax(RHS);
10434   APInt MaxValue = APInt::getMaxValue(BitWidth);
10435   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10436 
10437   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10438   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10439 }
10440 
10441 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10442                                          bool IsSigned, bool NoWrap) {
10443   if (NoWrap) return false;
10444 
10445   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10446   const SCEV *One = getOne(Stride->getType());
10447 
10448   if (IsSigned) {
10449     APInt MinRHS = getSignedRangeMin(RHS);
10450     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10451     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10452 
10453     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10454     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10455   }
10456 
10457   APInt MinRHS = getUnsignedRangeMin(RHS);
10458   APInt MinValue = APInt::getMinValue(BitWidth);
10459   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10460 
10461   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10462   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10463 }
10464 
10465 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10466                                             bool Equality) {
10467   const SCEV *One = getOne(Step->getType());
10468   Delta = Equality ? getAddExpr(Delta, Step)
10469                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10470   return getUDivExpr(Delta, Step);
10471 }
10472 
10473 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10474                                                     const SCEV *Stride,
10475                                                     const SCEV *End,
10476                                                     unsigned BitWidth,
10477                                                     bool IsSigned) {
10478 
10479   assert(!isKnownNonPositive(Stride) &&
10480          "Stride is expected strictly positive!");
10481   // Calculate the maximum backedge count based on the range of values
10482   // permitted by Start, End, and Stride.
10483   const SCEV *MaxBECount;
10484   APInt MinStart =
10485       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10486 
10487   APInt StrideForMaxBECount =
10488       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10489 
10490   // We already know that the stride is positive, so we paper over conservatism
10491   // in our range computation by forcing StrideForMaxBECount to be at least one.
10492   // In theory this is unnecessary, but we expect MaxBECount to be a
10493   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10494   // is nothing to constant fold it to).
10495   APInt One(BitWidth, 1, IsSigned);
10496   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10497 
10498   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10499                             : APInt::getMaxValue(BitWidth);
10500   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10501 
10502   // Although End can be a MAX expression we estimate MaxEnd considering only
10503   // the case End = RHS of the loop termination condition. This is safe because
10504   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10505   // taken count.
10506   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10507                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10508 
10509   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10510                               getConstant(StrideForMaxBECount) /* Step */,
10511                               false /* Equality */);
10512 
10513   return MaxBECount;
10514 }
10515 
10516 ScalarEvolution::ExitLimit
10517 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10518                                   const Loop *L, bool IsSigned,
10519                                   bool ControlsExit, bool AllowPredicates) {
10520   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10521 
10522   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10523   bool PredicatedIV = false;
10524 
10525   if (!IV && AllowPredicates) {
10526     // Try to make this an AddRec using runtime tests, in the first X
10527     // iterations of this loop, where X is the SCEV expression found by the
10528     // algorithm below.
10529     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10530     PredicatedIV = true;
10531   }
10532 
10533   // Avoid weird loops
10534   if (!IV || IV->getLoop() != L || !IV->isAffine())
10535     return getCouldNotCompute();
10536 
10537   bool NoWrap = ControlsExit &&
10538                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10539 
10540   const SCEV *Stride = IV->getStepRecurrence(*this);
10541 
10542   bool PositiveStride = isKnownPositive(Stride);
10543 
10544   // Avoid negative or zero stride values.
10545   if (!PositiveStride) {
10546     // We can compute the correct backedge taken count for loops with unknown
10547     // strides if we can prove that the loop is not an infinite loop with side
10548     // effects. Here's the loop structure we are trying to handle -
10549     //
10550     // i = start
10551     // do {
10552     //   A[i] = i;
10553     //   i += s;
10554     // } while (i < end);
10555     //
10556     // The backedge taken count for such loops is evaluated as -
10557     // (max(end, start + stride) - start - 1) /u stride
10558     //
10559     // The additional preconditions that we need to check to prove correctness
10560     // of the above formula is as follows -
10561     //
10562     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10563     //    NoWrap flag).
10564     // b) loop is single exit with no side effects.
10565     //
10566     //
10567     // Precondition a) implies that if the stride is negative, this is a single
10568     // trip loop. The backedge taken count formula reduces to zero in this case.
10569     //
10570     // Precondition b) implies that the unknown stride cannot be zero otherwise
10571     // we have UB.
10572     //
10573     // The positive stride case is the same as isKnownPositive(Stride) returning
10574     // true (original behavior of the function).
10575     //
10576     // We want to make sure that the stride is truly unknown as there are edge
10577     // cases where ScalarEvolution propagates no wrap flags to the
10578     // post-increment/decrement IV even though the increment/decrement operation
10579     // itself is wrapping. The computed backedge taken count may be wrong in
10580     // such cases. This is prevented by checking that the stride is not known to
10581     // be either positive or non-positive. For example, no wrap flags are
10582     // propagated to the post-increment IV of this loop with a trip count of 2 -
10583     //
10584     // unsigned char i;
10585     // for(i=127; i<128; i+=129)
10586     //   A[i] = i;
10587     //
10588     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10589         !loopHasNoSideEffects(L))
10590       return getCouldNotCompute();
10591   } else if (!Stride->isOne() &&
10592              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10593     // Avoid proven overflow cases: this will ensure that the backedge taken
10594     // count will not generate any unsigned overflow. Relaxed no-overflow
10595     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10596     // undefined behaviors like the case of C language.
10597     return getCouldNotCompute();
10598 
10599   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10600                                       : ICmpInst::ICMP_ULT;
10601   const SCEV *Start = IV->getStart();
10602   const SCEV *End = RHS;
10603   // When the RHS is not invariant, we do not know the end bound of the loop and
10604   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10605   // calculate the MaxBECount, given the start, stride and max value for the end
10606   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10607   // checked above).
10608   if (!isLoopInvariant(RHS, L)) {
10609     const SCEV *MaxBECount = computeMaxBECountForLT(
10610         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10611     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10612                      false /*MaxOrZero*/, Predicates);
10613   }
10614   // If the backedge is taken at least once, then it will be taken
10615   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10616   // is the LHS value of the less-than comparison the first time it is evaluated
10617   // and End is the RHS.
10618   const SCEV *BECountIfBackedgeTaken =
10619     computeBECount(getMinusSCEV(End, Start), Stride, false);
10620   // If the loop entry is guarded by the result of the backedge test of the
10621   // first loop iteration, then we know the backedge will be taken at least
10622   // once and so the backedge taken count is as above. If not then we use the
10623   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10624   // as if the backedge is taken at least once max(End,Start) is End and so the
10625   // result is as above, and if not max(End,Start) is Start so we get a backedge
10626   // count of zero.
10627   const SCEV *BECount;
10628   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10629     BECount = BECountIfBackedgeTaken;
10630   else {
10631     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10632     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10633   }
10634 
10635   const SCEV *MaxBECount;
10636   bool MaxOrZero = false;
10637   if (isa<SCEVConstant>(BECount))
10638     MaxBECount = BECount;
10639   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10640     // If we know exactly how many times the backedge will be taken if it's
10641     // taken at least once, then the backedge count will either be that or
10642     // zero.
10643     MaxBECount = BECountIfBackedgeTaken;
10644     MaxOrZero = true;
10645   } else {
10646     MaxBECount = computeMaxBECountForLT(
10647         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10648   }
10649 
10650   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10651       !isa<SCEVCouldNotCompute>(BECount))
10652     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10653 
10654   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10655 }
10656 
10657 ScalarEvolution::ExitLimit
10658 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10659                                      const Loop *L, bool IsSigned,
10660                                      bool ControlsExit, bool AllowPredicates) {
10661   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10662   // We handle only IV > Invariant
10663   if (!isLoopInvariant(RHS, L))
10664     return getCouldNotCompute();
10665 
10666   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10667   if (!IV && AllowPredicates)
10668     // Try to make this an AddRec using runtime tests, in the first X
10669     // iterations of this loop, where X is the SCEV expression found by the
10670     // algorithm below.
10671     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10672 
10673   // Avoid weird loops
10674   if (!IV || IV->getLoop() != L || !IV->isAffine())
10675     return getCouldNotCompute();
10676 
10677   bool NoWrap = ControlsExit &&
10678                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10679 
10680   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10681 
10682   // Avoid negative or zero stride values
10683   if (!isKnownPositive(Stride))
10684     return getCouldNotCompute();
10685 
10686   // Avoid proven overflow cases: this will ensure that the backedge taken count
10687   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10688   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10689   // behaviors like the case of C language.
10690   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10691     return getCouldNotCompute();
10692 
10693   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10694                                       : ICmpInst::ICMP_UGT;
10695 
10696   const SCEV *Start = IV->getStart();
10697   const SCEV *End = RHS;
10698   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10699     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10700 
10701   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10702 
10703   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10704                             : getUnsignedRangeMax(Start);
10705 
10706   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10707                              : getUnsignedRangeMin(Stride);
10708 
10709   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10710   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10711                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10712 
10713   // Although End can be a MIN expression we estimate MinEnd considering only
10714   // the case End = RHS. This is safe because in the other case (Start - End)
10715   // is zero, leading to a zero maximum backedge taken count.
10716   APInt MinEnd =
10717     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10718              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10719 
10720 
10721   const SCEV *MaxBECount = getCouldNotCompute();
10722   if (isa<SCEVConstant>(BECount))
10723     MaxBECount = BECount;
10724   else
10725     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10726                                 getConstant(MinStride), false);
10727 
10728   if (isa<SCEVCouldNotCompute>(MaxBECount))
10729     MaxBECount = BECount;
10730 
10731   return ExitLimit(BECount, MaxBECount, false, Predicates);
10732 }
10733 
10734 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10735                                                     ScalarEvolution &SE) const {
10736   if (Range.isFullSet())  // Infinite loop.
10737     return SE.getCouldNotCompute();
10738 
10739   // If the start is a non-zero constant, shift the range to simplify things.
10740   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10741     if (!SC->getValue()->isZero()) {
10742       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10743       Operands[0] = SE.getZero(SC->getType());
10744       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10745                                              getNoWrapFlags(FlagNW));
10746       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10747         return ShiftedAddRec->getNumIterationsInRange(
10748             Range.subtract(SC->getAPInt()), SE);
10749       // This is strange and shouldn't happen.
10750       return SE.getCouldNotCompute();
10751     }
10752 
10753   // The only time we can solve this is when we have all constant indices.
10754   // Otherwise, we cannot determine the overflow conditions.
10755   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10756     return SE.getCouldNotCompute();
10757 
10758   // Okay at this point we know that all elements of the chrec are constants and
10759   // that the start element is zero.
10760 
10761   // First check to see if the range contains zero.  If not, the first
10762   // iteration exits.
10763   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10764   if (!Range.contains(APInt(BitWidth, 0)))
10765     return SE.getZero(getType());
10766 
10767   if (isAffine()) {
10768     // If this is an affine expression then we have this situation:
10769     //   Solve {0,+,A} in Range  ===  Ax in Range
10770 
10771     // We know that zero is in the range.  If A is positive then we know that
10772     // the upper value of the range must be the first possible exit value.
10773     // If A is negative then the lower of the range is the last possible loop
10774     // value.  Also note that we already checked for a full range.
10775     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10776     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10777 
10778     // The exit value should be (End+A)/A.
10779     APInt ExitVal = (End + A).udiv(A);
10780     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10781 
10782     // Evaluate at the exit value.  If we really did fall out of the valid
10783     // range, then we computed our trip count, otherwise wrap around or other
10784     // things must have happened.
10785     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10786     if (Range.contains(Val->getValue()))
10787       return SE.getCouldNotCompute();  // Something strange happened
10788 
10789     // Ensure that the previous value is in the range.  This is a sanity check.
10790     assert(Range.contains(
10791            EvaluateConstantChrecAtConstant(this,
10792            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10793            "Linear scev computation is off in a bad way!");
10794     return SE.getConstant(ExitValue);
10795   }
10796 
10797   if (isQuadratic()) {
10798     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
10799       return SE.getConstant(S.getValue());
10800   }
10801 
10802   return SE.getCouldNotCompute();
10803 }
10804 
10805 const SCEVAddRecExpr *
10806 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10807   assert(getNumOperands() > 1 && "AddRec with zero step?");
10808   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10809   // but in this case we cannot guarantee that the value returned will be an
10810   // AddRec because SCEV does not have a fixed point where it stops
10811   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10812   // may happen if we reach arithmetic depth limit while simplifying. So we
10813   // construct the returned value explicitly.
10814   SmallVector<const SCEV *, 3> Ops;
10815   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10816   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10817   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10818     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10819   // We know that the last operand is not a constant zero (otherwise it would
10820   // have been popped out earlier). This guarantees us that if the result has
10821   // the same last operand, then it will also not be popped out, meaning that
10822   // the returned value will be an AddRec.
10823   const SCEV *Last = getOperand(getNumOperands() - 1);
10824   assert(!Last->isZero() && "Recurrency with zero step?");
10825   Ops.push_back(Last);
10826   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10827                                                SCEV::FlagAnyWrap));
10828 }
10829 
10830 // Return true when S contains at least an undef value.
10831 static inline bool containsUndefs(const SCEV *S) {
10832   return SCEVExprContains(S, [](const SCEV *S) {
10833     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10834       return isa<UndefValue>(SU->getValue());
10835     return false;
10836   });
10837 }
10838 
10839 namespace {
10840 
10841 // Collect all steps of SCEV expressions.
10842 struct SCEVCollectStrides {
10843   ScalarEvolution &SE;
10844   SmallVectorImpl<const SCEV *> &Strides;
10845 
10846   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10847       : SE(SE), Strides(S) {}
10848 
10849   bool follow(const SCEV *S) {
10850     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10851       Strides.push_back(AR->getStepRecurrence(SE));
10852     return true;
10853   }
10854 
10855   bool isDone() const { return false; }
10856 };
10857 
10858 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10859 struct SCEVCollectTerms {
10860   SmallVectorImpl<const SCEV *> &Terms;
10861 
10862   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10863 
10864   bool follow(const SCEV *S) {
10865     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10866         isa<SCEVSignExtendExpr>(S)) {
10867       if (!containsUndefs(S))
10868         Terms.push_back(S);
10869 
10870       // Stop recursion: once we collected a term, do not walk its operands.
10871       return false;
10872     }
10873 
10874     // Keep looking.
10875     return true;
10876   }
10877 
10878   bool isDone() const { return false; }
10879 };
10880 
10881 // Check if a SCEV contains an AddRecExpr.
10882 struct SCEVHasAddRec {
10883   bool &ContainsAddRec;
10884 
10885   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10886     ContainsAddRec = false;
10887   }
10888 
10889   bool follow(const SCEV *S) {
10890     if (isa<SCEVAddRecExpr>(S)) {
10891       ContainsAddRec = true;
10892 
10893       // Stop recursion: once we collected a term, do not walk its operands.
10894       return false;
10895     }
10896 
10897     // Keep looking.
10898     return true;
10899   }
10900 
10901   bool isDone() const { return false; }
10902 };
10903 
10904 // Find factors that are multiplied with an expression that (possibly as a
10905 // subexpression) contains an AddRecExpr. In the expression:
10906 //
10907 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10908 //
10909 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10910 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10911 // parameters as they form a product with an induction variable.
10912 //
10913 // This collector expects all array size parameters to be in the same MulExpr.
10914 // It might be necessary to later add support for collecting parameters that are
10915 // spread over different nested MulExpr.
10916 struct SCEVCollectAddRecMultiplies {
10917   SmallVectorImpl<const SCEV *> &Terms;
10918   ScalarEvolution &SE;
10919 
10920   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10921       : Terms(T), SE(SE) {}
10922 
10923   bool follow(const SCEV *S) {
10924     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10925       bool HasAddRec = false;
10926       SmallVector<const SCEV *, 0> Operands;
10927       for (auto Op : Mul->operands()) {
10928         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10929         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10930           Operands.push_back(Op);
10931         } else if (Unknown) {
10932           HasAddRec = true;
10933         } else {
10934           bool ContainsAddRec;
10935           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10936           visitAll(Op, ContiansAddRec);
10937           HasAddRec |= ContainsAddRec;
10938         }
10939       }
10940       if (Operands.size() == 0)
10941         return true;
10942 
10943       if (!HasAddRec)
10944         return false;
10945 
10946       Terms.push_back(SE.getMulExpr(Operands));
10947       // Stop recursion: once we collected a term, do not walk its operands.
10948       return false;
10949     }
10950 
10951     // Keep looking.
10952     return true;
10953   }
10954 
10955   bool isDone() const { return false; }
10956 };
10957 
10958 } // end anonymous namespace
10959 
10960 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10961 /// two places:
10962 ///   1) The strides of AddRec expressions.
10963 ///   2) Unknowns that are multiplied with AddRec expressions.
10964 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10965     SmallVectorImpl<const SCEV *> &Terms) {
10966   SmallVector<const SCEV *, 4> Strides;
10967   SCEVCollectStrides StrideCollector(*this, Strides);
10968   visitAll(Expr, StrideCollector);
10969 
10970   LLVM_DEBUG({
10971     dbgs() << "Strides:\n";
10972     for (const SCEV *S : Strides)
10973       dbgs() << *S << "\n";
10974   });
10975 
10976   for (const SCEV *S : Strides) {
10977     SCEVCollectTerms TermCollector(Terms);
10978     visitAll(S, TermCollector);
10979   }
10980 
10981   LLVM_DEBUG({
10982     dbgs() << "Terms:\n";
10983     for (const SCEV *T : Terms)
10984       dbgs() << *T << "\n";
10985   });
10986 
10987   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10988   visitAll(Expr, MulCollector);
10989 }
10990 
10991 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10992                                    SmallVectorImpl<const SCEV *> &Terms,
10993                                    SmallVectorImpl<const SCEV *> &Sizes) {
10994   int Last = Terms.size() - 1;
10995   const SCEV *Step = Terms[Last];
10996 
10997   // End of recursion.
10998   if (Last == 0) {
10999     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11000       SmallVector<const SCEV *, 2> Qs;
11001       for (const SCEV *Op : M->operands())
11002         if (!isa<SCEVConstant>(Op))
11003           Qs.push_back(Op);
11004 
11005       Step = SE.getMulExpr(Qs);
11006     }
11007 
11008     Sizes.push_back(Step);
11009     return true;
11010   }
11011 
11012   for (const SCEV *&Term : Terms) {
11013     // Normalize the terms before the next call to findArrayDimensionsRec.
11014     const SCEV *Q, *R;
11015     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11016 
11017     // Bail out when GCD does not evenly divide one of the terms.
11018     if (!R->isZero())
11019       return false;
11020 
11021     Term = Q;
11022   }
11023 
11024   // Remove all SCEVConstants.
11025   Terms.erase(
11026       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11027       Terms.end());
11028 
11029   if (Terms.size() > 0)
11030     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11031       return false;
11032 
11033   Sizes.push_back(Step);
11034   return true;
11035 }
11036 
11037 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11038 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11039   for (const SCEV *T : Terms)
11040     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
11041       return true;
11042   return false;
11043 }
11044 
11045 // Return the number of product terms in S.
11046 static inline int numberOfTerms(const SCEV *S) {
11047   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11048     return Expr->getNumOperands();
11049   return 1;
11050 }
11051 
11052 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11053   if (isa<SCEVConstant>(T))
11054     return nullptr;
11055 
11056   if (isa<SCEVUnknown>(T))
11057     return T;
11058 
11059   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11060     SmallVector<const SCEV *, 2> Factors;
11061     for (const SCEV *Op : M->operands())
11062       if (!isa<SCEVConstant>(Op))
11063         Factors.push_back(Op);
11064 
11065     return SE.getMulExpr(Factors);
11066   }
11067 
11068   return T;
11069 }
11070 
11071 /// Return the size of an element read or written by Inst.
11072 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11073   Type *Ty;
11074   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11075     Ty = Store->getValueOperand()->getType();
11076   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11077     Ty = Load->getType();
11078   else
11079     return nullptr;
11080 
11081   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11082   return getSizeOfExpr(ETy, Ty);
11083 }
11084 
11085 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11086                                           SmallVectorImpl<const SCEV *> &Sizes,
11087                                           const SCEV *ElementSize) {
11088   if (Terms.size() < 1 || !ElementSize)
11089     return;
11090 
11091   // Early return when Terms do not contain parameters: we do not delinearize
11092   // non parametric SCEVs.
11093   if (!containsParameters(Terms))
11094     return;
11095 
11096   LLVM_DEBUG({
11097     dbgs() << "Terms:\n";
11098     for (const SCEV *T : Terms)
11099       dbgs() << *T << "\n";
11100   });
11101 
11102   // Remove duplicates.
11103   array_pod_sort(Terms.begin(), Terms.end());
11104   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11105 
11106   // Put larger terms first.
11107   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11108     return numberOfTerms(LHS) > numberOfTerms(RHS);
11109   });
11110 
11111   // Try to divide all terms by the element size. If term is not divisible by
11112   // element size, proceed with the original term.
11113   for (const SCEV *&Term : Terms) {
11114     const SCEV *Q, *R;
11115     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11116     if (!Q->isZero())
11117       Term = Q;
11118   }
11119 
11120   SmallVector<const SCEV *, 4> NewTerms;
11121 
11122   // Remove constant factors.
11123   for (const SCEV *T : Terms)
11124     if (const SCEV *NewT = removeConstantFactors(*this, T))
11125       NewTerms.push_back(NewT);
11126 
11127   LLVM_DEBUG({
11128     dbgs() << "Terms after sorting:\n";
11129     for (const SCEV *T : NewTerms)
11130       dbgs() << *T << "\n";
11131   });
11132 
11133   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11134     Sizes.clear();
11135     return;
11136   }
11137 
11138   // The last element to be pushed into Sizes is the size of an element.
11139   Sizes.push_back(ElementSize);
11140 
11141   LLVM_DEBUG({
11142     dbgs() << "Sizes:\n";
11143     for (const SCEV *S : Sizes)
11144       dbgs() << *S << "\n";
11145   });
11146 }
11147 
11148 void ScalarEvolution::computeAccessFunctions(
11149     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11150     SmallVectorImpl<const SCEV *> &Sizes) {
11151   // Early exit in case this SCEV is not an affine multivariate function.
11152   if (Sizes.empty())
11153     return;
11154 
11155   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11156     if (!AR->isAffine())
11157       return;
11158 
11159   const SCEV *Res = Expr;
11160   int Last = Sizes.size() - 1;
11161   for (int i = Last; i >= 0; i--) {
11162     const SCEV *Q, *R;
11163     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11164 
11165     LLVM_DEBUG({
11166       dbgs() << "Res: " << *Res << "\n";
11167       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11168       dbgs() << "Res divided by Sizes[i]:\n";
11169       dbgs() << "Quotient: " << *Q << "\n";
11170       dbgs() << "Remainder: " << *R << "\n";
11171     });
11172 
11173     Res = Q;
11174 
11175     // Do not record the last subscript corresponding to the size of elements in
11176     // the array.
11177     if (i == Last) {
11178 
11179       // Bail out if the remainder is too complex.
11180       if (isa<SCEVAddRecExpr>(R)) {
11181         Subscripts.clear();
11182         Sizes.clear();
11183         return;
11184       }
11185 
11186       continue;
11187     }
11188 
11189     // Record the access function for the current subscript.
11190     Subscripts.push_back(R);
11191   }
11192 
11193   // Also push in last position the remainder of the last division: it will be
11194   // the access function of the innermost dimension.
11195   Subscripts.push_back(Res);
11196 
11197   std::reverse(Subscripts.begin(), Subscripts.end());
11198 
11199   LLVM_DEBUG({
11200     dbgs() << "Subscripts:\n";
11201     for (const SCEV *S : Subscripts)
11202       dbgs() << *S << "\n";
11203   });
11204 }
11205 
11206 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11207 /// sizes of an array access. Returns the remainder of the delinearization that
11208 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11209 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11210 /// expressions in the stride and base of a SCEV corresponding to the
11211 /// computation of a GCD (greatest common divisor) of base and stride.  When
11212 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11213 ///
11214 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11215 ///
11216 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11217 ///
11218 ///    for (long i = 0; i < n; i++)
11219 ///      for (long j = 0; j < m; j++)
11220 ///        for (long k = 0; k < o; k++)
11221 ///          A[i][j][k] = 1.0;
11222 ///  }
11223 ///
11224 /// the delinearization input is the following AddRec SCEV:
11225 ///
11226 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11227 ///
11228 /// From this SCEV, we are able to say that the base offset of the access is %A
11229 /// because it appears as an offset that does not divide any of the strides in
11230 /// the loops:
11231 ///
11232 ///  CHECK: Base offset: %A
11233 ///
11234 /// and then SCEV->delinearize determines the size of some of the dimensions of
11235 /// the array as these are the multiples by which the strides are happening:
11236 ///
11237 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11238 ///
11239 /// Note that the outermost dimension remains of UnknownSize because there are
11240 /// no strides that would help identifying the size of the last dimension: when
11241 /// the array has been statically allocated, one could compute the size of that
11242 /// dimension by dividing the overall size of the array by the size of the known
11243 /// dimensions: %m * %o * 8.
11244 ///
11245 /// Finally delinearize provides the access functions for the array reference
11246 /// that does correspond to A[i][j][k] of the above C testcase:
11247 ///
11248 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11249 ///
11250 /// The testcases are checking the output of a function pass:
11251 /// DelinearizationPass that walks through all loads and stores of a function
11252 /// asking for the SCEV of the memory access with respect to all enclosing
11253 /// loops, calling SCEV->delinearize on that and printing the results.
11254 void ScalarEvolution::delinearize(const SCEV *Expr,
11255                                  SmallVectorImpl<const SCEV *> &Subscripts,
11256                                  SmallVectorImpl<const SCEV *> &Sizes,
11257                                  const SCEV *ElementSize) {
11258   // First step: collect parametric terms.
11259   SmallVector<const SCEV *, 4> Terms;
11260   collectParametricTerms(Expr, Terms);
11261 
11262   if (Terms.empty())
11263     return;
11264 
11265   // Second step: find subscript sizes.
11266   findArrayDimensions(Terms, Sizes, ElementSize);
11267 
11268   if (Sizes.empty())
11269     return;
11270 
11271   // Third step: compute the access functions for each subscript.
11272   computeAccessFunctions(Expr, Subscripts, Sizes);
11273 
11274   if (Subscripts.empty())
11275     return;
11276 
11277   LLVM_DEBUG({
11278     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11279     dbgs() << "ArrayDecl[UnknownSize]";
11280     for (const SCEV *S : Sizes)
11281       dbgs() << "[" << *S << "]";
11282 
11283     dbgs() << "\nArrayRef";
11284     for (const SCEV *S : Subscripts)
11285       dbgs() << "[" << *S << "]";
11286     dbgs() << "\n";
11287   });
11288 }
11289 
11290 //===----------------------------------------------------------------------===//
11291 //                   SCEVCallbackVH Class Implementation
11292 //===----------------------------------------------------------------------===//
11293 
11294 void ScalarEvolution::SCEVCallbackVH::deleted() {
11295   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11296   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11297     SE->ConstantEvolutionLoopExitValue.erase(PN);
11298   SE->eraseValueFromMap(getValPtr());
11299   // this now dangles!
11300 }
11301 
11302 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11303   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11304 
11305   // Forget all the expressions associated with users of the old value,
11306   // so that future queries will recompute the expressions using the new
11307   // value.
11308   Value *Old = getValPtr();
11309   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11310   SmallPtrSet<User *, 8> Visited;
11311   while (!Worklist.empty()) {
11312     User *U = Worklist.pop_back_val();
11313     // Deleting the Old value will cause this to dangle. Postpone
11314     // that until everything else is done.
11315     if (U == Old)
11316       continue;
11317     if (!Visited.insert(U).second)
11318       continue;
11319     if (PHINode *PN = dyn_cast<PHINode>(U))
11320       SE->ConstantEvolutionLoopExitValue.erase(PN);
11321     SE->eraseValueFromMap(U);
11322     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11323   }
11324   // Delete the Old value.
11325   if (PHINode *PN = dyn_cast<PHINode>(Old))
11326     SE->ConstantEvolutionLoopExitValue.erase(PN);
11327   SE->eraseValueFromMap(Old);
11328   // this now dangles!
11329 }
11330 
11331 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11332   : CallbackVH(V), SE(se) {}
11333 
11334 //===----------------------------------------------------------------------===//
11335 //                   ScalarEvolution Class Implementation
11336 //===----------------------------------------------------------------------===//
11337 
11338 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11339                                  AssumptionCache &AC, DominatorTree &DT,
11340                                  LoopInfo &LI)
11341     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11342       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11343       LoopDispositions(64), BlockDispositions(64) {
11344   // To use guards for proving predicates, we need to scan every instruction in
11345   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11346   // time if the IR does not actually contain any calls to
11347   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11348   //
11349   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11350   // to _add_ guards to the module when there weren't any before, and wants
11351   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11352   // efficient in lieu of being smart in that rather obscure case.
11353 
11354   auto *GuardDecl = F.getParent()->getFunction(
11355       Intrinsic::getName(Intrinsic::experimental_guard));
11356   HasGuards = GuardDecl && !GuardDecl->use_empty();
11357 }
11358 
11359 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11360     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11361       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11362       ValueExprMap(std::move(Arg.ValueExprMap)),
11363       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11364       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11365       PendingMerges(std::move(Arg.PendingMerges)),
11366       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11367       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11368       PredicatedBackedgeTakenCounts(
11369           std::move(Arg.PredicatedBackedgeTakenCounts)),
11370       ConstantEvolutionLoopExitValue(
11371           std::move(Arg.ConstantEvolutionLoopExitValue)),
11372       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11373       LoopDispositions(std::move(Arg.LoopDispositions)),
11374       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11375       BlockDispositions(std::move(Arg.BlockDispositions)),
11376       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11377       SignedRanges(std::move(Arg.SignedRanges)),
11378       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11379       UniquePreds(std::move(Arg.UniquePreds)),
11380       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11381       LoopUsers(std::move(Arg.LoopUsers)),
11382       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11383       FirstUnknown(Arg.FirstUnknown) {
11384   Arg.FirstUnknown = nullptr;
11385 }
11386 
11387 ScalarEvolution::~ScalarEvolution() {
11388   // Iterate through all the SCEVUnknown instances and call their
11389   // destructors, so that they release their references to their values.
11390   for (SCEVUnknown *U = FirstUnknown; U;) {
11391     SCEVUnknown *Tmp = U;
11392     U = U->Next;
11393     Tmp->~SCEVUnknown();
11394   }
11395   FirstUnknown = nullptr;
11396 
11397   ExprValueMap.clear();
11398   ValueExprMap.clear();
11399   HasRecMap.clear();
11400 
11401   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11402   // that a loop had multiple computable exits.
11403   for (auto &BTCI : BackedgeTakenCounts)
11404     BTCI.second.clear();
11405   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11406     BTCI.second.clear();
11407 
11408   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11409   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11410   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11411   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11412   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11413 }
11414 
11415 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11416   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11417 }
11418 
11419 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11420                           const Loop *L) {
11421   // Print all inner loops first
11422   for (Loop *I : *L)
11423     PrintLoopInfo(OS, SE, I);
11424 
11425   OS << "Loop ";
11426   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11427   OS << ": ";
11428 
11429   SmallVector<BasicBlock *, 8> ExitBlocks;
11430   L->getExitBlocks(ExitBlocks);
11431   if (ExitBlocks.size() != 1)
11432     OS << "<multiple exits> ";
11433 
11434   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11435     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
11436   } else {
11437     OS << "Unpredictable backedge-taken count. ";
11438   }
11439 
11440   OS << "\n"
11441         "Loop ";
11442   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11443   OS << ": ";
11444 
11445   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
11446     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
11447     if (SE->isBackedgeTakenCountMaxOrZero(L))
11448       OS << ", actual taken count either this or zero.";
11449   } else {
11450     OS << "Unpredictable max backedge-taken count. ";
11451   }
11452 
11453   OS << "\n"
11454         "Loop ";
11455   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11456   OS << ": ";
11457 
11458   SCEVUnionPredicate Pred;
11459   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11460   if (!isa<SCEVCouldNotCompute>(PBT)) {
11461     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11462     OS << " Predicates:\n";
11463     Pred.print(OS, 4);
11464   } else {
11465     OS << "Unpredictable predicated backedge-taken count. ";
11466   }
11467   OS << "\n";
11468 
11469   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11470     OS << "Loop ";
11471     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11472     OS << ": ";
11473     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11474   }
11475 }
11476 
11477 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11478   switch (LD) {
11479   case ScalarEvolution::LoopVariant:
11480     return "Variant";
11481   case ScalarEvolution::LoopInvariant:
11482     return "Invariant";
11483   case ScalarEvolution::LoopComputable:
11484     return "Computable";
11485   }
11486   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11487 }
11488 
11489 void ScalarEvolution::print(raw_ostream &OS) const {
11490   // ScalarEvolution's implementation of the print method is to print
11491   // out SCEV values of all instructions that are interesting. Doing
11492   // this potentially causes it to create new SCEV objects though,
11493   // which technically conflicts with the const qualifier. This isn't
11494   // observable from outside the class though, so casting away the
11495   // const isn't dangerous.
11496   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11497 
11498   OS << "Classifying expressions for: ";
11499   F.printAsOperand(OS, /*PrintType=*/false);
11500   OS << "\n";
11501   for (Instruction &I : instructions(F))
11502     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11503       OS << I << '\n';
11504       OS << "  -->  ";
11505       const SCEV *SV = SE.getSCEV(&I);
11506       SV->print(OS);
11507       if (!isa<SCEVCouldNotCompute>(SV)) {
11508         OS << " U: ";
11509         SE.getUnsignedRange(SV).print(OS);
11510         OS << " S: ";
11511         SE.getSignedRange(SV).print(OS);
11512       }
11513 
11514       const Loop *L = LI.getLoopFor(I.getParent());
11515 
11516       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11517       if (AtUse != SV) {
11518         OS << "  -->  ";
11519         AtUse->print(OS);
11520         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11521           OS << " U: ";
11522           SE.getUnsignedRange(AtUse).print(OS);
11523           OS << " S: ";
11524           SE.getSignedRange(AtUse).print(OS);
11525         }
11526       }
11527 
11528       if (L) {
11529         OS << "\t\t" "Exits: ";
11530         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11531         if (!SE.isLoopInvariant(ExitValue, L)) {
11532           OS << "<<Unknown>>";
11533         } else {
11534           OS << *ExitValue;
11535         }
11536 
11537         bool First = true;
11538         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11539           if (First) {
11540             OS << "\t\t" "LoopDispositions: { ";
11541             First = false;
11542           } else {
11543             OS << ", ";
11544           }
11545 
11546           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11547           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11548         }
11549 
11550         for (auto *InnerL : depth_first(L)) {
11551           if (InnerL == L)
11552             continue;
11553           if (First) {
11554             OS << "\t\t" "LoopDispositions: { ";
11555             First = false;
11556           } else {
11557             OS << ", ";
11558           }
11559 
11560           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11561           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11562         }
11563 
11564         OS << " }";
11565       }
11566 
11567       OS << "\n";
11568     }
11569 
11570   OS << "Determining loop execution counts for: ";
11571   F.printAsOperand(OS, /*PrintType=*/false);
11572   OS << "\n";
11573   for (Loop *I : LI)
11574     PrintLoopInfo(OS, &SE, I);
11575 }
11576 
11577 ScalarEvolution::LoopDisposition
11578 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11579   auto &Values = LoopDispositions[S];
11580   for (auto &V : Values) {
11581     if (V.getPointer() == L)
11582       return V.getInt();
11583   }
11584   Values.emplace_back(L, LoopVariant);
11585   LoopDisposition D = computeLoopDisposition(S, L);
11586   auto &Values2 = LoopDispositions[S];
11587   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11588     if (V.getPointer() == L) {
11589       V.setInt(D);
11590       break;
11591     }
11592   }
11593   return D;
11594 }
11595 
11596 ScalarEvolution::LoopDisposition
11597 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11598   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11599   case scConstant:
11600     return LoopInvariant;
11601   case scTruncate:
11602   case scZeroExtend:
11603   case scSignExtend:
11604     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11605   case scAddRecExpr: {
11606     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11607 
11608     // If L is the addrec's loop, it's computable.
11609     if (AR->getLoop() == L)
11610       return LoopComputable;
11611 
11612     // Add recurrences are never invariant in the function-body (null loop).
11613     if (!L)
11614       return LoopVariant;
11615 
11616     // Everything that is not defined at loop entry is variant.
11617     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11618       return LoopVariant;
11619     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11620            " dominate the contained loop's header?");
11621 
11622     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11623     if (AR->getLoop()->contains(L))
11624       return LoopInvariant;
11625 
11626     // This recurrence is variant w.r.t. L if any of its operands
11627     // are variant.
11628     for (auto *Op : AR->operands())
11629       if (!isLoopInvariant(Op, L))
11630         return LoopVariant;
11631 
11632     // Otherwise it's loop-invariant.
11633     return LoopInvariant;
11634   }
11635   case scAddExpr:
11636   case scMulExpr:
11637   case scUMaxExpr:
11638   case scSMaxExpr: {
11639     bool HasVarying = false;
11640     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11641       LoopDisposition D = getLoopDisposition(Op, L);
11642       if (D == LoopVariant)
11643         return LoopVariant;
11644       if (D == LoopComputable)
11645         HasVarying = true;
11646     }
11647     return HasVarying ? LoopComputable : LoopInvariant;
11648   }
11649   case scUDivExpr: {
11650     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11651     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11652     if (LD == LoopVariant)
11653       return LoopVariant;
11654     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11655     if (RD == LoopVariant)
11656       return LoopVariant;
11657     return (LD == LoopInvariant && RD == LoopInvariant) ?
11658            LoopInvariant : LoopComputable;
11659   }
11660   case scUnknown:
11661     // All non-instruction values are loop invariant.  All instructions are loop
11662     // invariant if they are not contained in the specified loop.
11663     // Instructions are never considered invariant in the function body
11664     // (null loop) because they are defined within the "loop".
11665     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11666       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11667     return LoopInvariant;
11668   case scCouldNotCompute:
11669     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11670   }
11671   llvm_unreachable("Unknown SCEV kind!");
11672 }
11673 
11674 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11675   return getLoopDisposition(S, L) == LoopInvariant;
11676 }
11677 
11678 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11679   return getLoopDisposition(S, L) == LoopComputable;
11680 }
11681 
11682 ScalarEvolution::BlockDisposition
11683 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11684   auto &Values = BlockDispositions[S];
11685   for (auto &V : Values) {
11686     if (V.getPointer() == BB)
11687       return V.getInt();
11688   }
11689   Values.emplace_back(BB, DoesNotDominateBlock);
11690   BlockDisposition D = computeBlockDisposition(S, BB);
11691   auto &Values2 = BlockDispositions[S];
11692   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11693     if (V.getPointer() == BB) {
11694       V.setInt(D);
11695       break;
11696     }
11697   }
11698   return D;
11699 }
11700 
11701 ScalarEvolution::BlockDisposition
11702 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11703   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11704   case scConstant:
11705     return ProperlyDominatesBlock;
11706   case scTruncate:
11707   case scZeroExtend:
11708   case scSignExtend:
11709     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11710   case scAddRecExpr: {
11711     // This uses a "dominates" query instead of "properly dominates" query
11712     // to test for proper dominance too, because the instruction which
11713     // produces the addrec's value is a PHI, and a PHI effectively properly
11714     // dominates its entire containing block.
11715     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11716     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11717       return DoesNotDominateBlock;
11718 
11719     // Fall through into SCEVNAryExpr handling.
11720     LLVM_FALLTHROUGH;
11721   }
11722   case scAddExpr:
11723   case scMulExpr:
11724   case scUMaxExpr:
11725   case scSMaxExpr: {
11726     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11727     bool Proper = true;
11728     for (const SCEV *NAryOp : NAry->operands()) {
11729       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11730       if (D == DoesNotDominateBlock)
11731         return DoesNotDominateBlock;
11732       if (D == DominatesBlock)
11733         Proper = false;
11734     }
11735     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11736   }
11737   case scUDivExpr: {
11738     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11739     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11740     BlockDisposition LD = getBlockDisposition(LHS, BB);
11741     if (LD == DoesNotDominateBlock)
11742       return DoesNotDominateBlock;
11743     BlockDisposition RD = getBlockDisposition(RHS, BB);
11744     if (RD == DoesNotDominateBlock)
11745       return DoesNotDominateBlock;
11746     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11747       ProperlyDominatesBlock : DominatesBlock;
11748   }
11749   case scUnknown:
11750     if (Instruction *I =
11751           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11752       if (I->getParent() == BB)
11753         return DominatesBlock;
11754       if (DT.properlyDominates(I->getParent(), BB))
11755         return ProperlyDominatesBlock;
11756       return DoesNotDominateBlock;
11757     }
11758     return ProperlyDominatesBlock;
11759   case scCouldNotCompute:
11760     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11761   }
11762   llvm_unreachable("Unknown SCEV kind!");
11763 }
11764 
11765 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11766   return getBlockDisposition(S, BB) >= DominatesBlock;
11767 }
11768 
11769 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11770   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11771 }
11772 
11773 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11774   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11775 }
11776 
11777 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11778   auto IsS = [&](const SCEV *X) { return S == X; };
11779   auto ContainsS = [&](const SCEV *X) {
11780     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11781   };
11782   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11783 }
11784 
11785 void
11786 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11787   ValuesAtScopes.erase(S);
11788   LoopDispositions.erase(S);
11789   BlockDispositions.erase(S);
11790   UnsignedRanges.erase(S);
11791   SignedRanges.erase(S);
11792   ExprValueMap.erase(S);
11793   HasRecMap.erase(S);
11794   MinTrailingZerosCache.erase(S);
11795 
11796   for (auto I = PredicatedSCEVRewrites.begin();
11797        I != PredicatedSCEVRewrites.end();) {
11798     std::pair<const SCEV *, const Loop *> Entry = I->first;
11799     if (Entry.first == S)
11800       PredicatedSCEVRewrites.erase(I++);
11801     else
11802       ++I;
11803   }
11804 
11805   auto RemoveSCEVFromBackedgeMap =
11806       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11807         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11808           BackedgeTakenInfo &BEInfo = I->second;
11809           if (BEInfo.hasOperand(S, this)) {
11810             BEInfo.clear();
11811             Map.erase(I++);
11812           } else
11813             ++I;
11814         }
11815       };
11816 
11817   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11818   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11819 }
11820 
11821 void
11822 ScalarEvolution::getUsedLoops(const SCEV *S,
11823                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11824   struct FindUsedLoops {
11825     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11826         : LoopsUsed(LoopsUsed) {}
11827     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11828     bool follow(const SCEV *S) {
11829       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11830         LoopsUsed.insert(AR->getLoop());
11831       return true;
11832     }
11833 
11834     bool isDone() const { return false; }
11835   };
11836 
11837   FindUsedLoops F(LoopsUsed);
11838   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11839 }
11840 
11841 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11842   SmallPtrSet<const Loop *, 8> LoopsUsed;
11843   getUsedLoops(S, LoopsUsed);
11844   for (auto *L : LoopsUsed)
11845     LoopUsers[L].push_back(S);
11846 }
11847 
11848 void ScalarEvolution::verify() const {
11849   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11850   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11851 
11852   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11853 
11854   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11855   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11856     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11857 
11858     const SCEV *visitConstant(const SCEVConstant *Constant) {
11859       return SE.getConstant(Constant->getAPInt());
11860     }
11861 
11862     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11863       return SE.getUnknown(Expr->getValue());
11864     }
11865 
11866     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11867       return SE.getCouldNotCompute();
11868     }
11869   };
11870 
11871   SCEVMapper SCM(SE2);
11872 
11873   while (!LoopStack.empty()) {
11874     auto *L = LoopStack.pop_back_val();
11875     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11876 
11877     auto *CurBECount = SCM.visit(
11878         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11879     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11880 
11881     if (CurBECount == SE2.getCouldNotCompute() ||
11882         NewBECount == SE2.getCouldNotCompute()) {
11883       // NB! This situation is legal, but is very suspicious -- whatever pass
11884       // change the loop to make a trip count go from could not compute to
11885       // computable or vice-versa *should have* invalidated SCEV.  However, we
11886       // choose not to assert here (for now) since we don't want false
11887       // positives.
11888       continue;
11889     }
11890 
11891     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11892       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11893       // not propagate undef aggressively).  This means we can (and do) fail
11894       // verification in cases where a transform makes the trip count of a loop
11895       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11896       // both cases the loop iterates "undef" times, but SCEV thinks we
11897       // increased the trip count of the loop by 1 incorrectly.
11898       continue;
11899     }
11900 
11901     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11902         SE.getTypeSizeInBits(NewBECount->getType()))
11903       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11904     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11905              SE.getTypeSizeInBits(NewBECount->getType()))
11906       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11907 
11908     auto *ConstantDelta =
11909         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11910 
11911     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11912       dbgs() << "Trip Count Changed!\n";
11913       dbgs() << "Old: " << *CurBECount << "\n";
11914       dbgs() << "New: " << *NewBECount << "\n";
11915       dbgs() << "Delta: " << *ConstantDelta << "\n";
11916       std::abort();
11917     }
11918   }
11919 }
11920 
11921 bool ScalarEvolution::invalidate(
11922     Function &F, const PreservedAnalyses &PA,
11923     FunctionAnalysisManager::Invalidator &Inv) {
11924   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11925   // of its dependencies is invalidated.
11926   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11927   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11928          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11929          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11930          Inv.invalidate<LoopAnalysis>(F, PA);
11931 }
11932 
11933 AnalysisKey ScalarEvolutionAnalysis::Key;
11934 
11935 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11936                                              FunctionAnalysisManager &AM) {
11937   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11938                          AM.getResult<AssumptionAnalysis>(F),
11939                          AM.getResult<DominatorTreeAnalysis>(F),
11940                          AM.getResult<LoopAnalysis>(F));
11941 }
11942 
11943 PreservedAnalyses
11944 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11945   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11946   return PreservedAnalyses::all();
11947 }
11948 
11949 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11950                       "Scalar Evolution Analysis", false, true)
11951 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11952 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11953 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11954 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11955 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11956                     "Scalar Evolution Analysis", false, true)
11957 
11958 char ScalarEvolutionWrapperPass::ID = 0;
11959 
11960 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11961   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11962 }
11963 
11964 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11965   SE.reset(new ScalarEvolution(
11966       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11967       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11968       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11969       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11970   return false;
11971 }
11972 
11973 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11974 
11975 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11976   SE->print(OS);
11977 }
11978 
11979 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11980   if (!VerifySCEV)
11981     return;
11982 
11983   SE->verify();
11984 }
11985 
11986 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11987   AU.setPreservesAll();
11988   AU.addRequiredTransitive<AssumptionCacheTracker>();
11989   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11990   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11991   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11992 }
11993 
11994 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11995                                                         const SCEV *RHS) {
11996   FoldingSetNodeID ID;
11997   assert(LHS->getType() == RHS->getType() &&
11998          "Type mismatch between LHS and RHS");
11999   // Unique this node based on the arguments
12000   ID.AddInteger(SCEVPredicate::P_Equal);
12001   ID.AddPointer(LHS);
12002   ID.AddPointer(RHS);
12003   void *IP = nullptr;
12004   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12005     return S;
12006   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12007       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12008   UniquePreds.InsertNode(Eq, IP);
12009   return Eq;
12010 }
12011 
12012 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12013     const SCEVAddRecExpr *AR,
12014     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12015   FoldingSetNodeID ID;
12016   // Unique this node based on the arguments
12017   ID.AddInteger(SCEVPredicate::P_Wrap);
12018   ID.AddPointer(AR);
12019   ID.AddInteger(AddedFlags);
12020   void *IP = nullptr;
12021   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12022     return S;
12023   auto *OF = new (SCEVAllocator)
12024       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12025   UniquePreds.InsertNode(OF, IP);
12026   return OF;
12027 }
12028 
12029 namespace {
12030 
12031 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12032 public:
12033 
12034   /// Rewrites \p S in the context of a loop L and the SCEV predication
12035   /// infrastructure.
12036   ///
12037   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12038   /// equivalences present in \p Pred.
12039   ///
12040   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12041   /// \p NewPreds such that the result will be an AddRecExpr.
12042   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12043                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12044                              SCEVUnionPredicate *Pred) {
12045     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12046     return Rewriter.visit(S);
12047   }
12048 
12049   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12050     if (Pred) {
12051       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12052       for (auto *Pred : ExprPreds)
12053         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12054           if (IPred->getLHS() == Expr)
12055             return IPred->getRHS();
12056     }
12057     return convertToAddRecWithPreds(Expr);
12058   }
12059 
12060   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12061     const SCEV *Operand = visit(Expr->getOperand());
12062     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12063     if (AR && AR->getLoop() == L && AR->isAffine()) {
12064       // This couldn't be folded because the operand didn't have the nuw
12065       // flag. Add the nusw flag as an assumption that we could make.
12066       const SCEV *Step = AR->getStepRecurrence(SE);
12067       Type *Ty = Expr->getType();
12068       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12069         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12070                                 SE.getSignExtendExpr(Step, Ty), L,
12071                                 AR->getNoWrapFlags());
12072     }
12073     return SE.getZeroExtendExpr(Operand, Expr->getType());
12074   }
12075 
12076   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12077     const SCEV *Operand = visit(Expr->getOperand());
12078     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12079     if (AR && AR->getLoop() == L && AR->isAffine()) {
12080       // This couldn't be folded because the operand didn't have the nsw
12081       // flag. Add the nssw flag as an assumption that we could make.
12082       const SCEV *Step = AR->getStepRecurrence(SE);
12083       Type *Ty = Expr->getType();
12084       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12085         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12086                                 SE.getSignExtendExpr(Step, Ty), L,
12087                                 AR->getNoWrapFlags());
12088     }
12089     return SE.getSignExtendExpr(Operand, Expr->getType());
12090   }
12091 
12092 private:
12093   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12094                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12095                         SCEVUnionPredicate *Pred)
12096       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12097 
12098   bool addOverflowAssumption(const SCEVPredicate *P) {
12099     if (!NewPreds) {
12100       // Check if we've already made this assumption.
12101       return Pred && Pred->implies(P);
12102     }
12103     NewPreds->insert(P);
12104     return true;
12105   }
12106 
12107   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12108                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12109     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12110     return addOverflowAssumption(A);
12111   }
12112 
12113   // If \p Expr represents a PHINode, we try to see if it can be represented
12114   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12115   // to add this predicate as a runtime overflow check, we return the AddRec.
12116   // If \p Expr does not meet these conditions (is not a PHI node, or we
12117   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12118   // return \p Expr.
12119   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12120     if (!isa<PHINode>(Expr->getValue()))
12121       return Expr;
12122     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12123     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12124     if (!PredicatedRewrite)
12125       return Expr;
12126     for (auto *P : PredicatedRewrite->second){
12127       // Wrap predicates from outer loops are not supported.
12128       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12129         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12130         if (L != AR->getLoop())
12131           return Expr;
12132       }
12133       if (!addOverflowAssumption(P))
12134         return Expr;
12135     }
12136     return PredicatedRewrite->first;
12137   }
12138 
12139   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12140   SCEVUnionPredicate *Pred;
12141   const Loop *L;
12142 };
12143 
12144 } // end anonymous namespace
12145 
12146 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12147                                                    SCEVUnionPredicate &Preds) {
12148   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12149 }
12150 
12151 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12152     const SCEV *S, const Loop *L,
12153     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12154   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12155   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12156   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12157 
12158   if (!AddRec)
12159     return nullptr;
12160 
12161   // Since the transformation was successful, we can now transfer the SCEV
12162   // predicates.
12163   for (auto *P : TransformPreds)
12164     Preds.insert(P);
12165 
12166   return AddRec;
12167 }
12168 
12169 /// SCEV predicates
12170 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12171                              SCEVPredicateKind Kind)
12172     : FastID(ID), Kind(Kind) {}
12173 
12174 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12175                                        const SCEV *LHS, const SCEV *RHS)
12176     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12177   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12178   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12179 }
12180 
12181 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12182   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12183 
12184   if (!Op)
12185     return false;
12186 
12187   return Op->LHS == LHS && Op->RHS == RHS;
12188 }
12189 
12190 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12191 
12192 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12193 
12194 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12195   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12196 }
12197 
12198 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12199                                      const SCEVAddRecExpr *AR,
12200                                      IncrementWrapFlags Flags)
12201     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12202 
12203 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12204 
12205 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12206   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12207 
12208   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12209 }
12210 
12211 bool SCEVWrapPredicate::isAlwaysTrue() const {
12212   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12213   IncrementWrapFlags IFlags = Flags;
12214 
12215   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12216     IFlags = clearFlags(IFlags, IncrementNSSW);
12217 
12218   return IFlags == IncrementAnyWrap;
12219 }
12220 
12221 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12222   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12223   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12224     OS << "<nusw>";
12225   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12226     OS << "<nssw>";
12227   OS << "\n";
12228 }
12229 
12230 SCEVWrapPredicate::IncrementWrapFlags
12231 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12232                                    ScalarEvolution &SE) {
12233   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12234   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12235 
12236   // We can safely transfer the NSW flag as NSSW.
12237   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12238     ImpliedFlags = IncrementNSSW;
12239 
12240   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12241     // If the increment is positive, the SCEV NUW flag will also imply the
12242     // WrapPredicate NUSW flag.
12243     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12244       if (Step->getValue()->getValue().isNonNegative())
12245         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12246   }
12247 
12248   return ImpliedFlags;
12249 }
12250 
12251 /// Union predicates don't get cached so create a dummy set ID for it.
12252 SCEVUnionPredicate::SCEVUnionPredicate()
12253     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12254 
12255 bool SCEVUnionPredicate::isAlwaysTrue() const {
12256   return all_of(Preds,
12257                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12258 }
12259 
12260 ArrayRef<const SCEVPredicate *>
12261 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12262   auto I = SCEVToPreds.find(Expr);
12263   if (I == SCEVToPreds.end())
12264     return ArrayRef<const SCEVPredicate *>();
12265   return I->second;
12266 }
12267 
12268 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12269   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12270     return all_of(Set->Preds,
12271                   [this](const SCEVPredicate *I) { return this->implies(I); });
12272 
12273   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12274   if (ScevPredsIt == SCEVToPreds.end())
12275     return false;
12276   auto &SCEVPreds = ScevPredsIt->second;
12277 
12278   return any_of(SCEVPreds,
12279                 [N](const SCEVPredicate *I) { return I->implies(N); });
12280 }
12281 
12282 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12283 
12284 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12285   for (auto Pred : Preds)
12286     Pred->print(OS, Depth);
12287 }
12288 
12289 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12290   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12291     for (auto Pred : Set->Preds)
12292       add(Pred);
12293     return;
12294   }
12295 
12296   if (implies(N))
12297     return;
12298 
12299   const SCEV *Key = N->getExpr();
12300   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12301                 " associated expression!");
12302 
12303   SCEVToPreds[Key].push_back(N);
12304   Preds.push_back(N);
12305 }
12306 
12307 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12308                                                      Loop &L)
12309     : SE(SE), L(L) {}
12310 
12311 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12312   const SCEV *Expr = SE.getSCEV(V);
12313   RewriteEntry &Entry = RewriteMap[Expr];
12314 
12315   // If we already have an entry and the version matches, return it.
12316   if (Entry.second && Generation == Entry.first)
12317     return Entry.second;
12318 
12319   // We found an entry but it's stale. Rewrite the stale entry
12320   // according to the current predicate.
12321   if (Entry.second)
12322     Expr = Entry.second;
12323 
12324   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12325   Entry = {Generation, NewSCEV};
12326 
12327   return NewSCEV;
12328 }
12329 
12330 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12331   if (!BackedgeCount) {
12332     SCEVUnionPredicate BackedgePred;
12333     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12334     addPredicate(BackedgePred);
12335   }
12336   return BackedgeCount;
12337 }
12338 
12339 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12340   if (Preds.implies(&Pred))
12341     return;
12342   Preds.add(&Pred);
12343   updateGeneration();
12344 }
12345 
12346 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12347   return Preds;
12348 }
12349 
12350 void PredicatedScalarEvolution::updateGeneration() {
12351   // If the generation number wrapped recompute everything.
12352   if (++Generation == 0) {
12353     for (auto &II : RewriteMap) {
12354       const SCEV *Rewritten = II.second.second;
12355       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12356     }
12357   }
12358 }
12359 
12360 void PredicatedScalarEvolution::setNoOverflow(
12361     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12362   const SCEV *Expr = getSCEV(V);
12363   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12364 
12365   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12366 
12367   // Clear the statically implied flags.
12368   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12369   addPredicate(*SE.getWrapPredicate(AR, Flags));
12370 
12371   auto II = FlagsMap.insert({V, Flags});
12372   if (!II.second)
12373     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12374 }
12375 
12376 bool PredicatedScalarEvolution::hasNoOverflow(
12377     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12378   const SCEV *Expr = getSCEV(V);
12379   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12380 
12381   Flags = SCEVWrapPredicate::clearFlags(
12382       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12383 
12384   auto II = FlagsMap.find(V);
12385 
12386   if (II != FlagsMap.end())
12387     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12388 
12389   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12390 }
12391 
12392 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12393   const SCEV *Expr = this->getSCEV(V);
12394   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12395   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12396 
12397   if (!New)
12398     return nullptr;
12399 
12400   for (auto *P : NewPreds)
12401     Preds.add(P);
12402 
12403   updateGeneration();
12404   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12405   return New;
12406 }
12407 
12408 PredicatedScalarEvolution::PredicatedScalarEvolution(
12409     const PredicatedScalarEvolution &Init)
12410     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12411       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12412   for (const auto &I : Init.FlagsMap)
12413     FlagsMap.insert(I);
12414 }
12415 
12416 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12417   // For each block.
12418   for (auto *BB : L.getBlocks())
12419     for (auto &I : *BB) {
12420       if (!SE.isSCEVable(I.getType()))
12421         continue;
12422 
12423       auto *Expr = SE.getSCEV(&I);
12424       auto II = RewriteMap.find(Expr);
12425 
12426       if (II == RewriteMap.end())
12427         continue;
12428 
12429       // Don't print things that are not interesting.
12430       if (II->second.second == Expr)
12431         continue;
12432 
12433       OS.indent(Depth) << "[PSE]" << I << ":\n";
12434       OS.indent(Depth + 2) << *Expr << "\n";
12435       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12436     }
12437 }
12438 
12439 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12440 // arbitrary expressions.
12441 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12442 // 4, A / B becomes X / 8).
12443 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
12444                                 const SCEV *&RHS) {
12445   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
12446   if (Add == nullptr || Add->getNumOperands() != 2)
12447     return false;
12448 
12449   const SCEV *A = Add->getOperand(1);
12450   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
12451 
12452   if (Mul == nullptr)
12453     return false;
12454 
12455   const auto MatchURemWithDivisor = [&](const SCEV *B) {
12456     // (SomeExpr + (-(SomeExpr / B) * B)).
12457     if (Expr == getURemExpr(A, B)) {
12458       LHS = A;
12459       RHS = B;
12460       return true;
12461     }
12462     return false;
12463   };
12464 
12465   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12466   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12467     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12468            MatchURemWithDivisor(Mul->getOperand(2));
12469 
12470   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12471   if (Mul->getNumOperands() == 2)
12472     return MatchURemWithDivisor(Mul->getOperand(1)) ||
12473            MatchURemWithDivisor(Mul->getOperand(0)) ||
12474            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12475            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
12476   return false;
12477 }
12478