xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 8c209aa8779de57771b64896f805e14cc0016dcd)
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/Optional.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/ScopeExit.h"
65 #include "llvm/ADT/Sequence.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/Statistic.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/ConstantFolding.h"
70 #include "llvm/Analysis/InstructionSimplify.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
73 #include "llvm/Analysis/TargetLibraryInfo.h"
74 #include "llvm/Analysis/ValueTracking.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Dominators.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/GlobalAlias.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/InstIterator.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/LLVMContext.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/Operator.h"
88 #include "llvm/IR/PatternMatch.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include "llvm/Support/MathExtras.h"
93 #include "llvm/Support/raw_ostream.h"
94 #include "llvm/Support/SaveAndRestore.h"
95 #include <algorithm>
96 using namespace llvm;
97 
98 #define DEBUG_TYPE "scalar-evolution"
99 
100 STATISTIC(NumArrayLenItCounts,
101           "Number of trip counts computed with array length");
102 STATISTIC(NumTripCountsComputed,
103           "Number of loops with predictable loop counts");
104 STATISTIC(NumTripCountsNotComputed,
105           "Number of loops without predictable loop counts");
106 STATISTIC(NumBruteForceTripCountsComputed,
107           "Number of loops with trip counts computed by force");
108 
109 static cl::opt<unsigned>
110 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
111                         cl::desc("Maximum number of iterations SCEV will "
112                                  "symbolically execute a constant "
113                                  "derived loop"),
114                         cl::init(100));
115 
116 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
117 static cl::opt<bool>
118 VerifySCEV("verify-scev",
119            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
120 static cl::opt<bool>
121     VerifySCEVMap("verify-scev-maps",
122                   cl::desc("Verify no dangling value in ScalarEvolution's "
123                            "ExprValueMap (slow)"));
124 
125 static cl::opt<unsigned> MulOpsInlineThreshold(
126     "scev-mulops-inline-threshold", cl::Hidden,
127     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
128     cl::init(1000));
129 
130 static cl::opt<unsigned> AddOpsInlineThreshold(
131     "scev-addops-inline-threshold", cl::Hidden,
132     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
133     cl::init(500));
134 
135 static cl::opt<unsigned>
136     MaxCompareDepth("scalar-evolution-max-compare-depth", cl::Hidden,
137                     cl::desc("Maximum depth of recursive compare complexity"),
138                     cl::init(32));
139 
140 static cl::opt<unsigned> MaxConstantEvolvingDepth(
141     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
142     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
143 
144 //===----------------------------------------------------------------------===//
145 //                           SCEV class definitions
146 //===----------------------------------------------------------------------===//
147 
148 //===----------------------------------------------------------------------===//
149 // Implementation of the SCEV class.
150 //
151 
152 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
153 LLVM_DUMP_METHOD void SCEV::dump() const {
154   print(dbgs());
155   dbgs() << '\n';
156 }
157 #endif
158 
159 void SCEV::print(raw_ostream &OS) const {
160   switch (static_cast<SCEVTypes>(getSCEVType())) {
161   case scConstant:
162     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
163     return;
164   case scTruncate: {
165     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
166     const SCEV *Op = Trunc->getOperand();
167     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
168        << *Trunc->getType() << ")";
169     return;
170   }
171   case scZeroExtend: {
172     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
173     const SCEV *Op = ZExt->getOperand();
174     OS << "(zext " << *Op->getType() << " " << *Op << " to "
175        << *ZExt->getType() << ")";
176     return;
177   }
178   case scSignExtend: {
179     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
180     const SCEV *Op = SExt->getOperand();
181     OS << "(sext " << *Op->getType() << " " << *Op << " to "
182        << *SExt->getType() << ")";
183     return;
184   }
185   case scAddRecExpr: {
186     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
187     OS << "{" << *AR->getOperand(0);
188     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
189       OS << ",+," << *AR->getOperand(i);
190     OS << "}<";
191     if (AR->hasNoUnsignedWrap())
192       OS << "nuw><";
193     if (AR->hasNoSignedWrap())
194       OS << "nsw><";
195     if (AR->hasNoSelfWrap() &&
196         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
197       OS << "nw><";
198     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
199     OS << ">";
200     return;
201   }
202   case scAddExpr:
203   case scMulExpr:
204   case scUMaxExpr:
205   case scSMaxExpr: {
206     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
207     const char *OpStr = nullptr;
208     switch (NAry->getSCEVType()) {
209     case scAddExpr: OpStr = " + "; break;
210     case scMulExpr: OpStr = " * "; break;
211     case scUMaxExpr: OpStr = " umax "; break;
212     case scSMaxExpr: OpStr = " smax "; break;
213     }
214     OS << "(";
215     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
216          I != E; ++I) {
217       OS << **I;
218       if (std::next(I) != E)
219         OS << OpStr;
220     }
221     OS << ")";
222     switch (NAry->getSCEVType()) {
223     case scAddExpr:
224     case scMulExpr:
225       if (NAry->hasNoUnsignedWrap())
226         OS << "<nuw>";
227       if (NAry->hasNoSignedWrap())
228         OS << "<nsw>";
229     }
230     return;
231   }
232   case scUDivExpr: {
233     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
234     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
235     return;
236   }
237   case scUnknown: {
238     const SCEVUnknown *U = cast<SCEVUnknown>(this);
239     Type *AllocTy;
240     if (U->isSizeOf(AllocTy)) {
241       OS << "sizeof(" << *AllocTy << ")";
242       return;
243     }
244     if (U->isAlignOf(AllocTy)) {
245       OS << "alignof(" << *AllocTy << ")";
246       return;
247     }
248 
249     Type *CTy;
250     Constant *FieldNo;
251     if (U->isOffsetOf(CTy, FieldNo)) {
252       OS << "offsetof(" << *CTy << ", ";
253       FieldNo->printAsOperand(OS, false);
254       OS << ")";
255       return;
256     }
257 
258     // Otherwise just print it normally.
259     U->getValue()->printAsOperand(OS, false);
260     return;
261   }
262   case scCouldNotCompute:
263     OS << "***COULDNOTCOMPUTE***";
264     return;
265   }
266   llvm_unreachable("Unknown SCEV kind!");
267 }
268 
269 Type *SCEV::getType() const {
270   switch (static_cast<SCEVTypes>(getSCEVType())) {
271   case scConstant:
272     return cast<SCEVConstant>(this)->getType();
273   case scTruncate:
274   case scZeroExtend:
275   case scSignExtend:
276     return cast<SCEVCastExpr>(this)->getType();
277   case scAddRecExpr:
278   case scMulExpr:
279   case scUMaxExpr:
280   case scSMaxExpr:
281     return cast<SCEVNAryExpr>(this)->getType();
282   case scAddExpr:
283     return cast<SCEVAddExpr>(this)->getType();
284   case scUDivExpr:
285     return cast<SCEVUDivExpr>(this)->getType();
286   case scUnknown:
287     return cast<SCEVUnknown>(this)->getType();
288   case scCouldNotCompute:
289     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
290   }
291   llvm_unreachable("Unknown SCEV kind!");
292 }
293 
294 bool SCEV::isZero() const {
295   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
296     return SC->getValue()->isZero();
297   return false;
298 }
299 
300 bool SCEV::isOne() const {
301   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
302     return SC->getValue()->isOne();
303   return false;
304 }
305 
306 bool SCEV::isAllOnesValue() const {
307   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
308     return SC->getValue()->isAllOnesValue();
309   return false;
310 }
311 
312 bool SCEV::isNonConstantNegative() const {
313   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
314   if (!Mul) return false;
315 
316   // If there is a constant factor, it will be first.
317   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
318   if (!SC) return false;
319 
320   // Return true if the value is negative, this matches things like (-42 * V).
321   return SC->getAPInt().isNegative();
322 }
323 
324 SCEVCouldNotCompute::SCEVCouldNotCompute() :
325   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
326 
327 bool SCEVCouldNotCompute::classof(const SCEV *S) {
328   return S->getSCEVType() == scCouldNotCompute;
329 }
330 
331 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
332   FoldingSetNodeID ID;
333   ID.AddInteger(scConstant);
334   ID.AddPointer(V);
335   void *IP = nullptr;
336   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
337   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
338   UniqueSCEVs.InsertNode(S, IP);
339   return S;
340 }
341 
342 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
343   return getConstant(ConstantInt::get(getContext(), Val));
344 }
345 
346 const SCEV *
347 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
348   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
349   return getConstant(ConstantInt::get(ITy, V, isSigned));
350 }
351 
352 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
353                            unsigned SCEVTy, const SCEV *op, Type *ty)
354   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
355 
356 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
357                                    const SCEV *op, Type *ty)
358   : SCEVCastExpr(ID, scTruncate, op, ty) {
359   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
360          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
361          "Cannot truncate non-integer value!");
362 }
363 
364 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
365                                        const SCEV *op, Type *ty)
366   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
367   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
368          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
369          "Cannot zero extend non-integer value!");
370 }
371 
372 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
373                                        const SCEV *op, Type *ty)
374   : SCEVCastExpr(ID, scSignExtend, op, ty) {
375   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
376          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
377          "Cannot sign extend non-integer value!");
378 }
379 
380 void SCEVUnknown::deleted() {
381   // Clear this SCEVUnknown from various maps.
382   SE->forgetMemoizedResults(this);
383 
384   // Remove this SCEVUnknown from the uniquing map.
385   SE->UniqueSCEVs.RemoveNode(this);
386 
387   // Release the value.
388   setValPtr(nullptr);
389 }
390 
391 void SCEVUnknown::allUsesReplacedWith(Value *New) {
392   // Clear this SCEVUnknown from various maps.
393   SE->forgetMemoizedResults(this);
394 
395   // Remove this SCEVUnknown from the uniquing map.
396   SE->UniqueSCEVs.RemoveNode(this);
397 
398   // Update this SCEVUnknown to point to the new value. This is needed
399   // because there may still be outstanding SCEVs which still point to
400   // this SCEVUnknown.
401   setValPtr(New);
402 }
403 
404 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
405   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
406     if (VCE->getOpcode() == Instruction::PtrToInt)
407       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
408         if (CE->getOpcode() == Instruction::GetElementPtr &&
409             CE->getOperand(0)->isNullValue() &&
410             CE->getNumOperands() == 2)
411           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
412             if (CI->isOne()) {
413               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
414                                  ->getElementType();
415               return true;
416             }
417 
418   return false;
419 }
420 
421 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
422   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
423     if (VCE->getOpcode() == Instruction::PtrToInt)
424       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
425         if (CE->getOpcode() == Instruction::GetElementPtr &&
426             CE->getOperand(0)->isNullValue()) {
427           Type *Ty =
428             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
429           if (StructType *STy = dyn_cast<StructType>(Ty))
430             if (!STy->isPacked() &&
431                 CE->getNumOperands() == 3 &&
432                 CE->getOperand(1)->isNullValue()) {
433               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
434                 if (CI->isOne() &&
435                     STy->getNumElements() == 2 &&
436                     STy->getElementType(0)->isIntegerTy(1)) {
437                   AllocTy = STy->getElementType(1);
438                   return true;
439                 }
440             }
441         }
442 
443   return false;
444 }
445 
446 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
447   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
448     if (VCE->getOpcode() == Instruction::PtrToInt)
449       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
450         if (CE->getOpcode() == Instruction::GetElementPtr &&
451             CE->getNumOperands() == 3 &&
452             CE->getOperand(0)->isNullValue() &&
453             CE->getOperand(1)->isNullValue()) {
454           Type *Ty =
455             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
456           // Ignore vector types here so that ScalarEvolutionExpander doesn't
457           // emit getelementptrs that index into vectors.
458           if (Ty->isStructTy() || Ty->isArrayTy()) {
459             CTy = Ty;
460             FieldNo = CE->getOperand(2);
461             return true;
462           }
463         }
464 
465   return false;
466 }
467 
468 //===----------------------------------------------------------------------===//
469 //                               SCEV Utilities
470 //===----------------------------------------------------------------------===//
471 
472 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
473 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
474 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
475 /// have been previously deemed to be "equally complex" by this routine.  It is
476 /// intended to avoid exponential time complexity in cases like:
477 ///
478 ///   %a = f(%x, %y)
479 ///   %b = f(%a, %a)
480 ///   %c = f(%b, %b)
481 ///
482 ///   %d = f(%x, %y)
483 ///   %e = f(%d, %d)
484 ///   %f = f(%e, %e)
485 ///
486 ///   CompareValueComplexity(%f, %c)
487 ///
488 /// Since we do not continue running this routine on expression trees once we
489 /// have seen unequal values, there is no need to track them in the cache.
490 static int
491 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
492                        const LoopInfo *const LI, Value *LV, Value *RV,
493                        unsigned Depth) {
494   if (Depth > MaxCompareDepth || EqCache.count({LV, RV}))
495     return 0;
496 
497   // Order pointer values after integer values. This helps SCEVExpander form
498   // GEPs.
499   bool LIsPointer = LV->getType()->isPointerTy(),
500        RIsPointer = RV->getType()->isPointerTy();
501   if (LIsPointer != RIsPointer)
502     return (int)LIsPointer - (int)RIsPointer;
503 
504   // Compare getValueID values.
505   unsigned LID = LV->getValueID(), RID = RV->getValueID();
506   if (LID != RID)
507     return (int)LID - (int)RID;
508 
509   // Sort arguments by their position.
510   if (const auto *LA = dyn_cast<Argument>(LV)) {
511     const auto *RA = cast<Argument>(RV);
512     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513     return (int)LArgNo - (int)RArgNo;
514   }
515 
516   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
517     const auto *RGV = cast<GlobalValue>(RV);
518 
519     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
520       auto LT = GV->getLinkage();
521       return !(GlobalValue::isPrivateLinkage(LT) ||
522                GlobalValue::isInternalLinkage(LT));
523     };
524 
525     // Use the names to distinguish the two values, but only if the
526     // names are semantically important.
527     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
528       return LGV->getName().compare(RGV->getName());
529   }
530 
531   // For instructions, compare their loop depth, and their operand count.  This
532   // is pretty loose.
533   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
534     const auto *RInst = cast<Instruction>(RV);
535 
536     // Compare loop depths.
537     const BasicBlock *LParent = LInst->getParent(),
538                      *RParent = RInst->getParent();
539     if (LParent != RParent) {
540       unsigned LDepth = LI->getLoopDepth(LParent),
541                RDepth = LI->getLoopDepth(RParent);
542       if (LDepth != RDepth)
543         return (int)LDepth - (int)RDepth;
544     }
545 
546     // Compare the number of operands.
547     unsigned LNumOps = LInst->getNumOperands(),
548              RNumOps = RInst->getNumOperands();
549     if (LNumOps != RNumOps)
550       return (int)LNumOps - (int)RNumOps;
551 
552     for (unsigned Idx : seq(0u, LNumOps)) {
553       int Result =
554           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
555                                  RInst->getOperand(Idx), Depth + 1);
556       if (Result != 0)
557         return Result;
558     }
559   }
560 
561   EqCache.insert({LV, RV});
562   return 0;
563 }
564 
565 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
566 // than RHS, respectively. A three-way result allows recursive comparisons to be
567 // more efficient.
568 static int CompareSCEVComplexity(
569     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
570     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
571     unsigned Depth = 0) {
572   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
573   if (LHS == RHS)
574     return 0;
575 
576   // Primarily, sort the SCEVs by their getSCEVType().
577   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
578   if (LType != RType)
579     return (int)LType - (int)RType;
580 
581   if (Depth > MaxCompareDepth || EqCacheSCEV.count({LHS, RHS}))
582     return 0;
583   // Aside from the getSCEVType() ordering, the particular ordering
584   // isn't very important except that it's beneficial to be consistent,
585   // so that (a + b) and (b + a) don't end up as different expressions.
586   switch (static_cast<SCEVTypes>(LType)) {
587   case scUnknown: {
588     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
589     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
590 
591     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
592     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
593                                    Depth + 1);
594     if (X == 0)
595       EqCacheSCEV.insert({LHS, RHS});
596     return X;
597   }
598 
599   case scConstant: {
600     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
601     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
602 
603     // Compare constant values.
604     const APInt &LA = LC->getAPInt();
605     const APInt &RA = RC->getAPInt();
606     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
607     if (LBitWidth != RBitWidth)
608       return (int)LBitWidth - (int)RBitWidth;
609     return LA.ult(RA) ? -1 : 1;
610   }
611 
612   case scAddRecExpr: {
613     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
614     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
615 
616     // Compare addrec loop depths.
617     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
618     if (LLoop != RLoop) {
619       unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth();
620       if (LDepth != RDepth)
621         return (int)LDepth - (int)RDepth;
622     }
623 
624     // Addrec complexity grows with operand count.
625     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
626     if (LNumOps != RNumOps)
627       return (int)LNumOps - (int)RNumOps;
628 
629     // Lexicographically compare.
630     for (unsigned i = 0; i != LNumOps; ++i) {
631       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
632                                     RA->getOperand(i), Depth + 1);
633       if (X != 0)
634         return X;
635     }
636     EqCacheSCEV.insert({LHS, RHS});
637     return 0;
638   }
639 
640   case scAddExpr:
641   case scMulExpr:
642   case scSMaxExpr:
643   case scUMaxExpr: {
644     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
645     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
646 
647     // Lexicographically compare n-ary expressions.
648     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
649     if (LNumOps != RNumOps)
650       return (int)LNumOps - (int)RNumOps;
651 
652     for (unsigned i = 0; i != LNumOps; ++i) {
653       if (i >= RNumOps)
654         return 1;
655       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
656                                     RC->getOperand(i), Depth + 1);
657       if (X != 0)
658         return X;
659     }
660     EqCacheSCEV.insert({LHS, RHS});
661     return 0;
662   }
663 
664   case scUDivExpr: {
665     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
666     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
667 
668     // Lexicographically compare udiv expressions.
669     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
670                                   Depth + 1);
671     if (X != 0)
672       return X;
673     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(),
674                               Depth + 1);
675     if (X == 0)
676       EqCacheSCEV.insert({LHS, RHS});
677     return X;
678   }
679 
680   case scTruncate:
681   case scZeroExtend:
682   case scSignExtend: {
683     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
684     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
685 
686     // Compare cast expressions by operand.
687     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
688                                   RC->getOperand(), Depth + 1);
689     if (X == 0)
690       EqCacheSCEV.insert({LHS, RHS});
691     return X;
692   }
693 
694   case scCouldNotCompute:
695     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
696   }
697   llvm_unreachable("Unknown SCEV kind!");
698 }
699 
700 /// Given a list of SCEV objects, order them by their complexity, and group
701 /// objects of the same complexity together by value.  When this routine is
702 /// finished, we know that any duplicates in the vector are consecutive and that
703 /// complexity is monotonically increasing.
704 ///
705 /// Note that we go take special precautions to ensure that we get deterministic
706 /// results from this routine.  In other words, we don't want the results of
707 /// this to depend on where the addresses of various SCEV objects happened to
708 /// land in memory.
709 ///
710 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
711                               LoopInfo *LI) {
712   if (Ops.size() < 2) return;  // Noop
713 
714   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
715   if (Ops.size() == 2) {
716     // This is the common case, which also happens to be trivially simple.
717     // Special case it.
718     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
719     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS) < 0)
720       std::swap(LHS, RHS);
721     return;
722   }
723 
724   // Do the rough sort by complexity.
725   std::stable_sort(Ops.begin(), Ops.end(),
726                    [&EqCache, LI](const SCEV *LHS, const SCEV *RHS) {
727                      return CompareSCEVComplexity(EqCache, LI, LHS, RHS) < 0;
728                    });
729 
730   // Now that we are sorted by complexity, group elements of the same
731   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
732   // be extremely short in practice.  Note that we take this approach because we
733   // do not want to depend on the addresses of the objects we are grouping.
734   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
735     const SCEV *S = Ops[i];
736     unsigned Complexity = S->getSCEVType();
737 
738     // If there are any objects of the same complexity and same value as this
739     // one, group them.
740     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
741       if (Ops[j] == S) { // Found a duplicate.
742         // Move it to immediately after i'th element.
743         std::swap(Ops[i+1], Ops[j]);
744         ++i;   // no need to rescan it.
745         if (i == e-2) return;  // Done!
746       }
747     }
748   }
749 }
750 
751 // Returns the size of the SCEV S.
752 static inline int sizeOfSCEV(const SCEV *S) {
753   struct FindSCEVSize {
754     int Size;
755     FindSCEVSize() : Size(0) {}
756 
757     bool follow(const SCEV *S) {
758       ++Size;
759       // Keep looking at all operands of S.
760       return true;
761     }
762     bool isDone() const {
763       return false;
764     }
765   };
766 
767   FindSCEVSize F;
768   SCEVTraversal<FindSCEVSize> ST(F);
769   ST.visitAll(S);
770   return F.Size;
771 }
772 
773 namespace {
774 
775 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
776 public:
777   // Computes the Quotient and Remainder of the division of Numerator by
778   // Denominator.
779   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
780                      const SCEV *Denominator, const SCEV **Quotient,
781                      const SCEV **Remainder) {
782     assert(Numerator && Denominator && "Uninitialized SCEV");
783 
784     SCEVDivision D(SE, Numerator, Denominator);
785 
786     // Check for the trivial case here to avoid having to check for it in the
787     // rest of the code.
788     if (Numerator == Denominator) {
789       *Quotient = D.One;
790       *Remainder = D.Zero;
791       return;
792     }
793 
794     if (Numerator->isZero()) {
795       *Quotient = D.Zero;
796       *Remainder = D.Zero;
797       return;
798     }
799 
800     // A simple case when N/1. The quotient is N.
801     if (Denominator->isOne()) {
802       *Quotient = Numerator;
803       *Remainder = D.Zero;
804       return;
805     }
806 
807     // Split the Denominator when it is a product.
808     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
809       const SCEV *Q, *R;
810       *Quotient = Numerator;
811       for (const SCEV *Op : T->operands()) {
812         divide(SE, *Quotient, Op, &Q, &R);
813         *Quotient = Q;
814 
815         // Bail out when the Numerator is not divisible by one of the terms of
816         // the Denominator.
817         if (!R->isZero()) {
818           *Quotient = D.Zero;
819           *Remainder = Numerator;
820           return;
821         }
822       }
823       *Remainder = D.Zero;
824       return;
825     }
826 
827     D.visit(Numerator);
828     *Quotient = D.Quotient;
829     *Remainder = D.Remainder;
830   }
831 
832   // Except in the trivial case described above, we do not know how to divide
833   // Expr by Denominator for the following functions with empty implementation.
834   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
835   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
836   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
837   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
838   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
839   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
840   void visitUnknown(const SCEVUnknown *Numerator) {}
841   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
842 
843   void visitConstant(const SCEVConstant *Numerator) {
844     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
845       APInt NumeratorVal = Numerator->getAPInt();
846       APInt DenominatorVal = D->getAPInt();
847       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
848       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
849 
850       if (NumeratorBW > DenominatorBW)
851         DenominatorVal = DenominatorVal.sext(NumeratorBW);
852       else if (NumeratorBW < DenominatorBW)
853         NumeratorVal = NumeratorVal.sext(DenominatorBW);
854 
855       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
856       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
857       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
858       Quotient = SE.getConstant(QuotientVal);
859       Remainder = SE.getConstant(RemainderVal);
860       return;
861     }
862   }
863 
864   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
865     const SCEV *StartQ, *StartR, *StepQ, *StepR;
866     if (!Numerator->isAffine())
867       return cannotDivide(Numerator);
868     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
869     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
870     // Bail out if the types do not match.
871     Type *Ty = Denominator->getType();
872     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
873         Ty != StepQ->getType() || Ty != StepR->getType())
874       return cannotDivide(Numerator);
875     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
876                                 Numerator->getNoWrapFlags());
877     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
878                                  Numerator->getNoWrapFlags());
879   }
880 
881   void visitAddExpr(const SCEVAddExpr *Numerator) {
882     SmallVector<const SCEV *, 2> Qs, Rs;
883     Type *Ty = Denominator->getType();
884 
885     for (const SCEV *Op : Numerator->operands()) {
886       const SCEV *Q, *R;
887       divide(SE, Op, Denominator, &Q, &R);
888 
889       // Bail out if types do not match.
890       if (Ty != Q->getType() || Ty != R->getType())
891         return cannotDivide(Numerator);
892 
893       Qs.push_back(Q);
894       Rs.push_back(R);
895     }
896 
897     if (Qs.size() == 1) {
898       Quotient = Qs[0];
899       Remainder = Rs[0];
900       return;
901     }
902 
903     Quotient = SE.getAddExpr(Qs);
904     Remainder = SE.getAddExpr(Rs);
905   }
906 
907   void visitMulExpr(const SCEVMulExpr *Numerator) {
908     SmallVector<const SCEV *, 2> Qs;
909     Type *Ty = Denominator->getType();
910 
911     bool FoundDenominatorTerm = false;
912     for (const SCEV *Op : Numerator->operands()) {
913       // Bail out if types do not match.
914       if (Ty != Op->getType())
915         return cannotDivide(Numerator);
916 
917       if (FoundDenominatorTerm) {
918         Qs.push_back(Op);
919         continue;
920       }
921 
922       // Check whether Denominator divides one of the product operands.
923       const SCEV *Q, *R;
924       divide(SE, Op, Denominator, &Q, &R);
925       if (!R->isZero()) {
926         Qs.push_back(Op);
927         continue;
928       }
929 
930       // Bail out if types do not match.
931       if (Ty != Q->getType())
932         return cannotDivide(Numerator);
933 
934       FoundDenominatorTerm = true;
935       Qs.push_back(Q);
936     }
937 
938     if (FoundDenominatorTerm) {
939       Remainder = Zero;
940       if (Qs.size() == 1)
941         Quotient = Qs[0];
942       else
943         Quotient = SE.getMulExpr(Qs);
944       return;
945     }
946 
947     if (!isa<SCEVUnknown>(Denominator))
948       return cannotDivide(Numerator);
949 
950     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
951     ValueToValueMap RewriteMap;
952     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
953         cast<SCEVConstant>(Zero)->getValue();
954     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
955 
956     if (Remainder->isZero()) {
957       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
958       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
959           cast<SCEVConstant>(One)->getValue();
960       Quotient =
961           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
962       return;
963     }
964 
965     // Quotient is (Numerator - Remainder) divided by Denominator.
966     const SCEV *Q, *R;
967     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
968     // This SCEV does not seem to simplify: fail the division here.
969     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
970       return cannotDivide(Numerator);
971     divide(SE, Diff, Denominator, &Q, &R);
972     if (R != Zero)
973       return cannotDivide(Numerator);
974     Quotient = Q;
975   }
976 
977 private:
978   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
979                const SCEV *Denominator)
980       : SE(S), Denominator(Denominator) {
981     Zero = SE.getZero(Denominator->getType());
982     One = SE.getOne(Denominator->getType());
983 
984     // We generally do not know how to divide Expr by Denominator. We
985     // initialize the division to a "cannot divide" state to simplify the rest
986     // of the code.
987     cannotDivide(Numerator);
988   }
989 
990   // Convenience function for giving up on the division. We set the quotient to
991   // be equal to zero and the remainder to be equal to the numerator.
992   void cannotDivide(const SCEV *Numerator) {
993     Quotient = Zero;
994     Remainder = Numerator;
995   }
996 
997   ScalarEvolution &SE;
998   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
999 };
1000 
1001 }
1002 
1003 //===----------------------------------------------------------------------===//
1004 //                      Simple SCEV method implementations
1005 //===----------------------------------------------------------------------===//
1006 
1007 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1008 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1009                                        ScalarEvolution &SE,
1010                                        Type *ResultTy) {
1011   // Handle the simplest case efficiently.
1012   if (K == 1)
1013     return SE.getTruncateOrZeroExtend(It, ResultTy);
1014 
1015   // We are using the following formula for BC(It, K):
1016   //
1017   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1018   //
1019   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1020   // overflow.  Hence, we must assure that the result of our computation is
1021   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1022   // safe in modular arithmetic.
1023   //
1024   // However, this code doesn't use exactly that formula; the formula it uses
1025   // is something like the following, where T is the number of factors of 2 in
1026   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1027   // exponentiation:
1028   //
1029   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1030   //
1031   // This formula is trivially equivalent to the previous formula.  However,
1032   // this formula can be implemented much more efficiently.  The trick is that
1033   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1034   // arithmetic.  To do exact division in modular arithmetic, all we have
1035   // to do is multiply by the inverse.  Therefore, this step can be done at
1036   // width W.
1037   //
1038   // The next issue is how to safely do the division by 2^T.  The way this
1039   // is done is by doing the multiplication step at a width of at least W + T
1040   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1041   // when we perform the division by 2^T (which is equivalent to a right shift
1042   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1043   // truncated out after the division by 2^T.
1044   //
1045   // In comparison to just directly using the first formula, this technique
1046   // is much more efficient; using the first formula requires W * K bits,
1047   // but this formula less than W + K bits. Also, the first formula requires
1048   // a division step, whereas this formula only requires multiplies and shifts.
1049   //
1050   // It doesn't matter whether the subtraction step is done in the calculation
1051   // width or the input iteration count's width; if the subtraction overflows,
1052   // the result must be zero anyway.  We prefer here to do it in the width of
1053   // the induction variable because it helps a lot for certain cases; CodeGen
1054   // isn't smart enough to ignore the overflow, which leads to much less
1055   // efficient code if the width of the subtraction is wider than the native
1056   // register width.
1057   //
1058   // (It's possible to not widen at all by pulling out factors of 2 before
1059   // the multiplication; for example, K=2 can be calculated as
1060   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1061   // extra arithmetic, so it's not an obvious win, and it gets
1062   // much more complicated for K > 3.)
1063 
1064   // Protection from insane SCEVs; this bound is conservative,
1065   // but it probably doesn't matter.
1066   if (K > 1000)
1067     return SE.getCouldNotCompute();
1068 
1069   unsigned W = SE.getTypeSizeInBits(ResultTy);
1070 
1071   // Calculate K! / 2^T and T; we divide out the factors of two before
1072   // multiplying for calculating K! / 2^T to avoid overflow.
1073   // Other overflow doesn't matter because we only care about the bottom
1074   // W bits of the result.
1075   APInt OddFactorial(W, 1);
1076   unsigned T = 1;
1077   for (unsigned i = 3; i <= K; ++i) {
1078     APInt Mult(W, i);
1079     unsigned TwoFactors = Mult.countTrailingZeros();
1080     T += TwoFactors;
1081     Mult = Mult.lshr(TwoFactors);
1082     OddFactorial *= Mult;
1083   }
1084 
1085   // We need at least W + T bits for the multiplication step
1086   unsigned CalculationBits = W + T;
1087 
1088   // Calculate 2^T, at width T+W.
1089   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1090 
1091   // Calculate the multiplicative inverse of K! / 2^T;
1092   // this multiplication factor will perform the exact division by
1093   // K! / 2^T.
1094   APInt Mod = APInt::getSignedMinValue(W+1);
1095   APInt MultiplyFactor = OddFactorial.zext(W+1);
1096   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1097   MultiplyFactor = MultiplyFactor.trunc(W);
1098 
1099   // Calculate the product, at width T+W
1100   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1101                                                       CalculationBits);
1102   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1103   for (unsigned i = 1; i != K; ++i) {
1104     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1105     Dividend = SE.getMulExpr(Dividend,
1106                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1107   }
1108 
1109   // Divide by 2^T
1110   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1111 
1112   // Truncate the result, and divide by K! / 2^T.
1113 
1114   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1115                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1116 }
1117 
1118 /// Return the value of this chain of recurrences at the specified iteration
1119 /// number.  We can evaluate this recurrence by multiplying each element in the
1120 /// chain by the binomial coefficient corresponding to it.  In other words, we
1121 /// can evaluate {A,+,B,+,C,+,D} as:
1122 ///
1123 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1124 ///
1125 /// where BC(It, k) stands for binomial coefficient.
1126 ///
1127 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1128                                                 ScalarEvolution &SE) const {
1129   const SCEV *Result = getStart();
1130   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1131     // The computation is correct in the face of overflow provided that the
1132     // multiplication is performed _after_ the evaluation of the binomial
1133     // coefficient.
1134     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1135     if (isa<SCEVCouldNotCompute>(Coeff))
1136       return Coeff;
1137 
1138     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1139   }
1140   return Result;
1141 }
1142 
1143 //===----------------------------------------------------------------------===//
1144 //                    SCEV Expression folder implementations
1145 //===----------------------------------------------------------------------===//
1146 
1147 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1148                                              Type *Ty) {
1149   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1150          "This is not a truncating conversion!");
1151   assert(isSCEVable(Ty) &&
1152          "This is not a conversion to a SCEVable type!");
1153   Ty = getEffectiveSCEVType(Ty);
1154 
1155   FoldingSetNodeID ID;
1156   ID.AddInteger(scTruncate);
1157   ID.AddPointer(Op);
1158   ID.AddPointer(Ty);
1159   void *IP = nullptr;
1160   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1161 
1162   // Fold if the operand is constant.
1163   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1164     return getConstant(
1165       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1166 
1167   // trunc(trunc(x)) --> trunc(x)
1168   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1169     return getTruncateExpr(ST->getOperand(), Ty);
1170 
1171   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1172   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1173     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1174 
1175   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1176   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1177     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1178 
1179   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1180   // eliminate all the truncates, or we replace other casts with truncates.
1181   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1182     SmallVector<const SCEV *, 4> Operands;
1183     bool hasTrunc = false;
1184     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1185       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1186       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1187         hasTrunc = isa<SCEVTruncateExpr>(S);
1188       Operands.push_back(S);
1189     }
1190     if (!hasTrunc)
1191       return getAddExpr(Operands);
1192     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1193   }
1194 
1195   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1196   // eliminate all the truncates, or we replace other casts with truncates.
1197   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1198     SmallVector<const SCEV *, 4> Operands;
1199     bool hasTrunc = false;
1200     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1201       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1202       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1203         hasTrunc = isa<SCEVTruncateExpr>(S);
1204       Operands.push_back(S);
1205     }
1206     if (!hasTrunc)
1207       return getMulExpr(Operands);
1208     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1209   }
1210 
1211   // If the input value is a chrec scev, truncate the chrec's operands.
1212   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1213     SmallVector<const SCEV *, 4> Operands;
1214     for (const SCEV *Op : AddRec->operands())
1215       Operands.push_back(getTruncateExpr(Op, Ty));
1216     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1217   }
1218 
1219   // The cast wasn't folded; create an explicit cast node. We can reuse
1220   // the existing insert position since if we get here, we won't have
1221   // made any changes which would invalidate it.
1222   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1223                                                  Op, Ty);
1224   UniqueSCEVs.InsertNode(S, IP);
1225   return S;
1226 }
1227 
1228 // Get the limit of a recurrence such that incrementing by Step cannot cause
1229 // signed overflow as long as the value of the recurrence within the
1230 // loop does not exceed this limit before incrementing.
1231 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1232                                                  ICmpInst::Predicate *Pred,
1233                                                  ScalarEvolution *SE) {
1234   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1235   if (SE->isKnownPositive(Step)) {
1236     *Pred = ICmpInst::ICMP_SLT;
1237     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1238                            SE->getSignedRange(Step).getSignedMax());
1239   }
1240   if (SE->isKnownNegative(Step)) {
1241     *Pred = ICmpInst::ICMP_SGT;
1242     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1243                            SE->getSignedRange(Step).getSignedMin());
1244   }
1245   return nullptr;
1246 }
1247 
1248 // Get the limit of a recurrence such that incrementing by Step cannot cause
1249 // unsigned overflow as long as the value of the recurrence within the loop does
1250 // not exceed this limit before incrementing.
1251 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1252                                                    ICmpInst::Predicate *Pred,
1253                                                    ScalarEvolution *SE) {
1254   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1255   *Pred = ICmpInst::ICMP_ULT;
1256 
1257   return SE->getConstant(APInt::getMinValue(BitWidth) -
1258                          SE->getUnsignedRange(Step).getUnsignedMax());
1259 }
1260 
1261 namespace {
1262 
1263 struct ExtendOpTraitsBase {
1264   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1265 };
1266 
1267 // Used to make code generic over signed and unsigned overflow.
1268 template <typename ExtendOp> struct ExtendOpTraits {
1269   // Members present:
1270   //
1271   // static const SCEV::NoWrapFlags WrapType;
1272   //
1273   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1274   //
1275   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1276   //                                           ICmpInst::Predicate *Pred,
1277   //                                           ScalarEvolution *SE);
1278 };
1279 
1280 template <>
1281 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1282   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1283 
1284   static const GetExtendExprTy GetExtendExpr;
1285 
1286   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287                                              ICmpInst::Predicate *Pred,
1288                                              ScalarEvolution *SE) {
1289     return getSignedOverflowLimitForStep(Step, Pred, SE);
1290   }
1291 };
1292 
1293 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1294     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1295 
1296 template <>
1297 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1298   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1299 
1300   static const GetExtendExprTy GetExtendExpr;
1301 
1302   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303                                              ICmpInst::Predicate *Pred,
1304                                              ScalarEvolution *SE) {
1305     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1306   }
1307 };
1308 
1309 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1310     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1311 }
1312 
1313 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1314 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1315 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1316 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1317 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1318 // expression "Step + sext/zext(PreIncAR)" is congruent with
1319 // "sext/zext(PostIncAR)"
1320 template <typename ExtendOpTy>
1321 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1322                                         ScalarEvolution *SE) {
1323   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1324   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1325 
1326   const Loop *L = AR->getLoop();
1327   const SCEV *Start = AR->getStart();
1328   const SCEV *Step = AR->getStepRecurrence(*SE);
1329 
1330   // Check for a simple looking step prior to loop entry.
1331   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1332   if (!SA)
1333     return nullptr;
1334 
1335   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1336   // subtraction is expensive. For this purpose, perform a quick and dirty
1337   // difference, by checking for Step in the operand list.
1338   SmallVector<const SCEV *, 4> DiffOps;
1339   for (const SCEV *Op : SA->operands())
1340     if (Op != Step)
1341       DiffOps.push_back(Op);
1342 
1343   if (DiffOps.size() == SA->getNumOperands())
1344     return nullptr;
1345 
1346   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1347   // `Step`:
1348 
1349   // 1. NSW/NUW flags on the step increment.
1350   auto PreStartFlags =
1351     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1352   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1353   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1354       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1355 
1356   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1357   // "S+X does not sign/unsign-overflow".
1358   //
1359 
1360   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1361   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1362       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1363     return PreStart;
1364 
1365   // 2. Direct overflow check on the step operation's expression.
1366   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1367   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1368   const SCEV *OperandExtendedStart =
1369       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1370                      (SE->*GetExtendExpr)(Step, WideTy));
1371   if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1372     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1373       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1374       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1375       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1376       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1377     }
1378     return PreStart;
1379   }
1380 
1381   // 3. Loop precondition.
1382   ICmpInst::Predicate Pred;
1383   const SCEV *OverflowLimit =
1384       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1385 
1386   if (OverflowLimit &&
1387       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1388     return PreStart;
1389 
1390   return nullptr;
1391 }
1392 
1393 // Get the normalized zero or sign extended expression for this AddRec's Start.
1394 template <typename ExtendOpTy>
1395 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1396                                         ScalarEvolution *SE) {
1397   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1398 
1399   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1400   if (!PreStart)
1401     return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1402 
1403   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1404                         (SE->*GetExtendExpr)(PreStart, Ty));
1405 }
1406 
1407 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1408 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1409 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1410 //
1411 // Formally:
1412 //
1413 //     {S,+,X} == {S-T,+,X} + T
1414 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1415 //
1416 // If ({S-T,+,X} + T) does not overflow  ... (1)
1417 //
1418 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1419 //
1420 // If {S-T,+,X} does not overflow  ... (2)
1421 //
1422 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1423 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1424 //
1425 // If (S-T)+T does not overflow  ... (3)
1426 //
1427 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1428 //      == {Ext(S),+,Ext(X)} == LHS
1429 //
1430 // Thus, if (1), (2) and (3) are true for some T, then
1431 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1432 //
1433 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1434 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1435 // to check for (1) and (2).
1436 //
1437 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1438 // is `Delta` (defined below).
1439 //
1440 template <typename ExtendOpTy>
1441 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1442                                                 const SCEV *Step,
1443                                                 const Loop *L) {
1444   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1445 
1446   // We restrict `Start` to a constant to prevent SCEV from spending too much
1447   // time here.  It is correct (but more expensive) to continue with a
1448   // non-constant `Start` and do a general SCEV subtraction to compute
1449   // `PreStart` below.
1450   //
1451   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1452   if (!StartC)
1453     return false;
1454 
1455   APInt StartAI = StartC->getAPInt();
1456 
1457   for (unsigned Delta : {-2, -1, 1, 2}) {
1458     const SCEV *PreStart = getConstant(StartAI - Delta);
1459 
1460     FoldingSetNodeID ID;
1461     ID.AddInteger(scAddRecExpr);
1462     ID.AddPointer(PreStart);
1463     ID.AddPointer(Step);
1464     ID.AddPointer(L);
1465     void *IP = nullptr;
1466     const auto *PreAR =
1467       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1468 
1469     // Give up if we don't already have the add recurrence we need because
1470     // actually constructing an add recurrence is relatively expensive.
1471     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1472       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1473       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1474       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1475           DeltaS, &Pred, this);
1476       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1477         return true;
1478     }
1479   }
1480 
1481   return false;
1482 }
1483 
1484 const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
1485                                                Type *Ty) {
1486   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1487          "This is not an extending conversion!");
1488   assert(isSCEVable(Ty) &&
1489          "This is not a conversion to a SCEVable type!");
1490   Ty = getEffectiveSCEVType(Ty);
1491 
1492   // Fold if the operand is constant.
1493   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1494     return getConstant(
1495       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1496 
1497   // zext(zext(x)) --> zext(x)
1498   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1499     return getZeroExtendExpr(SZ->getOperand(), Ty);
1500 
1501   // Before doing any expensive analysis, check to see if we've already
1502   // computed a SCEV for this Op and Ty.
1503   FoldingSetNodeID ID;
1504   ID.AddInteger(scZeroExtend);
1505   ID.AddPointer(Op);
1506   ID.AddPointer(Ty);
1507   void *IP = nullptr;
1508   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1509 
1510   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1511   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1512     // It's possible the bits taken off by the truncate were all zero bits. If
1513     // so, we should be able to simplify this further.
1514     const SCEV *X = ST->getOperand();
1515     ConstantRange CR = getUnsignedRange(X);
1516     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1517     unsigned NewBits = getTypeSizeInBits(Ty);
1518     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1519             CR.zextOrTrunc(NewBits)))
1520       return getTruncateOrZeroExtend(X, Ty);
1521   }
1522 
1523   // If the input value is a chrec scev, and we can prove that the value
1524   // did not overflow the old, smaller, value, we can zero extend all of the
1525   // operands (often constants).  This allows analysis of something like
1526   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1527   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1528     if (AR->isAffine()) {
1529       const SCEV *Start = AR->getStart();
1530       const SCEV *Step = AR->getStepRecurrence(*this);
1531       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1532       const Loop *L = AR->getLoop();
1533 
1534       if (!AR->hasNoUnsignedWrap()) {
1535         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1536         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1537       }
1538 
1539       // If we have special knowledge that this addrec won't overflow,
1540       // we don't need to do any further analysis.
1541       if (AR->hasNoUnsignedWrap())
1542         return getAddRecExpr(
1543             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1544             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1545 
1546       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1547       // Note that this serves two purposes: It filters out loops that are
1548       // simply not analyzable, and it covers the case where this code is
1549       // being called from within backedge-taken count analysis, such that
1550       // attempting to ask for the backedge-taken count would likely result
1551       // in infinite recursion. In the later case, the analysis code will
1552       // cope with a conservative value, and it will take care to purge
1553       // that value once it has finished.
1554       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1555       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1556         // Manually compute the final value for AR, checking for
1557         // overflow.
1558 
1559         // Check whether the backedge-taken count can be losslessly casted to
1560         // the addrec's type. The count is always unsigned.
1561         const SCEV *CastedMaxBECount =
1562           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1563         const SCEV *RecastedMaxBECount =
1564           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1565         if (MaxBECount == RecastedMaxBECount) {
1566           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1567           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1568           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
1569           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1570           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1571           const SCEV *WideMaxBECount =
1572             getZeroExtendExpr(CastedMaxBECount, WideTy);
1573           const SCEV *OperandExtendedAdd =
1574             getAddExpr(WideStart,
1575                        getMulExpr(WideMaxBECount,
1576                                   getZeroExtendExpr(Step, WideTy)));
1577           if (ZAdd == OperandExtendedAdd) {
1578             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1579             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1580             // Return the expression with the addrec on the outside.
1581             return getAddRecExpr(
1582                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1583                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1584           }
1585           // Similar to above, only this time treat the step value as signed.
1586           // This covers loops that count down.
1587           OperandExtendedAdd =
1588             getAddExpr(WideStart,
1589                        getMulExpr(WideMaxBECount,
1590                                   getSignExtendExpr(Step, WideTy)));
1591           if (ZAdd == OperandExtendedAdd) {
1592             // Cache knowledge of AR NW, which is propagated to this AddRec.
1593             // Negative step causes unsigned wrap, but it still can't self-wrap.
1594             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1595             // Return the expression with the addrec on the outside.
1596             return getAddRecExpr(
1597                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1598                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1599           }
1600         }
1601       }
1602 
1603       // Normally, in the cases we can prove no-overflow via a
1604       // backedge guarding condition, we can also compute a backedge
1605       // taken count for the loop.  The exceptions are assumptions and
1606       // guards present in the loop -- SCEV is not great at exploiting
1607       // these to compute max backedge taken counts, but can still use
1608       // these to prove lack of overflow.  Use this fact to avoid
1609       // doing extra work that may not pay off.
1610       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1611           !AC.assumptions().empty()) {
1612         // If the backedge is guarded by a comparison with the pre-inc
1613         // value the addrec is safe. Also, if the entry is guarded by
1614         // a comparison with the start value and the backedge is
1615         // guarded by a comparison with the post-inc value, the addrec
1616         // is safe.
1617         if (isKnownPositive(Step)) {
1618           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1619                                       getUnsignedRange(Step).getUnsignedMax());
1620           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1621               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1622                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1623                                            AR->getPostIncExpr(*this), N))) {
1624             // Cache knowledge of AR NUW, which is propagated to this
1625             // AddRec.
1626             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1627             // Return the expression with the addrec on the outside.
1628             return getAddRecExpr(
1629                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1630                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1631           }
1632         } else if (isKnownNegative(Step)) {
1633           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1634                                       getSignedRange(Step).getSignedMin());
1635           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1636               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1637                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1638                                            AR->getPostIncExpr(*this), N))) {
1639             // Cache knowledge of AR NW, which is propagated to this
1640             // AddRec.  Negative step causes unsigned wrap, but it
1641             // still can't self-wrap.
1642             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1643             // Return the expression with the addrec on the outside.
1644             return getAddRecExpr(
1645                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1646                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1647           }
1648         }
1649       }
1650 
1651       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1652         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1653         return getAddRecExpr(
1654             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1655             getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1656       }
1657     }
1658 
1659   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1660     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1661     if (SA->hasNoUnsignedWrap()) {
1662       // If the addition does not unsign overflow then we can, by definition,
1663       // commute the zero extension with the addition operation.
1664       SmallVector<const SCEV *, 4> Ops;
1665       for (const auto *Op : SA->operands())
1666         Ops.push_back(getZeroExtendExpr(Op, Ty));
1667       return getAddExpr(Ops, SCEV::FlagNUW);
1668     }
1669   }
1670 
1671   // The cast wasn't folded; create an explicit cast node.
1672   // Recompute the insert position, as it may have been invalidated.
1673   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1674   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1675                                                    Op, Ty);
1676   UniqueSCEVs.InsertNode(S, IP);
1677   return S;
1678 }
1679 
1680 const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
1681                                                Type *Ty) {
1682   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1683          "This is not an extending conversion!");
1684   assert(isSCEVable(Ty) &&
1685          "This is not a conversion to a SCEVable type!");
1686   Ty = getEffectiveSCEVType(Ty);
1687 
1688   // Fold if the operand is constant.
1689   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1690     return getConstant(
1691       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1692 
1693   // sext(sext(x)) --> sext(x)
1694   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1695     return getSignExtendExpr(SS->getOperand(), Ty);
1696 
1697   // sext(zext(x)) --> zext(x)
1698   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1699     return getZeroExtendExpr(SZ->getOperand(), Ty);
1700 
1701   // Before doing any expensive analysis, check to see if we've already
1702   // computed a SCEV for this Op and Ty.
1703   FoldingSetNodeID ID;
1704   ID.AddInteger(scSignExtend);
1705   ID.AddPointer(Op);
1706   ID.AddPointer(Ty);
1707   void *IP = nullptr;
1708   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1709 
1710   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1711   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1712     // It's possible the bits taken off by the truncate were all sign bits. If
1713     // so, we should be able to simplify this further.
1714     const SCEV *X = ST->getOperand();
1715     ConstantRange CR = getSignedRange(X);
1716     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1717     unsigned NewBits = getTypeSizeInBits(Ty);
1718     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1719             CR.sextOrTrunc(NewBits)))
1720       return getTruncateOrSignExtend(X, Ty);
1721   }
1722 
1723   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1724   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1725     if (SA->getNumOperands() == 2) {
1726       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1727       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1728       if (SMul && SC1) {
1729         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1730           const APInt &C1 = SC1->getAPInt();
1731           const APInt &C2 = SC2->getAPInt();
1732           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1733               C2.ugt(C1) && C2.isPowerOf2())
1734             return getAddExpr(getSignExtendExpr(SC1, Ty),
1735                               getSignExtendExpr(SMul, Ty));
1736         }
1737       }
1738     }
1739 
1740     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1741     if (SA->hasNoSignedWrap()) {
1742       // If the addition does not sign overflow then we can, by definition,
1743       // commute the sign extension with the addition operation.
1744       SmallVector<const SCEV *, 4> Ops;
1745       for (const auto *Op : SA->operands())
1746         Ops.push_back(getSignExtendExpr(Op, Ty));
1747       return getAddExpr(Ops, SCEV::FlagNSW);
1748     }
1749   }
1750   // If the input value is a chrec scev, and we can prove that the value
1751   // did not overflow the old, smaller, value, we can sign extend all of the
1752   // operands (often constants).  This allows analysis of something like
1753   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1754   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1755     if (AR->isAffine()) {
1756       const SCEV *Start = AR->getStart();
1757       const SCEV *Step = AR->getStepRecurrence(*this);
1758       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1759       const Loop *L = AR->getLoop();
1760 
1761       if (!AR->hasNoSignedWrap()) {
1762         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1763         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1764       }
1765 
1766       // If we have special knowledge that this addrec won't overflow,
1767       // we don't need to do any further analysis.
1768       if (AR->hasNoSignedWrap())
1769         return getAddRecExpr(
1770             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1771             getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
1772 
1773       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1774       // Note that this serves two purposes: It filters out loops that are
1775       // simply not analyzable, and it covers the case where this code is
1776       // being called from within backedge-taken count analysis, such that
1777       // attempting to ask for the backedge-taken count would likely result
1778       // in infinite recursion. In the later case, the analysis code will
1779       // cope with a conservative value, and it will take care to purge
1780       // that value once it has finished.
1781       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1782       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1783         // Manually compute the final value for AR, checking for
1784         // overflow.
1785 
1786         // Check whether the backedge-taken count can be losslessly casted to
1787         // the addrec's type. The count is always unsigned.
1788         const SCEV *CastedMaxBECount =
1789           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1790         const SCEV *RecastedMaxBECount =
1791           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1792         if (MaxBECount == RecastedMaxBECount) {
1793           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1794           // Check whether Start+Step*MaxBECount has no signed overflow.
1795           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
1796           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1797           const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1798           const SCEV *WideMaxBECount =
1799             getZeroExtendExpr(CastedMaxBECount, WideTy);
1800           const SCEV *OperandExtendedAdd =
1801             getAddExpr(WideStart,
1802                        getMulExpr(WideMaxBECount,
1803                                   getSignExtendExpr(Step, WideTy)));
1804           if (SAdd == OperandExtendedAdd) {
1805             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1806             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1807             // Return the expression with the addrec on the outside.
1808             return getAddRecExpr(
1809                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1810                 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1811           }
1812           // Similar to above, only this time treat the step value as unsigned.
1813           // This covers loops that count up with an unsigned step.
1814           OperandExtendedAdd =
1815             getAddExpr(WideStart,
1816                        getMulExpr(WideMaxBECount,
1817                                   getZeroExtendExpr(Step, WideTy)));
1818           if (SAdd == OperandExtendedAdd) {
1819             // If AR wraps around then
1820             //
1821             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1822             // => SAdd != OperandExtendedAdd
1823             //
1824             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1825             // (SAdd == OperandExtendedAdd => AR is NW)
1826 
1827             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1828 
1829             // Return the expression with the addrec on the outside.
1830             return getAddRecExpr(
1831                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1832                 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1833           }
1834         }
1835       }
1836 
1837       // Normally, in the cases we can prove no-overflow via a
1838       // backedge guarding condition, we can also compute a backedge
1839       // taken count for the loop.  The exceptions are assumptions and
1840       // guards present in the loop -- SCEV is not great at exploiting
1841       // these to compute max backedge taken counts, but can still use
1842       // these to prove lack of overflow.  Use this fact to avoid
1843       // doing extra work that may not pay off.
1844 
1845       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1846           !AC.assumptions().empty()) {
1847         // If the backedge is guarded by a comparison with the pre-inc
1848         // value the addrec is safe. Also, if the entry is guarded by
1849         // a comparison with the start value and the backedge is
1850         // guarded by a comparison with the post-inc value, the addrec
1851         // is safe.
1852         ICmpInst::Predicate Pred;
1853         const SCEV *OverflowLimit =
1854             getSignedOverflowLimitForStep(Step, &Pred, this);
1855         if (OverflowLimit &&
1856             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1857              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1858               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1859                                           OverflowLimit)))) {
1860           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1861           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1862           return getAddRecExpr(
1863               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1864               getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1865         }
1866       }
1867 
1868       // If Start and Step are constants, check if we can apply this
1869       // transformation:
1870       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1871       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1872       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1873       if (SC1 && SC2) {
1874         const APInt &C1 = SC1->getAPInt();
1875         const APInt &C2 = SC2->getAPInt();
1876         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1877             C2.isPowerOf2()) {
1878           Start = getSignExtendExpr(Start, Ty);
1879           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1880                                             AR->getNoWrapFlags());
1881           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1882         }
1883       }
1884 
1885       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1886         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1887         return getAddRecExpr(
1888             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1889             getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1890       }
1891     }
1892 
1893   // If the input value is provably positive and we could not simplify
1894   // away the sext build a zext instead.
1895   if (isKnownNonNegative(Op))
1896     return getZeroExtendExpr(Op, Ty);
1897 
1898   // The cast wasn't folded; create an explicit cast node.
1899   // Recompute the insert position, as it may have been invalidated.
1900   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1901   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1902                                                    Op, Ty);
1903   UniqueSCEVs.InsertNode(S, IP);
1904   return S;
1905 }
1906 
1907 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1908 /// unspecified bits out to the given type.
1909 ///
1910 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1911                                               Type *Ty) {
1912   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1913          "This is not an extending conversion!");
1914   assert(isSCEVable(Ty) &&
1915          "This is not a conversion to a SCEVable type!");
1916   Ty = getEffectiveSCEVType(Ty);
1917 
1918   // Sign-extend negative constants.
1919   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1920     if (SC->getAPInt().isNegative())
1921       return getSignExtendExpr(Op, Ty);
1922 
1923   // Peel off a truncate cast.
1924   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
1925     const SCEV *NewOp = T->getOperand();
1926     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1927       return getAnyExtendExpr(NewOp, Ty);
1928     return getTruncateOrNoop(NewOp, Ty);
1929   }
1930 
1931   // Next try a zext cast. If the cast is folded, use it.
1932   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
1933   if (!isa<SCEVZeroExtendExpr>(ZExt))
1934     return ZExt;
1935 
1936   // Next try a sext cast. If the cast is folded, use it.
1937   const SCEV *SExt = getSignExtendExpr(Op, Ty);
1938   if (!isa<SCEVSignExtendExpr>(SExt))
1939     return SExt;
1940 
1941   // Force the cast to be folded into the operands of an addrec.
1942   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1943     SmallVector<const SCEV *, 4> Ops;
1944     for (const SCEV *Op : AR->operands())
1945       Ops.push_back(getAnyExtendExpr(Op, Ty));
1946     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
1947   }
1948 
1949   // If the expression is obviously signed, use the sext cast value.
1950   if (isa<SCEVSMaxExpr>(Op))
1951     return SExt;
1952 
1953   // Absent any other information, use the zext cast value.
1954   return ZExt;
1955 }
1956 
1957 /// Process the given Ops list, which is a list of operands to be added under
1958 /// the given scale, update the given map. This is a helper function for
1959 /// getAddRecExpr. As an example of what it does, given a sequence of operands
1960 /// that would form an add expression like this:
1961 ///
1962 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
1963 ///
1964 /// where A and B are constants, update the map with these values:
1965 ///
1966 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1967 ///
1968 /// and add 13 + A*B*29 to AccumulatedConstant.
1969 /// This will allow getAddRecExpr to produce this:
1970 ///
1971 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1972 ///
1973 /// This form often exposes folding opportunities that are hidden in
1974 /// the original operand list.
1975 ///
1976 /// Return true iff it appears that any interesting folding opportunities
1977 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
1978 /// the common case where no interesting opportunities are present, and
1979 /// is also used as a check to avoid infinite recursion.
1980 ///
1981 static bool
1982 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1983                              SmallVectorImpl<const SCEV *> &NewOps,
1984                              APInt &AccumulatedConstant,
1985                              const SCEV *const *Ops, size_t NumOperands,
1986                              const APInt &Scale,
1987                              ScalarEvolution &SE) {
1988   bool Interesting = false;
1989 
1990   // Iterate over the add operands. They are sorted, with constants first.
1991   unsigned i = 0;
1992   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1993     ++i;
1994     // Pull a buried constant out to the outside.
1995     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1996       Interesting = true;
1997     AccumulatedConstant += Scale * C->getAPInt();
1998   }
1999 
2000   // Next comes everything else. We're especially interested in multiplies
2001   // here, but they're in the middle, so just visit the rest with one loop.
2002   for (; i != NumOperands; ++i) {
2003     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2004     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2005       APInt NewScale =
2006           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2007       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2008         // A multiplication of a constant with another add; recurse.
2009         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2010         Interesting |=
2011           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2012                                        Add->op_begin(), Add->getNumOperands(),
2013                                        NewScale, SE);
2014       } else {
2015         // A multiplication of a constant with some other value. Update
2016         // the map.
2017         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2018         const SCEV *Key = SE.getMulExpr(MulOps);
2019         auto Pair = M.insert({Key, NewScale});
2020         if (Pair.second) {
2021           NewOps.push_back(Pair.first->first);
2022         } else {
2023           Pair.first->second += NewScale;
2024           // The map already had an entry for this value, which may indicate
2025           // a folding opportunity.
2026           Interesting = true;
2027         }
2028       }
2029     } else {
2030       // An ordinary operand. Update the map.
2031       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2032           M.insert({Ops[i], Scale});
2033       if (Pair.second) {
2034         NewOps.push_back(Pair.first->first);
2035       } else {
2036         Pair.first->second += Scale;
2037         // The map already had an entry for this value, which may indicate
2038         // a folding opportunity.
2039         Interesting = true;
2040       }
2041     }
2042   }
2043 
2044   return Interesting;
2045 }
2046 
2047 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2048 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2049 // can't-overflow flags for the operation if possible.
2050 static SCEV::NoWrapFlags
2051 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2052                       const SmallVectorImpl<const SCEV *> &Ops,
2053                       SCEV::NoWrapFlags Flags) {
2054   using namespace std::placeholders;
2055   typedef OverflowingBinaryOperator OBO;
2056 
2057   bool CanAnalyze =
2058       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2059   (void)CanAnalyze;
2060   assert(CanAnalyze && "don't call from other places!");
2061 
2062   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2063   SCEV::NoWrapFlags SignOrUnsignWrap =
2064       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2065 
2066   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2067   auto IsKnownNonNegative = [&](const SCEV *S) {
2068     return SE->isKnownNonNegative(S);
2069   };
2070 
2071   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2072     Flags =
2073         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2074 
2075   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2076 
2077   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2078       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2079 
2080     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2081     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2082 
2083     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2084     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2085       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2086           Instruction::Add, C, OBO::NoSignedWrap);
2087       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2088         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2089     }
2090     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2091       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2092           Instruction::Add, C, OBO::NoUnsignedWrap);
2093       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2094         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2095     }
2096   }
2097 
2098   return Flags;
2099 }
2100 
2101 /// Get a canonical add expression, or something simpler if possible.
2102 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2103                                         SCEV::NoWrapFlags Flags) {
2104   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2105          "only nuw or nsw allowed");
2106   assert(!Ops.empty() && "Cannot get empty add!");
2107   if (Ops.size() == 1) return Ops[0];
2108 #ifndef NDEBUG
2109   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2110   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2111     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2112            "SCEVAddExpr operand types don't match!");
2113 #endif
2114 
2115   // Sort by complexity, this groups all similar expression types together.
2116   GroupByComplexity(Ops, &LI);
2117 
2118   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2119 
2120   // If there are any constants, fold them together.
2121   unsigned Idx = 0;
2122   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2123     ++Idx;
2124     assert(Idx < Ops.size());
2125     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2126       // We found two constants, fold them together!
2127       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2128       if (Ops.size() == 2) return Ops[0];
2129       Ops.erase(Ops.begin()+1);  // Erase the folded element
2130       LHSC = cast<SCEVConstant>(Ops[0]);
2131     }
2132 
2133     // If we are left with a constant zero being added, strip it off.
2134     if (LHSC->getValue()->isZero()) {
2135       Ops.erase(Ops.begin());
2136       --Idx;
2137     }
2138 
2139     if (Ops.size() == 1) return Ops[0];
2140   }
2141 
2142   // Okay, check to see if the same value occurs in the operand list more than
2143   // once.  If so, merge them together into an multiply expression.  Since we
2144   // sorted the list, these values are required to be adjacent.
2145   Type *Ty = Ops[0]->getType();
2146   bool FoundMatch = false;
2147   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2148     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2149       // Scan ahead to count how many equal operands there are.
2150       unsigned Count = 2;
2151       while (i+Count != e && Ops[i+Count] == Ops[i])
2152         ++Count;
2153       // Merge the values into a multiply.
2154       const SCEV *Scale = getConstant(Ty, Count);
2155       const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2156       if (Ops.size() == Count)
2157         return Mul;
2158       Ops[i] = Mul;
2159       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2160       --i; e -= Count - 1;
2161       FoundMatch = true;
2162     }
2163   if (FoundMatch)
2164     return getAddExpr(Ops, Flags);
2165 
2166   // Check for truncates. If all the operands are truncated from the same
2167   // type, see if factoring out the truncate would permit the result to be
2168   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2169   // if the contents of the resulting outer trunc fold to something simple.
2170   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2171     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2172     Type *DstType = Trunc->getType();
2173     Type *SrcType = Trunc->getOperand()->getType();
2174     SmallVector<const SCEV *, 8> LargeOps;
2175     bool Ok = true;
2176     // Check all the operands to see if they can be represented in the
2177     // source type of the truncate.
2178     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2179       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2180         if (T->getOperand()->getType() != SrcType) {
2181           Ok = false;
2182           break;
2183         }
2184         LargeOps.push_back(T->getOperand());
2185       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2186         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2187       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2188         SmallVector<const SCEV *, 8> LargeMulOps;
2189         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2190           if (const SCEVTruncateExpr *T =
2191                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2192             if (T->getOperand()->getType() != SrcType) {
2193               Ok = false;
2194               break;
2195             }
2196             LargeMulOps.push_back(T->getOperand());
2197           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2198             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2199           } else {
2200             Ok = false;
2201             break;
2202           }
2203         }
2204         if (Ok)
2205           LargeOps.push_back(getMulExpr(LargeMulOps));
2206       } else {
2207         Ok = false;
2208         break;
2209       }
2210     }
2211     if (Ok) {
2212       // Evaluate the expression in the larger type.
2213       const SCEV *Fold = getAddExpr(LargeOps, Flags);
2214       // If it folds to something simple, use it. Otherwise, don't.
2215       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2216         return getTruncateExpr(Fold, DstType);
2217     }
2218   }
2219 
2220   // Skip past any other cast SCEVs.
2221   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2222     ++Idx;
2223 
2224   // If there are add operands they would be next.
2225   if (Idx < Ops.size()) {
2226     bool DeletedAdd = false;
2227     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2228       if (Ops.size() > AddOpsInlineThreshold ||
2229           Add->getNumOperands() > AddOpsInlineThreshold)
2230         break;
2231       // If we have an add, expand the add operands onto the end of the operands
2232       // list.
2233       Ops.erase(Ops.begin()+Idx);
2234       Ops.append(Add->op_begin(), Add->op_end());
2235       DeletedAdd = true;
2236     }
2237 
2238     // If we deleted at least one add, we added operands to the end of the list,
2239     // and they are not necessarily sorted.  Recurse to resort and resimplify
2240     // any operands we just acquired.
2241     if (DeletedAdd)
2242       return getAddExpr(Ops);
2243   }
2244 
2245   // Skip over the add expression until we get to a multiply.
2246   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2247     ++Idx;
2248 
2249   // Check to see if there are any folding opportunities present with
2250   // operands multiplied by constant values.
2251   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2252     uint64_t BitWidth = getTypeSizeInBits(Ty);
2253     DenseMap<const SCEV *, APInt> M;
2254     SmallVector<const SCEV *, 8> NewOps;
2255     APInt AccumulatedConstant(BitWidth, 0);
2256     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2257                                      Ops.data(), Ops.size(),
2258                                      APInt(BitWidth, 1), *this)) {
2259       struct APIntCompare {
2260         bool operator()(const APInt &LHS, const APInt &RHS) const {
2261           return LHS.ult(RHS);
2262         }
2263       };
2264 
2265       // Some interesting folding opportunity is present, so its worthwhile to
2266       // re-generate the operands list. Group the operands by constant scale,
2267       // to avoid multiplying by the same constant scale multiple times.
2268       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2269       for (const SCEV *NewOp : NewOps)
2270         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2271       // Re-generate the operands list.
2272       Ops.clear();
2273       if (AccumulatedConstant != 0)
2274         Ops.push_back(getConstant(AccumulatedConstant));
2275       for (auto &MulOp : MulOpLists)
2276         if (MulOp.first != 0)
2277           Ops.push_back(getMulExpr(getConstant(MulOp.first),
2278                                    getAddExpr(MulOp.second)));
2279       if (Ops.empty())
2280         return getZero(Ty);
2281       if (Ops.size() == 1)
2282         return Ops[0];
2283       return getAddExpr(Ops);
2284     }
2285   }
2286 
2287   // If we are adding something to a multiply expression, make sure the
2288   // something is not already an operand of the multiply.  If so, merge it into
2289   // the multiply.
2290   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2291     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2292     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2293       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2294       if (isa<SCEVConstant>(MulOpSCEV))
2295         continue;
2296       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2297         if (MulOpSCEV == Ops[AddOp]) {
2298           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2299           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2300           if (Mul->getNumOperands() != 2) {
2301             // If the multiply has more than two operands, we must get the
2302             // Y*Z term.
2303             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2304                                                 Mul->op_begin()+MulOp);
2305             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2306             InnerMul = getMulExpr(MulOps);
2307           }
2308           const SCEV *One = getOne(Ty);
2309           const SCEV *AddOne = getAddExpr(One, InnerMul);
2310           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
2311           if (Ops.size() == 2) return OuterMul;
2312           if (AddOp < Idx) {
2313             Ops.erase(Ops.begin()+AddOp);
2314             Ops.erase(Ops.begin()+Idx-1);
2315           } else {
2316             Ops.erase(Ops.begin()+Idx);
2317             Ops.erase(Ops.begin()+AddOp-1);
2318           }
2319           Ops.push_back(OuterMul);
2320           return getAddExpr(Ops);
2321         }
2322 
2323       // Check this multiply against other multiplies being added together.
2324       for (unsigned OtherMulIdx = Idx+1;
2325            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2326            ++OtherMulIdx) {
2327         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2328         // If MulOp occurs in OtherMul, we can fold the two multiplies
2329         // together.
2330         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2331              OMulOp != e; ++OMulOp)
2332           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2333             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2334             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2335             if (Mul->getNumOperands() != 2) {
2336               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2337                                                   Mul->op_begin()+MulOp);
2338               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2339               InnerMul1 = getMulExpr(MulOps);
2340             }
2341             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2342             if (OtherMul->getNumOperands() != 2) {
2343               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2344                                                   OtherMul->op_begin()+OMulOp);
2345               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2346               InnerMul2 = getMulExpr(MulOps);
2347             }
2348             const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2349             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
2350             if (Ops.size() == 2) return OuterMul;
2351             Ops.erase(Ops.begin()+Idx);
2352             Ops.erase(Ops.begin()+OtherMulIdx-1);
2353             Ops.push_back(OuterMul);
2354             return getAddExpr(Ops);
2355           }
2356       }
2357     }
2358   }
2359 
2360   // If there are any add recurrences in the operands list, see if any other
2361   // added values are loop invariant.  If so, we can fold them into the
2362   // recurrence.
2363   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2364     ++Idx;
2365 
2366   // Scan over all recurrences, trying to fold loop invariants into them.
2367   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2368     // Scan all of the other operands to this add and add them to the vector if
2369     // they are loop invariant w.r.t. the recurrence.
2370     SmallVector<const SCEV *, 8> LIOps;
2371     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2372     const Loop *AddRecLoop = AddRec->getLoop();
2373     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2374       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2375         LIOps.push_back(Ops[i]);
2376         Ops.erase(Ops.begin()+i);
2377         --i; --e;
2378       }
2379 
2380     // If we found some loop invariants, fold them into the recurrence.
2381     if (!LIOps.empty()) {
2382       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2383       LIOps.push_back(AddRec->getStart());
2384 
2385       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2386                                              AddRec->op_end());
2387       // This follows from the fact that the no-wrap flags on the outer add
2388       // expression are applicable on the 0th iteration, when the add recurrence
2389       // will be equal to its start value.
2390       AddRecOps[0] = getAddExpr(LIOps, Flags);
2391 
2392       // Build the new addrec. Propagate the NUW and NSW flags if both the
2393       // outer add and the inner addrec are guaranteed to have no overflow.
2394       // Always propagate NW.
2395       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2396       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2397 
2398       // If all of the other operands were loop invariant, we are done.
2399       if (Ops.size() == 1) return NewRec;
2400 
2401       // Otherwise, add the folded AddRec by the non-invariant parts.
2402       for (unsigned i = 0;; ++i)
2403         if (Ops[i] == AddRec) {
2404           Ops[i] = NewRec;
2405           break;
2406         }
2407       return getAddExpr(Ops);
2408     }
2409 
2410     // Okay, if there weren't any loop invariants to be folded, check to see if
2411     // there are multiple AddRec's with the same loop induction variable being
2412     // added together.  If so, we can fold them.
2413     for (unsigned OtherIdx = Idx+1;
2414          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2415          ++OtherIdx)
2416       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2417         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2418         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2419                                                AddRec->op_end());
2420         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2421              ++OtherIdx)
2422           if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
2423             if (OtherAddRec->getLoop() == AddRecLoop) {
2424               for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2425                    i != e; ++i) {
2426                 if (i >= AddRecOps.size()) {
2427                   AddRecOps.append(OtherAddRec->op_begin()+i,
2428                                    OtherAddRec->op_end());
2429                   break;
2430                 }
2431                 AddRecOps[i] = getAddExpr(AddRecOps[i],
2432                                           OtherAddRec->getOperand(i));
2433               }
2434               Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2435             }
2436         // Step size has changed, so we cannot guarantee no self-wraparound.
2437         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2438         return getAddExpr(Ops);
2439       }
2440 
2441     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2442     // next one.
2443   }
2444 
2445   // Okay, it looks like we really DO need an add expr.  Check to see if we
2446   // already have one, otherwise create a new one.
2447   FoldingSetNodeID ID;
2448   ID.AddInteger(scAddExpr);
2449   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2450     ID.AddPointer(Ops[i]);
2451   void *IP = nullptr;
2452   SCEVAddExpr *S =
2453     static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2454   if (!S) {
2455     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2456     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2457     S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2458                                         O, Ops.size());
2459     UniqueSCEVs.InsertNode(S, IP);
2460   }
2461   S->setNoWrapFlags(Flags);
2462   return S;
2463 }
2464 
2465 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2466   uint64_t k = i*j;
2467   if (j > 1 && k / j != i) Overflow = true;
2468   return k;
2469 }
2470 
2471 /// Compute the result of "n choose k", the binomial coefficient.  If an
2472 /// intermediate computation overflows, Overflow will be set and the return will
2473 /// be garbage. Overflow is not cleared on absence of overflow.
2474 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2475   // We use the multiplicative formula:
2476   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2477   // At each iteration, we take the n-th term of the numeral and divide by the
2478   // (k-n)th term of the denominator.  This division will always produce an
2479   // integral result, and helps reduce the chance of overflow in the
2480   // intermediate computations. However, we can still overflow even when the
2481   // final result would fit.
2482 
2483   if (n == 0 || n == k) return 1;
2484   if (k > n) return 0;
2485 
2486   if (k > n/2)
2487     k = n-k;
2488 
2489   uint64_t r = 1;
2490   for (uint64_t i = 1; i <= k; ++i) {
2491     r = umul_ov(r, n-(i-1), Overflow);
2492     r /= i;
2493   }
2494   return r;
2495 }
2496 
2497 /// Determine if any of the operands in this SCEV are a constant or if
2498 /// any of the add or multiply expressions in this SCEV contain a constant.
2499 static bool containsConstantSomewhere(const SCEV *StartExpr) {
2500   SmallVector<const SCEV *, 4> Ops;
2501   Ops.push_back(StartExpr);
2502   while (!Ops.empty()) {
2503     const SCEV *CurrentExpr = Ops.pop_back_val();
2504     if (isa<SCEVConstant>(*CurrentExpr))
2505       return true;
2506 
2507     if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2508       const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
2509       Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
2510     }
2511   }
2512   return false;
2513 }
2514 
2515 /// Get a canonical multiply expression, or something simpler if possible.
2516 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2517                                         SCEV::NoWrapFlags Flags) {
2518   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2519          "only nuw or nsw allowed");
2520   assert(!Ops.empty() && "Cannot get empty mul!");
2521   if (Ops.size() == 1) return Ops[0];
2522 #ifndef NDEBUG
2523   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2524   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2525     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2526            "SCEVMulExpr operand types don't match!");
2527 #endif
2528 
2529   // Sort by complexity, this groups all similar expression types together.
2530   GroupByComplexity(Ops, &LI);
2531 
2532   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2533 
2534   // If there are any constants, fold them together.
2535   unsigned Idx = 0;
2536   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2537 
2538     // C1*(C2+V) -> C1*C2 + C1*V
2539     if (Ops.size() == 2)
2540         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2541           // If any of Add's ops are Adds or Muls with a constant,
2542           // apply this transformation as well.
2543           if (Add->getNumOperands() == 2)
2544             if (containsConstantSomewhere(Add))
2545               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2546                                 getMulExpr(LHSC, Add->getOperand(1)));
2547 
2548     ++Idx;
2549     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2550       // We found two constants, fold them together!
2551       ConstantInt *Fold =
2552           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2553       Ops[0] = getConstant(Fold);
2554       Ops.erase(Ops.begin()+1);  // Erase the folded element
2555       if (Ops.size() == 1) return Ops[0];
2556       LHSC = cast<SCEVConstant>(Ops[0]);
2557     }
2558 
2559     // If we are left with a constant one being multiplied, strip it off.
2560     if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2561       Ops.erase(Ops.begin());
2562       --Idx;
2563     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2564       // If we have a multiply of zero, it will always be zero.
2565       return Ops[0];
2566     } else if (Ops[0]->isAllOnesValue()) {
2567       // If we have a mul by -1 of an add, try distributing the -1 among the
2568       // add operands.
2569       if (Ops.size() == 2) {
2570         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2571           SmallVector<const SCEV *, 4> NewOps;
2572           bool AnyFolded = false;
2573           for (const SCEV *AddOp : Add->operands()) {
2574             const SCEV *Mul = getMulExpr(Ops[0], AddOp);
2575             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2576             NewOps.push_back(Mul);
2577           }
2578           if (AnyFolded)
2579             return getAddExpr(NewOps);
2580         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2581           // Negation preserves a recurrence's no self-wrap property.
2582           SmallVector<const SCEV *, 4> Operands;
2583           for (const SCEV *AddRecOp : AddRec->operands())
2584             Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2585 
2586           return getAddRecExpr(Operands, AddRec->getLoop(),
2587                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2588         }
2589       }
2590     }
2591 
2592     if (Ops.size() == 1)
2593       return Ops[0];
2594   }
2595 
2596   // Skip over the add expression until we get to a multiply.
2597   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2598     ++Idx;
2599 
2600   // If there are mul operands inline them all into this expression.
2601   if (Idx < Ops.size()) {
2602     bool DeletedMul = false;
2603     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2604       if (Ops.size() > MulOpsInlineThreshold)
2605         break;
2606       // If we have an mul, expand the mul operands onto the end of the operands
2607       // list.
2608       Ops.erase(Ops.begin()+Idx);
2609       Ops.append(Mul->op_begin(), Mul->op_end());
2610       DeletedMul = true;
2611     }
2612 
2613     // If we deleted at least one mul, we added operands to the end of the list,
2614     // and they are not necessarily sorted.  Recurse to resort and resimplify
2615     // any operands we just acquired.
2616     if (DeletedMul)
2617       return getMulExpr(Ops);
2618   }
2619 
2620   // If there are any add recurrences in the operands list, see if any other
2621   // added values are loop invariant.  If so, we can fold them into the
2622   // recurrence.
2623   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2624     ++Idx;
2625 
2626   // Scan over all recurrences, trying to fold loop invariants into them.
2627   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2628     // Scan all of the other operands to this mul and add them to the vector if
2629     // they are loop invariant w.r.t. the recurrence.
2630     SmallVector<const SCEV *, 8> LIOps;
2631     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2632     const Loop *AddRecLoop = AddRec->getLoop();
2633     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2634       if (isLoopInvariant(Ops[i], AddRecLoop)) {
2635         LIOps.push_back(Ops[i]);
2636         Ops.erase(Ops.begin()+i);
2637         --i; --e;
2638       }
2639 
2640     // If we found some loop invariants, fold them into the recurrence.
2641     if (!LIOps.empty()) {
2642       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2643       SmallVector<const SCEV *, 4> NewOps;
2644       NewOps.reserve(AddRec->getNumOperands());
2645       const SCEV *Scale = getMulExpr(LIOps);
2646       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2647         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
2648 
2649       // Build the new addrec. Propagate the NUW and NSW flags if both the
2650       // outer mul and the inner addrec are guaranteed to have no overflow.
2651       //
2652       // No self-wrap cannot be guaranteed after changing the step size, but
2653       // will be inferred if either NUW or NSW is true.
2654       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2655       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2656 
2657       // If all of the other operands were loop invariant, we are done.
2658       if (Ops.size() == 1) return NewRec;
2659 
2660       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2661       for (unsigned i = 0;; ++i)
2662         if (Ops[i] == AddRec) {
2663           Ops[i] = NewRec;
2664           break;
2665         }
2666       return getMulExpr(Ops);
2667     }
2668 
2669     // Okay, if there weren't any loop invariants to be folded, check to see if
2670     // there are multiple AddRec's with the same loop induction variable being
2671     // multiplied together.  If so, we can fold them.
2672 
2673     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2674     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2675     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2676     //   ]]],+,...up to x=2n}.
2677     // Note that the arguments to choose() are always integers with values
2678     // known at compile time, never SCEV objects.
2679     //
2680     // The implementation avoids pointless extra computations when the two
2681     // addrec's are of different length (mathematically, it's equivalent to
2682     // an infinite stream of zeros on the right).
2683     bool OpsModified = false;
2684     for (unsigned OtherIdx = Idx+1;
2685          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2686          ++OtherIdx) {
2687       const SCEVAddRecExpr *OtherAddRec =
2688         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2689       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2690         continue;
2691 
2692       bool Overflow = false;
2693       Type *Ty = AddRec->getType();
2694       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2695       SmallVector<const SCEV*, 7> AddRecOps;
2696       for (int x = 0, xe = AddRec->getNumOperands() +
2697              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2698         const SCEV *Term = getZero(Ty);
2699         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2700           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2701           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2702                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2703                z < ze && !Overflow; ++z) {
2704             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2705             uint64_t Coeff;
2706             if (LargerThan64Bits)
2707               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2708             else
2709               Coeff = Coeff1*Coeff2;
2710             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2711             const SCEV *Term1 = AddRec->getOperand(y-z);
2712             const SCEV *Term2 = OtherAddRec->getOperand(z);
2713             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
2714           }
2715         }
2716         AddRecOps.push_back(Term);
2717       }
2718       if (!Overflow) {
2719         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2720                                               SCEV::FlagAnyWrap);
2721         if (Ops.size() == 2) return NewAddRec;
2722         Ops[Idx] = NewAddRec;
2723         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2724         OpsModified = true;
2725         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2726         if (!AddRec)
2727           break;
2728       }
2729     }
2730     if (OpsModified)
2731       return getMulExpr(Ops);
2732 
2733     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2734     // next one.
2735   }
2736 
2737   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2738   // already have one, otherwise create a new one.
2739   FoldingSetNodeID ID;
2740   ID.AddInteger(scMulExpr);
2741   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2742     ID.AddPointer(Ops[i]);
2743   void *IP = nullptr;
2744   SCEVMulExpr *S =
2745     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2746   if (!S) {
2747     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2748     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2749     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2750                                         O, Ops.size());
2751     UniqueSCEVs.InsertNode(S, IP);
2752   }
2753   S->setNoWrapFlags(Flags);
2754   return S;
2755 }
2756 
2757 /// Get a canonical unsigned division expression, or something simpler if
2758 /// possible.
2759 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2760                                          const SCEV *RHS) {
2761   assert(getEffectiveSCEVType(LHS->getType()) ==
2762          getEffectiveSCEVType(RHS->getType()) &&
2763          "SCEVUDivExpr operand types don't match!");
2764 
2765   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2766     if (RHSC->getValue()->equalsInt(1))
2767       return LHS;                               // X udiv 1 --> x
2768     // If the denominator is zero, the result of the udiv is undefined. Don't
2769     // try to analyze it, because the resolution chosen here may differ from
2770     // the resolution chosen in other parts of the compiler.
2771     if (!RHSC->getValue()->isZero()) {
2772       // Determine if the division can be folded into the operands of
2773       // its operands.
2774       // TODO: Generalize this to non-constants by using known-bits information.
2775       Type *Ty = LHS->getType();
2776       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2777       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2778       // For non-power-of-two values, effectively round the value up to the
2779       // nearest power of two.
2780       if (!RHSC->getAPInt().isPowerOf2())
2781         ++MaxShiftAmt;
2782       IntegerType *ExtTy =
2783         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2784       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2785         if (const SCEVConstant *Step =
2786             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2787           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2788           const APInt &StepInt = Step->getAPInt();
2789           const APInt &DivInt = RHSC->getAPInt();
2790           if (!StepInt.urem(DivInt) &&
2791               getZeroExtendExpr(AR, ExtTy) ==
2792               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2793                             getZeroExtendExpr(Step, ExtTy),
2794                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2795             SmallVector<const SCEV *, 4> Operands;
2796             for (const SCEV *Op : AR->operands())
2797               Operands.push_back(getUDivExpr(Op, RHS));
2798             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2799           }
2800           /// Get a canonical UDivExpr for a recurrence.
2801           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2802           // We can currently only fold X%N if X is constant.
2803           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2804           if (StartC && !DivInt.urem(StepInt) &&
2805               getZeroExtendExpr(AR, ExtTy) ==
2806               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2807                             getZeroExtendExpr(Step, ExtTy),
2808                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2809             const APInt &StartInt = StartC->getAPInt();
2810             const APInt &StartRem = StartInt.urem(StepInt);
2811             if (StartRem != 0)
2812               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2813                                   AR->getLoop(), SCEV::FlagNW);
2814           }
2815         }
2816       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2817       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2818         SmallVector<const SCEV *, 4> Operands;
2819         for (const SCEV *Op : M->operands())
2820           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2821         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2822           // Find an operand that's safely divisible.
2823           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2824             const SCEV *Op = M->getOperand(i);
2825             const SCEV *Div = getUDivExpr(Op, RHSC);
2826             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2827               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2828                                                       M->op_end());
2829               Operands[i] = Div;
2830               return getMulExpr(Operands);
2831             }
2832           }
2833       }
2834       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
2835       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
2836         SmallVector<const SCEV *, 4> Operands;
2837         for (const SCEV *Op : A->operands())
2838           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
2839         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2840           Operands.clear();
2841           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2842             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2843             if (isa<SCEVUDivExpr>(Op) ||
2844                 getMulExpr(Op, RHS) != A->getOperand(i))
2845               break;
2846             Operands.push_back(Op);
2847           }
2848           if (Operands.size() == A->getNumOperands())
2849             return getAddExpr(Operands);
2850         }
2851       }
2852 
2853       // Fold if both operands are constant.
2854       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2855         Constant *LHSCV = LHSC->getValue();
2856         Constant *RHSCV = RHSC->getValue();
2857         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2858                                                                    RHSCV)));
2859       }
2860     }
2861   }
2862 
2863   FoldingSetNodeID ID;
2864   ID.AddInteger(scUDivExpr);
2865   ID.AddPointer(LHS);
2866   ID.AddPointer(RHS);
2867   void *IP = nullptr;
2868   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2869   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2870                                              LHS, RHS);
2871   UniqueSCEVs.InsertNode(S, IP);
2872   return S;
2873 }
2874 
2875 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2876   APInt A = C1->getAPInt().abs();
2877   APInt B = C2->getAPInt().abs();
2878   uint32_t ABW = A.getBitWidth();
2879   uint32_t BBW = B.getBitWidth();
2880 
2881   if (ABW > BBW)
2882     B = B.zext(ABW);
2883   else if (ABW < BBW)
2884     A = A.zext(BBW);
2885 
2886   return APIntOps::GreatestCommonDivisor(A, B);
2887 }
2888 
2889 /// Get a canonical unsigned division expression, or something simpler if
2890 /// possible. There is no representation for an exact udiv in SCEV IR, but we
2891 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
2892 /// it's not exact because the udiv may be clearing bits.
2893 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2894                                               const SCEV *RHS) {
2895   // TODO: we could try to find factors in all sorts of things, but for now we
2896   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2897   // end of this file for inspiration.
2898 
2899   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2900   if (!Mul || !Mul->hasNoUnsignedWrap())
2901     return getUDivExpr(LHS, RHS);
2902 
2903   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2904     // If the mulexpr multiplies by a constant, then that constant must be the
2905     // first element of the mulexpr.
2906     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2907       if (LHSCst == RHSCst) {
2908         SmallVector<const SCEV *, 2> Operands;
2909         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2910         return getMulExpr(Operands);
2911       }
2912 
2913       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2914       // that there's a factor provided by one of the other terms. We need to
2915       // check.
2916       APInt Factor = gcd(LHSCst, RHSCst);
2917       if (!Factor.isIntN(1)) {
2918         LHSCst =
2919             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2920         RHSCst =
2921             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
2922         SmallVector<const SCEV *, 2> Operands;
2923         Operands.push_back(LHSCst);
2924         Operands.append(Mul->op_begin() + 1, Mul->op_end());
2925         LHS = getMulExpr(Operands);
2926         RHS = RHSCst;
2927         Mul = dyn_cast<SCEVMulExpr>(LHS);
2928         if (!Mul)
2929           return getUDivExactExpr(LHS, RHS);
2930       }
2931     }
2932   }
2933 
2934   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2935     if (Mul->getOperand(i) == RHS) {
2936       SmallVector<const SCEV *, 2> Operands;
2937       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2938       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2939       return getMulExpr(Operands);
2940     }
2941   }
2942 
2943   return getUDivExpr(LHS, RHS);
2944 }
2945 
2946 /// Get an add recurrence expression for the specified loop.  Simplify the
2947 /// expression as much as possible.
2948 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2949                                            const Loop *L,
2950                                            SCEV::NoWrapFlags Flags) {
2951   SmallVector<const SCEV *, 4> Operands;
2952   Operands.push_back(Start);
2953   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
2954     if (StepChrec->getLoop() == L) {
2955       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
2956       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
2957     }
2958 
2959   Operands.push_back(Step);
2960   return getAddRecExpr(Operands, L, Flags);
2961 }
2962 
2963 /// Get an add recurrence expression for the specified loop.  Simplify the
2964 /// expression as much as possible.
2965 const SCEV *
2966 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
2967                                const Loop *L, SCEV::NoWrapFlags Flags) {
2968   if (Operands.size() == 1) return Operands[0];
2969 #ifndef NDEBUG
2970   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
2971   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2972     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
2973            "SCEVAddRecExpr operand types don't match!");
2974   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2975     assert(isLoopInvariant(Operands[i], L) &&
2976            "SCEVAddRecExpr operand is not loop-invariant!");
2977 #endif
2978 
2979   if (Operands.back()->isZero()) {
2980     Operands.pop_back();
2981     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
2982   }
2983 
2984   // It's tempting to want to call getMaxBackedgeTakenCount count here and
2985   // use that information to infer NUW and NSW flags. However, computing a
2986   // BE count requires calling getAddRecExpr, so we may not yet have a
2987   // meaningful BE count at this point (and if we don't, we'd be stuck
2988   // with a SCEVCouldNotCompute as the cached BE count).
2989 
2990   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
2991 
2992   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
2993   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
2994     const Loop *NestedLoop = NestedAR->getLoop();
2995     if (L->contains(NestedLoop)
2996             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2997             : (!NestedLoop->contains(L) &&
2998                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
2999       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3000                                                   NestedAR->op_end());
3001       Operands[0] = NestedAR->getStart();
3002       // AddRecs require their operands be loop-invariant with respect to their
3003       // loops. Don't perform this transformation if it would break this
3004       // requirement.
3005       bool AllInvariant = all_of(
3006           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3007 
3008       if (AllInvariant) {
3009         // Create a recurrence for the outer loop with the same step size.
3010         //
3011         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3012         // inner recurrence has the same property.
3013         SCEV::NoWrapFlags OuterFlags =
3014           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3015 
3016         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3017         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3018           return isLoopInvariant(Op, NestedLoop);
3019         });
3020 
3021         if (AllInvariant) {
3022           // Ok, both add recurrences are valid after the transformation.
3023           //
3024           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3025           // the outer recurrence has the same property.
3026           SCEV::NoWrapFlags InnerFlags =
3027             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3028           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3029         }
3030       }
3031       // Reset Operands to its original state.
3032       Operands[0] = NestedAR;
3033     }
3034   }
3035 
3036   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3037   // already have one, otherwise create a new one.
3038   FoldingSetNodeID ID;
3039   ID.AddInteger(scAddRecExpr);
3040   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3041     ID.AddPointer(Operands[i]);
3042   ID.AddPointer(L);
3043   void *IP = nullptr;
3044   SCEVAddRecExpr *S =
3045     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3046   if (!S) {
3047     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3048     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3049     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3050                                            O, Operands.size(), L);
3051     UniqueSCEVs.InsertNode(S, IP);
3052   }
3053   S->setNoWrapFlags(Flags);
3054   return S;
3055 }
3056 
3057 const SCEV *
3058 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3059                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3060   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3061   // getSCEV(Base)->getType() has the same address space as Base->getType()
3062   // because SCEV::getType() preserves the address space.
3063   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3064   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3065   // instruction to its SCEV, because the Instruction may be guarded by control
3066   // flow and the no-overflow bits may not be valid for the expression in any
3067   // context. This can be fixed similarly to how these flags are handled for
3068   // adds.
3069   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3070                                              : SCEV::FlagAnyWrap;
3071 
3072   const SCEV *TotalOffset = getZero(IntPtrTy);
3073   // The array size is unimportant. The first thing we do on CurTy is getting
3074   // its element type.
3075   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3076   for (const SCEV *IndexExpr : IndexExprs) {
3077     // Compute the (potentially symbolic) offset in bytes for this index.
3078     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3079       // For a struct, add the member offset.
3080       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3081       unsigned FieldNo = Index->getZExtValue();
3082       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3083 
3084       // Add the field offset to the running total offset.
3085       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3086 
3087       // Update CurTy to the type of the field at Index.
3088       CurTy = STy->getTypeAtIndex(Index);
3089     } else {
3090       // Update CurTy to its element type.
3091       CurTy = cast<SequentialType>(CurTy)->getElementType();
3092       // For an array, add the element offset, explicitly scaled.
3093       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3094       // Getelementptr indices are signed.
3095       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3096 
3097       // Multiply the index by the element size to compute the element offset.
3098       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3099 
3100       // Add the element offset to the running total offset.
3101       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3102     }
3103   }
3104 
3105   // Add the total offset from all the GEP indices to the base.
3106   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3107 }
3108 
3109 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3110                                          const SCEV *RHS) {
3111   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3112   return getSMaxExpr(Ops);
3113 }
3114 
3115 const SCEV *
3116 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3117   assert(!Ops.empty() && "Cannot get empty smax!");
3118   if (Ops.size() == 1) return Ops[0];
3119 #ifndef NDEBUG
3120   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3121   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3122     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3123            "SCEVSMaxExpr operand types don't match!");
3124 #endif
3125 
3126   // Sort by complexity, this groups all similar expression types together.
3127   GroupByComplexity(Ops, &LI);
3128 
3129   // If there are any constants, fold them together.
3130   unsigned Idx = 0;
3131   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3132     ++Idx;
3133     assert(Idx < Ops.size());
3134     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3135       // We found two constants, fold them together!
3136       ConstantInt *Fold = ConstantInt::get(
3137           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3138       Ops[0] = getConstant(Fold);
3139       Ops.erase(Ops.begin()+1);  // Erase the folded element
3140       if (Ops.size() == 1) return Ops[0];
3141       LHSC = cast<SCEVConstant>(Ops[0]);
3142     }
3143 
3144     // If we are left with a constant minimum-int, strip it off.
3145     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3146       Ops.erase(Ops.begin());
3147       --Idx;
3148     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3149       // If we have an smax with a constant maximum-int, it will always be
3150       // maximum-int.
3151       return Ops[0];
3152     }
3153 
3154     if (Ops.size() == 1) return Ops[0];
3155   }
3156 
3157   // Find the first SMax
3158   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3159     ++Idx;
3160 
3161   // Check to see if one of the operands is an SMax. If so, expand its operands
3162   // onto our operand list, and recurse to simplify.
3163   if (Idx < Ops.size()) {
3164     bool DeletedSMax = false;
3165     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3166       Ops.erase(Ops.begin()+Idx);
3167       Ops.append(SMax->op_begin(), SMax->op_end());
3168       DeletedSMax = true;
3169     }
3170 
3171     if (DeletedSMax)
3172       return getSMaxExpr(Ops);
3173   }
3174 
3175   // Okay, check to see if the same value occurs in the operand list twice.  If
3176   // so, delete one.  Since we sorted the list, these values are required to
3177   // be adjacent.
3178   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3179     //  X smax Y smax Y  -->  X smax Y
3180     //  X smax Y         -->  X, if X is always greater than Y
3181     if (Ops[i] == Ops[i+1] ||
3182         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3183       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3184       --i; --e;
3185     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3186       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3187       --i; --e;
3188     }
3189 
3190   if (Ops.size() == 1) return Ops[0];
3191 
3192   assert(!Ops.empty() && "Reduced smax down to nothing!");
3193 
3194   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3195   // already have one, otherwise create a new one.
3196   FoldingSetNodeID ID;
3197   ID.AddInteger(scSMaxExpr);
3198   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3199     ID.AddPointer(Ops[i]);
3200   void *IP = nullptr;
3201   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3202   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3203   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3204   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3205                                              O, Ops.size());
3206   UniqueSCEVs.InsertNode(S, IP);
3207   return S;
3208 }
3209 
3210 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3211                                          const SCEV *RHS) {
3212   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3213   return getUMaxExpr(Ops);
3214 }
3215 
3216 const SCEV *
3217 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3218   assert(!Ops.empty() && "Cannot get empty umax!");
3219   if (Ops.size() == 1) return Ops[0];
3220 #ifndef NDEBUG
3221   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3222   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3223     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3224            "SCEVUMaxExpr operand types don't match!");
3225 #endif
3226 
3227   // Sort by complexity, this groups all similar expression types together.
3228   GroupByComplexity(Ops, &LI);
3229 
3230   // If there are any constants, fold them together.
3231   unsigned Idx = 0;
3232   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3233     ++Idx;
3234     assert(Idx < Ops.size());
3235     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3236       // We found two constants, fold them together!
3237       ConstantInt *Fold = ConstantInt::get(
3238           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3239       Ops[0] = getConstant(Fold);
3240       Ops.erase(Ops.begin()+1);  // Erase the folded element
3241       if (Ops.size() == 1) return Ops[0];
3242       LHSC = cast<SCEVConstant>(Ops[0]);
3243     }
3244 
3245     // If we are left with a constant minimum-int, strip it off.
3246     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3247       Ops.erase(Ops.begin());
3248       --Idx;
3249     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3250       // If we have an umax with a constant maximum-int, it will always be
3251       // maximum-int.
3252       return Ops[0];
3253     }
3254 
3255     if (Ops.size() == 1) return Ops[0];
3256   }
3257 
3258   // Find the first UMax
3259   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3260     ++Idx;
3261 
3262   // Check to see if one of the operands is a UMax. If so, expand its operands
3263   // onto our operand list, and recurse to simplify.
3264   if (Idx < Ops.size()) {
3265     bool DeletedUMax = false;
3266     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3267       Ops.erase(Ops.begin()+Idx);
3268       Ops.append(UMax->op_begin(), UMax->op_end());
3269       DeletedUMax = true;
3270     }
3271 
3272     if (DeletedUMax)
3273       return getUMaxExpr(Ops);
3274   }
3275 
3276   // Okay, check to see if the same value occurs in the operand list twice.  If
3277   // so, delete one.  Since we sorted the list, these values are required to
3278   // be adjacent.
3279   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3280     //  X umax Y umax Y  -->  X umax Y
3281     //  X umax Y         -->  X, if X is always greater than Y
3282     if (Ops[i] == Ops[i+1] ||
3283         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3284       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3285       --i; --e;
3286     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3287       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3288       --i; --e;
3289     }
3290 
3291   if (Ops.size() == 1) return Ops[0];
3292 
3293   assert(!Ops.empty() && "Reduced umax down to nothing!");
3294 
3295   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3296   // already have one, otherwise create a new one.
3297   FoldingSetNodeID ID;
3298   ID.AddInteger(scUMaxExpr);
3299   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3300     ID.AddPointer(Ops[i]);
3301   void *IP = nullptr;
3302   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3303   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3304   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3305   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3306                                              O, Ops.size());
3307   UniqueSCEVs.InsertNode(S, IP);
3308   return S;
3309 }
3310 
3311 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3312                                          const SCEV *RHS) {
3313   // ~smax(~x, ~y) == smin(x, y).
3314   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3315 }
3316 
3317 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3318                                          const SCEV *RHS) {
3319   // ~umax(~x, ~y) == umin(x, y)
3320   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3321 }
3322 
3323 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3324   // We can bypass creating a target-independent
3325   // constant expression and then folding it back into a ConstantInt.
3326   // This is just a compile-time optimization.
3327   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3328 }
3329 
3330 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3331                                              StructType *STy,
3332                                              unsigned FieldNo) {
3333   // We can bypass creating a target-independent
3334   // constant expression and then folding it back into a ConstantInt.
3335   // This is just a compile-time optimization.
3336   return getConstant(
3337       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3338 }
3339 
3340 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3341   // Don't attempt to do anything other than create a SCEVUnknown object
3342   // here.  createSCEV only calls getUnknown after checking for all other
3343   // interesting possibilities, and any other code that calls getUnknown
3344   // is doing so in order to hide a value from SCEV canonicalization.
3345 
3346   FoldingSetNodeID ID;
3347   ID.AddInteger(scUnknown);
3348   ID.AddPointer(V);
3349   void *IP = nullptr;
3350   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3351     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3352            "Stale SCEVUnknown in uniquing map!");
3353     return S;
3354   }
3355   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3356                                             FirstUnknown);
3357   FirstUnknown = cast<SCEVUnknown>(S);
3358   UniqueSCEVs.InsertNode(S, IP);
3359   return S;
3360 }
3361 
3362 //===----------------------------------------------------------------------===//
3363 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3364 //
3365 
3366 /// Test if values of the given type are analyzable within the SCEV
3367 /// framework. This primarily includes integer types, and it can optionally
3368 /// include pointer types if the ScalarEvolution class has access to
3369 /// target-specific information.
3370 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3371   // Integers and pointers are always SCEVable.
3372   return Ty->isIntegerTy() || Ty->isPointerTy();
3373 }
3374 
3375 /// Return the size in bits of the specified type, for which isSCEVable must
3376 /// return true.
3377 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3378   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3379   return getDataLayout().getTypeSizeInBits(Ty);
3380 }
3381 
3382 /// Return a type with the same bitwidth as the given type and which represents
3383 /// how SCEV will treat the given type, for which isSCEVable must return
3384 /// true. For pointer types, this is the pointer-sized integer type.
3385 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3386   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3387 
3388   if (Ty->isIntegerTy())
3389     return Ty;
3390 
3391   // The only other support type is pointer.
3392   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3393   return getDataLayout().getIntPtrType(Ty);
3394 }
3395 
3396 const SCEV *ScalarEvolution::getCouldNotCompute() {
3397   return CouldNotCompute.get();
3398 }
3399 
3400 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3401   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3402     auto *SU = dyn_cast<SCEVUnknown>(S);
3403     return SU && SU->getValue() == nullptr;
3404   });
3405 
3406   return !ContainsNulls;
3407 }
3408 
3409 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3410   HasRecMapType::iterator I = HasRecMap.find(S);
3411   if (I != HasRecMap.end())
3412     return I->second;
3413 
3414   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3415   HasRecMap.insert({S, FoundAddRec});
3416   return FoundAddRec;
3417 }
3418 
3419 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3420 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3421 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3422 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3423   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3424   if (!Add)
3425     return {S, nullptr};
3426 
3427   if (Add->getNumOperands() != 2)
3428     return {S, nullptr};
3429 
3430   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3431   if (!ConstOp)
3432     return {S, nullptr};
3433 
3434   return {Add->getOperand(1), ConstOp->getValue()};
3435 }
3436 
3437 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3438 /// by the value and offset from any ValueOffsetPair in the set.
3439 SetVector<ScalarEvolution::ValueOffsetPair> *
3440 ScalarEvolution::getSCEVValues(const SCEV *S) {
3441   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3442   if (SI == ExprValueMap.end())
3443     return nullptr;
3444 #ifndef NDEBUG
3445   if (VerifySCEVMap) {
3446     // Check there is no dangling Value in the set returned.
3447     for (const auto &VE : SI->second)
3448       assert(ValueExprMap.count(VE.first));
3449   }
3450 #endif
3451   return &SI->second;
3452 }
3453 
3454 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3455 /// cannot be used separately. eraseValueFromMap should be used to remove
3456 /// V from ValueExprMap and ExprValueMap at the same time.
3457 void ScalarEvolution::eraseValueFromMap(Value *V) {
3458   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3459   if (I != ValueExprMap.end()) {
3460     const SCEV *S = I->second;
3461     // Remove {V, 0} from the set of ExprValueMap[S]
3462     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3463       SV->remove({V, nullptr});
3464 
3465     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3466     const SCEV *Stripped;
3467     ConstantInt *Offset;
3468     std::tie(Stripped, Offset) = splitAddExpr(S);
3469     if (Offset != nullptr) {
3470       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3471         SV->remove({V, Offset});
3472     }
3473     ValueExprMap.erase(V);
3474   }
3475 }
3476 
3477 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3478 /// create a new one.
3479 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3480   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3481 
3482   const SCEV *S = getExistingSCEV(V);
3483   if (S == nullptr) {
3484     S = createSCEV(V);
3485     // During PHI resolution, it is possible to create two SCEVs for the same
3486     // V, so it is needed to double check whether V->S is inserted into
3487     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3488     std::pair<ValueExprMapType::iterator, bool> Pair =
3489         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3490     if (Pair.second) {
3491       ExprValueMap[S].insert({V, nullptr});
3492 
3493       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3494       // ExprValueMap.
3495       const SCEV *Stripped = S;
3496       ConstantInt *Offset = nullptr;
3497       std::tie(Stripped, Offset) = splitAddExpr(S);
3498       // If stripped is SCEVUnknown, don't bother to save
3499       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3500       // increase the complexity of the expansion code.
3501       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3502       // because it may generate add/sub instead of GEP in SCEV expansion.
3503       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3504           !isa<GetElementPtrInst>(V))
3505         ExprValueMap[Stripped].insert({V, Offset});
3506     }
3507   }
3508   return S;
3509 }
3510 
3511 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3512   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3513 
3514   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3515   if (I != ValueExprMap.end()) {
3516     const SCEV *S = I->second;
3517     if (checkValidity(S))
3518       return S;
3519     eraseValueFromMap(V);
3520     forgetMemoizedResults(S);
3521   }
3522   return nullptr;
3523 }
3524 
3525 /// Return a SCEV corresponding to -V = -1*V
3526 ///
3527 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3528                                              SCEV::NoWrapFlags Flags) {
3529   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3530     return getConstant(
3531                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3532 
3533   Type *Ty = V->getType();
3534   Ty = getEffectiveSCEVType(Ty);
3535   return getMulExpr(
3536       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3537 }
3538 
3539 /// Return a SCEV corresponding to ~V = -1-V
3540 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3541   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3542     return getConstant(
3543                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3544 
3545   Type *Ty = V->getType();
3546   Ty = getEffectiveSCEVType(Ty);
3547   const SCEV *AllOnes =
3548                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3549   return getMinusSCEV(AllOnes, V);
3550 }
3551 
3552 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3553                                           SCEV::NoWrapFlags Flags) {
3554   // Fast path: X - X --> 0.
3555   if (LHS == RHS)
3556     return getZero(LHS->getType());
3557 
3558   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3559   // makes it so that we cannot make much use of NUW.
3560   auto AddFlags = SCEV::FlagAnyWrap;
3561   const bool RHSIsNotMinSigned =
3562       !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3563   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3564     // Let M be the minimum representable signed value. Then (-1)*RHS
3565     // signed-wraps if and only if RHS is M. That can happen even for
3566     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3567     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3568     // (-1)*RHS, we need to prove that RHS != M.
3569     //
3570     // If LHS is non-negative and we know that LHS - RHS does not
3571     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3572     // either by proving that RHS > M or that LHS >= 0.
3573     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3574       AddFlags = SCEV::FlagNSW;
3575     }
3576   }
3577 
3578   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3579   // RHS is NSW and LHS >= 0.
3580   //
3581   // The difficulty here is that the NSW flag may have been proven
3582   // relative to a loop that is to be found in a recurrence in LHS and
3583   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3584   // larger scope than intended.
3585   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3586 
3587   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
3588 }
3589 
3590 const SCEV *
3591 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3592   Type *SrcTy = V->getType();
3593   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3594          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3595          "Cannot truncate or zero extend with non-integer arguments!");
3596   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3597     return V;  // No conversion
3598   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3599     return getTruncateExpr(V, Ty);
3600   return getZeroExtendExpr(V, Ty);
3601 }
3602 
3603 const SCEV *
3604 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3605                                          Type *Ty) {
3606   Type *SrcTy = V->getType();
3607   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3608          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3609          "Cannot truncate or zero extend with non-integer arguments!");
3610   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3611     return V;  // No conversion
3612   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3613     return getTruncateExpr(V, Ty);
3614   return getSignExtendExpr(V, Ty);
3615 }
3616 
3617 const SCEV *
3618 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3619   Type *SrcTy = V->getType();
3620   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3621          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3622          "Cannot noop or zero extend with non-integer arguments!");
3623   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3624          "getNoopOrZeroExtend cannot truncate!");
3625   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3626     return V;  // No conversion
3627   return getZeroExtendExpr(V, Ty);
3628 }
3629 
3630 const SCEV *
3631 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3632   Type *SrcTy = V->getType();
3633   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3634          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3635          "Cannot noop or sign extend with non-integer arguments!");
3636   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3637          "getNoopOrSignExtend cannot truncate!");
3638   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3639     return V;  // No conversion
3640   return getSignExtendExpr(V, Ty);
3641 }
3642 
3643 const SCEV *
3644 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3645   Type *SrcTy = V->getType();
3646   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3647          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3648          "Cannot noop or any extend with non-integer arguments!");
3649   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3650          "getNoopOrAnyExtend cannot truncate!");
3651   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3652     return V;  // No conversion
3653   return getAnyExtendExpr(V, Ty);
3654 }
3655 
3656 const SCEV *
3657 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3658   Type *SrcTy = V->getType();
3659   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3660          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3661          "Cannot truncate or noop with non-integer arguments!");
3662   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3663          "getTruncateOrNoop cannot extend!");
3664   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3665     return V;  // No conversion
3666   return getTruncateExpr(V, Ty);
3667 }
3668 
3669 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3670                                                         const SCEV *RHS) {
3671   const SCEV *PromotedLHS = LHS;
3672   const SCEV *PromotedRHS = RHS;
3673 
3674   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3675     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3676   else
3677     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3678 
3679   return getUMaxExpr(PromotedLHS, PromotedRHS);
3680 }
3681 
3682 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3683                                                         const SCEV *RHS) {
3684   const SCEV *PromotedLHS = LHS;
3685   const SCEV *PromotedRHS = RHS;
3686 
3687   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3688     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3689   else
3690     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3691 
3692   return getUMinExpr(PromotedLHS, PromotedRHS);
3693 }
3694 
3695 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3696   // A pointer operand may evaluate to a nonpointer expression, such as null.
3697   if (!V->getType()->isPointerTy())
3698     return V;
3699 
3700   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3701     return getPointerBase(Cast->getOperand());
3702   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3703     const SCEV *PtrOp = nullptr;
3704     for (const SCEV *NAryOp : NAry->operands()) {
3705       if (NAryOp->getType()->isPointerTy()) {
3706         // Cannot find the base of an expression with multiple pointer operands.
3707         if (PtrOp)
3708           return V;
3709         PtrOp = NAryOp;
3710       }
3711     }
3712     if (!PtrOp)
3713       return V;
3714     return getPointerBase(PtrOp);
3715   }
3716   return V;
3717 }
3718 
3719 /// Push users of the given Instruction onto the given Worklist.
3720 static void
3721 PushDefUseChildren(Instruction *I,
3722                    SmallVectorImpl<Instruction *> &Worklist) {
3723   // Push the def-use children onto the Worklist stack.
3724   for (User *U : I->users())
3725     Worklist.push_back(cast<Instruction>(U));
3726 }
3727 
3728 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3729   SmallVector<Instruction *, 16> Worklist;
3730   PushDefUseChildren(PN, Worklist);
3731 
3732   SmallPtrSet<Instruction *, 8> Visited;
3733   Visited.insert(PN);
3734   while (!Worklist.empty()) {
3735     Instruction *I = Worklist.pop_back_val();
3736     if (!Visited.insert(I).second)
3737       continue;
3738 
3739     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3740     if (It != ValueExprMap.end()) {
3741       const SCEV *Old = It->second;
3742 
3743       // Short-circuit the def-use traversal if the symbolic name
3744       // ceases to appear in expressions.
3745       if (Old != SymName && !hasOperand(Old, SymName))
3746         continue;
3747 
3748       // SCEVUnknown for a PHI either means that it has an unrecognized
3749       // structure, it's a PHI that's in the progress of being computed
3750       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3751       // additional loop trip count information isn't going to change anything.
3752       // In the second case, createNodeForPHI will perform the necessary
3753       // updates on its own when it gets to that point. In the third, we do
3754       // want to forget the SCEVUnknown.
3755       if (!isa<PHINode>(I) ||
3756           !isa<SCEVUnknown>(Old) ||
3757           (I != PN && Old == SymName)) {
3758         eraseValueFromMap(It->first);
3759         forgetMemoizedResults(Old);
3760       }
3761     }
3762 
3763     PushDefUseChildren(I, Worklist);
3764   }
3765 }
3766 
3767 namespace {
3768 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3769 public:
3770   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3771                              ScalarEvolution &SE) {
3772     SCEVInitRewriter Rewriter(L, SE);
3773     const SCEV *Result = Rewriter.visit(S);
3774     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3775   }
3776 
3777   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3778       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3779 
3780   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3781     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3782       Valid = false;
3783     return Expr;
3784   }
3785 
3786   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3787     // Only allow AddRecExprs for this loop.
3788     if (Expr->getLoop() == L)
3789       return Expr->getStart();
3790     Valid = false;
3791     return Expr;
3792   }
3793 
3794   bool isValid() { return Valid; }
3795 
3796 private:
3797   const Loop *L;
3798   bool Valid;
3799 };
3800 
3801 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3802 public:
3803   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3804                              ScalarEvolution &SE) {
3805     SCEVShiftRewriter Rewriter(L, SE);
3806     const SCEV *Result = Rewriter.visit(S);
3807     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3808   }
3809 
3810   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3811       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3812 
3813   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3814     // Only allow AddRecExprs for this loop.
3815     if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3816       Valid = false;
3817     return Expr;
3818   }
3819 
3820   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3821     if (Expr->getLoop() == L && Expr->isAffine())
3822       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3823     Valid = false;
3824     return Expr;
3825   }
3826   bool isValid() { return Valid; }
3827 
3828 private:
3829   const Loop *L;
3830   bool Valid;
3831 };
3832 } // end anonymous namespace
3833 
3834 SCEV::NoWrapFlags
3835 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3836   if (!AR->isAffine())
3837     return SCEV::FlagAnyWrap;
3838 
3839   typedef OverflowingBinaryOperator OBO;
3840   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3841 
3842   if (!AR->hasNoSignedWrap()) {
3843     ConstantRange AddRecRange = getSignedRange(AR);
3844     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3845 
3846     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3847         Instruction::Add, IncRange, OBO::NoSignedWrap);
3848     if (NSWRegion.contains(AddRecRange))
3849       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3850   }
3851 
3852   if (!AR->hasNoUnsignedWrap()) {
3853     ConstantRange AddRecRange = getUnsignedRange(AR);
3854     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3855 
3856     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3857         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3858     if (NUWRegion.contains(AddRecRange))
3859       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3860   }
3861 
3862   return Result;
3863 }
3864 
3865 namespace {
3866 /// Represents an abstract binary operation.  This may exist as a
3867 /// normal instruction or constant expression, or may have been
3868 /// derived from an expression tree.
3869 struct BinaryOp {
3870   unsigned Opcode;
3871   Value *LHS;
3872   Value *RHS;
3873   bool IsNSW;
3874   bool IsNUW;
3875 
3876   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3877   /// constant expression.
3878   Operator *Op;
3879 
3880   explicit BinaryOp(Operator *Op)
3881       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
3882         IsNSW(false), IsNUW(false), Op(Op) {
3883     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3884       IsNSW = OBO->hasNoSignedWrap();
3885       IsNUW = OBO->hasNoUnsignedWrap();
3886     }
3887   }
3888 
3889   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3890                     bool IsNUW = false)
3891       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3892         Op(nullptr) {}
3893 };
3894 }
3895 
3896 
3897 /// Try to map \p V into a BinaryOp, and return \c None on failure.
3898 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
3899   auto *Op = dyn_cast<Operator>(V);
3900   if (!Op)
3901     return None;
3902 
3903   // Implementation detail: all the cleverness here should happen without
3904   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3905   // SCEV expressions when possible, and we should not break that.
3906 
3907   switch (Op->getOpcode()) {
3908   case Instruction::Add:
3909   case Instruction::Sub:
3910   case Instruction::Mul:
3911   case Instruction::UDiv:
3912   case Instruction::And:
3913   case Instruction::Or:
3914   case Instruction::AShr:
3915   case Instruction::Shl:
3916     return BinaryOp(Op);
3917 
3918   case Instruction::Xor:
3919     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3920       // If the RHS of the xor is a signbit, then this is just an add.
3921       // Instcombine turns add of signbit into xor as a strength reduction step.
3922       if (RHSC->getValue().isSignBit())
3923         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3924     return BinaryOp(Op);
3925 
3926   case Instruction::LShr:
3927     // Turn logical shift right of a constant into a unsigned divide.
3928     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3929       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3930 
3931       // If the shift count is not less than the bitwidth, the result of
3932       // the shift is undefined. Don't try to analyze it, because the
3933       // resolution chosen here may differ from the resolution chosen in
3934       // other parts of the compiler.
3935       if (SA->getValue().ult(BitWidth)) {
3936         Constant *X =
3937             ConstantInt::get(SA->getContext(),
3938                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3939         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3940       }
3941     }
3942     return BinaryOp(Op);
3943 
3944   case Instruction::ExtractValue: {
3945     auto *EVI = cast<ExtractValueInst>(Op);
3946     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3947       break;
3948 
3949     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3950     if (!CI)
3951       break;
3952 
3953     if (auto *F = CI->getCalledFunction())
3954       switch (F->getIntrinsicID()) {
3955       case Intrinsic::sadd_with_overflow:
3956       case Intrinsic::uadd_with_overflow: {
3957         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3958           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3959                           CI->getArgOperand(1));
3960 
3961         // Now that we know that all uses of the arithmetic-result component of
3962         // CI are guarded by the overflow check, we can go ahead and pretend
3963         // that the arithmetic is non-overflowing.
3964         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3965           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3966                           CI->getArgOperand(1), /* IsNSW = */ true,
3967                           /* IsNUW = */ false);
3968         else
3969           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3970                           CI->getArgOperand(1), /* IsNSW = */ false,
3971                           /* IsNUW*/ true);
3972       }
3973 
3974       case Intrinsic::ssub_with_overflow:
3975       case Intrinsic::usub_with_overflow:
3976         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3977                         CI->getArgOperand(1));
3978 
3979       case Intrinsic::smul_with_overflow:
3980       case Intrinsic::umul_with_overflow:
3981         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3982                         CI->getArgOperand(1));
3983       default:
3984         break;
3985       }
3986   }
3987 
3988   default:
3989     break;
3990   }
3991 
3992   return None;
3993 }
3994 
3995 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3996   const Loop *L = LI.getLoopFor(PN->getParent());
3997   if (!L || L->getHeader() != PN->getParent())
3998     return nullptr;
3999 
4000   // The loop may have multiple entrances or multiple exits; we can analyze
4001   // this phi as an addrec if it has a unique entry value and a unique
4002   // backedge value.
4003   Value *BEValueV = nullptr, *StartValueV = nullptr;
4004   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4005     Value *V = PN->getIncomingValue(i);
4006     if (L->contains(PN->getIncomingBlock(i))) {
4007       if (!BEValueV) {
4008         BEValueV = V;
4009       } else if (BEValueV != V) {
4010         BEValueV = nullptr;
4011         break;
4012       }
4013     } else if (!StartValueV) {
4014       StartValueV = V;
4015     } else if (StartValueV != V) {
4016       StartValueV = nullptr;
4017       break;
4018     }
4019   }
4020   if (BEValueV && StartValueV) {
4021     // While we are analyzing this PHI node, handle its value symbolically.
4022     const SCEV *SymbolicName = getUnknown(PN);
4023     assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4024            "PHI node already processed?");
4025     ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4026 
4027     // Using this symbolic name for the PHI, analyze the value coming around
4028     // the back-edge.
4029     const SCEV *BEValue = getSCEV(BEValueV);
4030 
4031     // NOTE: If BEValue is loop invariant, we know that the PHI node just
4032     // has a special value for the first iteration of the loop.
4033 
4034     // If the value coming around the backedge is an add with the symbolic
4035     // value we just inserted, then we found a simple induction variable!
4036     if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4037       // If there is a single occurrence of the symbolic value, replace it
4038       // with a recurrence.
4039       unsigned FoundIndex = Add->getNumOperands();
4040       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4041         if (Add->getOperand(i) == SymbolicName)
4042           if (FoundIndex == e) {
4043             FoundIndex = i;
4044             break;
4045           }
4046 
4047       if (FoundIndex != Add->getNumOperands()) {
4048         // Create an add with everything but the specified operand.
4049         SmallVector<const SCEV *, 8> Ops;
4050         for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4051           if (i != FoundIndex)
4052             Ops.push_back(Add->getOperand(i));
4053         const SCEV *Accum = getAddExpr(Ops);
4054 
4055         // This is not a valid addrec if the step amount is varying each
4056         // loop iteration, but is not itself an addrec in this loop.
4057         if (isLoopInvariant(Accum, L) ||
4058             (isa<SCEVAddRecExpr>(Accum) &&
4059              cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4060           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4061 
4062           if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4063             if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4064               if (BO->IsNUW)
4065                 Flags = setFlags(Flags, SCEV::FlagNUW);
4066               if (BO->IsNSW)
4067                 Flags = setFlags(Flags, SCEV::FlagNSW);
4068             }
4069           } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4070             // If the increment is an inbounds GEP, then we know the address
4071             // space cannot be wrapped around. We cannot make any guarantee
4072             // about signed or unsigned overflow because pointers are
4073             // unsigned but we may have a negative index from the base
4074             // pointer. We can guarantee that no unsigned wrap occurs if the
4075             // indices form a positive value.
4076             if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4077               Flags = setFlags(Flags, SCEV::FlagNW);
4078 
4079               const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4080               if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4081                 Flags = setFlags(Flags, SCEV::FlagNUW);
4082             }
4083 
4084             // We cannot transfer nuw and nsw flags from subtraction
4085             // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4086             // for instance.
4087           }
4088 
4089           const SCEV *StartVal = getSCEV(StartValueV);
4090           const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4091 
4092           // Okay, for the entire analysis of this edge we assumed the PHI
4093           // to be symbolic.  We now need to go back and purge all of the
4094           // entries for the scalars that use the symbolic expression.
4095           forgetSymbolicName(PN, SymbolicName);
4096           ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4097 
4098           // We can add Flags to the post-inc expression only if we
4099           // know that it us *undefined behavior* for BEValueV to
4100           // overflow.
4101           if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4102             if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4103               (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4104 
4105           return PHISCEV;
4106         }
4107       }
4108     } else {
4109       // Otherwise, this could be a loop like this:
4110       //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4111       // In this case, j = {1,+,1}  and BEValue is j.
4112       // Because the other in-value of i (0) fits the evolution of BEValue
4113       // i really is an addrec evolution.
4114       //
4115       // We can generalize this saying that i is the shifted value of BEValue
4116       // by one iteration:
4117       //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4118       const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4119       const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4120       if (Shifted != getCouldNotCompute() &&
4121           Start != getCouldNotCompute()) {
4122         const SCEV *StartVal = getSCEV(StartValueV);
4123         if (Start == StartVal) {
4124           // Okay, for the entire analysis of this edge we assumed the PHI
4125           // to be symbolic.  We now need to go back and purge all of the
4126           // entries for the scalars that use the symbolic expression.
4127           forgetSymbolicName(PN, SymbolicName);
4128           ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4129           return Shifted;
4130         }
4131       }
4132     }
4133 
4134     // Remove the temporary PHI node SCEV that has been inserted while intending
4135     // to create an AddRecExpr for this PHI node. We can not keep this temporary
4136     // as it will prevent later (possibly simpler) SCEV expressions to be added
4137     // to the ValueExprMap.
4138     eraseValueFromMap(PN);
4139   }
4140 
4141   return nullptr;
4142 }
4143 
4144 // Checks if the SCEV S is available at BB.  S is considered available at BB
4145 // if S can be materialized at BB without introducing a fault.
4146 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4147                                BasicBlock *BB) {
4148   struct CheckAvailable {
4149     bool TraversalDone = false;
4150     bool Available = true;
4151 
4152     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4153     BasicBlock *BB = nullptr;
4154     DominatorTree &DT;
4155 
4156     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4157       : L(L), BB(BB), DT(DT) {}
4158 
4159     bool setUnavailable() {
4160       TraversalDone = true;
4161       Available = false;
4162       return false;
4163     }
4164 
4165     bool follow(const SCEV *S) {
4166       switch (S->getSCEVType()) {
4167       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4168       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4169         // These expressions are available if their operand(s) is/are.
4170         return true;
4171 
4172       case scAddRecExpr: {
4173         // We allow add recurrences that are on the loop BB is in, or some
4174         // outer loop.  This guarantees availability because the value of the
4175         // add recurrence at BB is simply the "current" value of the induction
4176         // variable.  We can relax this in the future; for instance an add
4177         // recurrence on a sibling dominating loop is also available at BB.
4178         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4179         if (L && (ARLoop == L || ARLoop->contains(L)))
4180           return true;
4181 
4182         return setUnavailable();
4183       }
4184 
4185       case scUnknown: {
4186         // For SCEVUnknown, we check for simple dominance.
4187         const auto *SU = cast<SCEVUnknown>(S);
4188         Value *V = SU->getValue();
4189 
4190         if (isa<Argument>(V))
4191           return false;
4192 
4193         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4194           return false;
4195 
4196         return setUnavailable();
4197       }
4198 
4199       case scUDivExpr:
4200       case scCouldNotCompute:
4201         // We do not try to smart about these at all.
4202         return setUnavailable();
4203       }
4204       llvm_unreachable("switch should be fully covered!");
4205     }
4206 
4207     bool isDone() { return TraversalDone; }
4208   };
4209 
4210   CheckAvailable CA(L, BB, DT);
4211   SCEVTraversal<CheckAvailable> ST(CA);
4212 
4213   ST.visitAll(S);
4214   return CA.Available;
4215 }
4216 
4217 // Try to match a control flow sequence that branches out at BI and merges back
4218 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4219 // match.
4220 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4221                           Value *&C, Value *&LHS, Value *&RHS) {
4222   C = BI->getCondition();
4223 
4224   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4225   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4226 
4227   if (!LeftEdge.isSingleEdge())
4228     return false;
4229 
4230   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4231 
4232   Use &LeftUse = Merge->getOperandUse(0);
4233   Use &RightUse = Merge->getOperandUse(1);
4234 
4235   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4236     LHS = LeftUse;
4237     RHS = RightUse;
4238     return true;
4239   }
4240 
4241   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4242     LHS = RightUse;
4243     RHS = LeftUse;
4244     return true;
4245   }
4246 
4247   return false;
4248 }
4249 
4250 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4251   auto IsReachable =
4252       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4253   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4254     const Loop *L = LI.getLoopFor(PN->getParent());
4255 
4256     // We don't want to break LCSSA, even in a SCEV expression tree.
4257     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4258       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4259         return nullptr;
4260 
4261     // Try to match
4262     //
4263     //  br %cond, label %left, label %right
4264     // left:
4265     //  br label %merge
4266     // right:
4267     //  br label %merge
4268     // merge:
4269     //  V = phi [ %x, %left ], [ %y, %right ]
4270     //
4271     // as "select %cond, %x, %y"
4272 
4273     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4274     assert(IDom && "At least the entry block should dominate PN");
4275 
4276     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4277     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4278 
4279     if (BI && BI->isConditional() &&
4280         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4281         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4282         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4283       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4284   }
4285 
4286   return nullptr;
4287 }
4288 
4289 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4290   if (const SCEV *S = createAddRecFromPHI(PN))
4291     return S;
4292 
4293   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4294     return S;
4295 
4296   // If the PHI has a single incoming value, follow that value, unless the
4297   // PHI's incoming blocks are in a different loop, in which case doing so
4298   // risks breaking LCSSA form. Instcombine would normally zap these, but
4299   // it doesn't have DominatorTree information, so it may miss cases.
4300   if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
4301     if (LI.replacementPreservesLCSSAForm(PN, V))
4302       return getSCEV(V);
4303 
4304   // If it's not a loop phi, we can't handle it yet.
4305   return getUnknown(PN);
4306 }
4307 
4308 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4309                                                       Value *Cond,
4310                                                       Value *TrueVal,
4311                                                       Value *FalseVal) {
4312   // Handle "constant" branch or select. This can occur for instance when a
4313   // loop pass transforms an inner loop and moves on to process the outer loop.
4314   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4315     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4316 
4317   // Try to match some simple smax or umax patterns.
4318   auto *ICI = dyn_cast<ICmpInst>(Cond);
4319   if (!ICI)
4320     return getUnknown(I);
4321 
4322   Value *LHS = ICI->getOperand(0);
4323   Value *RHS = ICI->getOperand(1);
4324 
4325   switch (ICI->getPredicate()) {
4326   case ICmpInst::ICMP_SLT:
4327   case ICmpInst::ICMP_SLE:
4328     std::swap(LHS, RHS);
4329     LLVM_FALLTHROUGH;
4330   case ICmpInst::ICMP_SGT:
4331   case ICmpInst::ICMP_SGE:
4332     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4333     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4334     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4335       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4336       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4337       const SCEV *LA = getSCEV(TrueVal);
4338       const SCEV *RA = getSCEV(FalseVal);
4339       const SCEV *LDiff = getMinusSCEV(LA, LS);
4340       const SCEV *RDiff = getMinusSCEV(RA, RS);
4341       if (LDiff == RDiff)
4342         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4343       LDiff = getMinusSCEV(LA, RS);
4344       RDiff = getMinusSCEV(RA, LS);
4345       if (LDiff == RDiff)
4346         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4347     }
4348     break;
4349   case ICmpInst::ICMP_ULT:
4350   case ICmpInst::ICMP_ULE:
4351     std::swap(LHS, RHS);
4352     LLVM_FALLTHROUGH;
4353   case ICmpInst::ICMP_UGT:
4354   case ICmpInst::ICMP_UGE:
4355     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4356     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4357     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4358       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4359       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4360       const SCEV *LA = getSCEV(TrueVal);
4361       const SCEV *RA = getSCEV(FalseVal);
4362       const SCEV *LDiff = getMinusSCEV(LA, LS);
4363       const SCEV *RDiff = getMinusSCEV(RA, RS);
4364       if (LDiff == RDiff)
4365         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4366       LDiff = getMinusSCEV(LA, RS);
4367       RDiff = getMinusSCEV(RA, LS);
4368       if (LDiff == RDiff)
4369         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4370     }
4371     break;
4372   case ICmpInst::ICMP_NE:
4373     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4374     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4375         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4376       const SCEV *One = getOne(I->getType());
4377       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4378       const SCEV *LA = getSCEV(TrueVal);
4379       const SCEV *RA = getSCEV(FalseVal);
4380       const SCEV *LDiff = getMinusSCEV(LA, LS);
4381       const SCEV *RDiff = getMinusSCEV(RA, One);
4382       if (LDiff == RDiff)
4383         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4384     }
4385     break;
4386   case ICmpInst::ICMP_EQ:
4387     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4388     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4389         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4390       const SCEV *One = getOne(I->getType());
4391       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4392       const SCEV *LA = getSCEV(TrueVal);
4393       const SCEV *RA = getSCEV(FalseVal);
4394       const SCEV *LDiff = getMinusSCEV(LA, One);
4395       const SCEV *RDiff = getMinusSCEV(RA, LS);
4396       if (LDiff == RDiff)
4397         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4398     }
4399     break;
4400   default:
4401     break;
4402   }
4403 
4404   return getUnknown(I);
4405 }
4406 
4407 /// Expand GEP instructions into add and multiply operations. This allows them
4408 /// to be analyzed by regular SCEV code.
4409 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4410   // Don't attempt to analyze GEPs over unsized objects.
4411   if (!GEP->getSourceElementType()->isSized())
4412     return getUnknown(GEP);
4413 
4414   SmallVector<const SCEV *, 4> IndexExprs;
4415   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4416     IndexExprs.push_back(getSCEV(*Index));
4417   return getGEPExpr(GEP, IndexExprs);
4418 }
4419 
4420 uint32_t
4421 ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
4422   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4423     return C->getAPInt().countTrailingZeros();
4424 
4425   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4426     return std::min(GetMinTrailingZeros(T->getOperand()),
4427                     (uint32_t)getTypeSizeInBits(T->getType()));
4428 
4429   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4430     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4431     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4432              getTypeSizeInBits(E->getType()) : OpRes;
4433   }
4434 
4435   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
4436     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4437     return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4438              getTypeSizeInBits(E->getType()) : OpRes;
4439   }
4440 
4441   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
4442     // The result is the min of all operands results.
4443     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4444     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4445       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4446     return MinOpRes;
4447   }
4448 
4449   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
4450     // The result is the sum of all operands results.
4451     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4452     uint32_t BitWidth = getTypeSizeInBits(M->getType());
4453     for (unsigned i = 1, e = M->getNumOperands();
4454          SumOpRes != BitWidth && i != e; ++i)
4455       SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
4456                           BitWidth);
4457     return SumOpRes;
4458   }
4459 
4460   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
4461     // The result is the min of all operands results.
4462     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
4463     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
4464       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
4465     return MinOpRes;
4466   }
4467 
4468   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
4469     // The result is the min of all operands results.
4470     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4471     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4472       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4473     return MinOpRes;
4474   }
4475 
4476   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
4477     // The result is the min of all operands results.
4478     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
4479     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
4480       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
4481     return MinOpRes;
4482   }
4483 
4484   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4485     // For a SCEVUnknown, ask ValueTracking.
4486     unsigned BitWidth = getTypeSizeInBits(U->getType());
4487     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4488     computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4489                      nullptr, &DT);
4490     return Zeros.countTrailingOnes();
4491   }
4492 
4493   // SCEVUDivExpr
4494   return 0;
4495 }
4496 
4497 /// Helper method to assign a range to V from metadata present in the IR.
4498 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
4499   if (Instruction *I = dyn_cast<Instruction>(V))
4500     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4501       return getConstantRangeFromMetadata(*MD);
4502 
4503   return None;
4504 }
4505 
4506 /// Determine the range for a particular SCEV.  If SignHint is
4507 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4508 /// with a "cleaner" unsigned (resp. signed) representation.
4509 ConstantRange
4510 ScalarEvolution::getRange(const SCEV *S,
4511                           ScalarEvolution::RangeSignHint SignHint) {
4512   DenseMap<const SCEV *, ConstantRange> &Cache =
4513       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4514                                                        : SignedRanges;
4515 
4516   // See if we've computed this range already.
4517   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4518   if (I != Cache.end())
4519     return I->second;
4520 
4521   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4522     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
4523 
4524   unsigned BitWidth = getTypeSizeInBits(S->getType());
4525   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4526 
4527   // If the value has known zeros, the maximum value will have those known zeros
4528   // as well.
4529   uint32_t TZ = GetMinTrailingZeros(S);
4530   if (TZ != 0) {
4531     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4532       ConservativeResult =
4533           ConstantRange(APInt::getMinValue(BitWidth),
4534                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4535     else
4536       ConservativeResult = ConstantRange(
4537           APInt::getSignedMinValue(BitWidth),
4538           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4539   }
4540 
4541   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
4542     ConstantRange X = getRange(Add->getOperand(0), SignHint);
4543     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
4544       X = X.add(getRange(Add->getOperand(i), SignHint));
4545     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
4546   }
4547 
4548   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
4549     ConstantRange X = getRange(Mul->getOperand(0), SignHint);
4550     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
4551       X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4552     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
4553   }
4554 
4555   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
4556     ConstantRange X = getRange(SMax->getOperand(0), SignHint);
4557     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
4558       X = X.smax(getRange(SMax->getOperand(i), SignHint));
4559     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
4560   }
4561 
4562   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
4563     ConstantRange X = getRange(UMax->getOperand(0), SignHint);
4564     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
4565       X = X.umax(getRange(UMax->getOperand(i), SignHint));
4566     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
4567   }
4568 
4569   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
4570     ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4571     ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4572     return setRange(UDiv, SignHint,
4573                     ConservativeResult.intersectWith(X.udiv(Y)));
4574   }
4575 
4576   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
4577     ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4578     return setRange(ZExt, SignHint,
4579                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
4580   }
4581 
4582   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
4583     ConstantRange X = getRange(SExt->getOperand(), SignHint);
4584     return setRange(SExt, SignHint,
4585                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
4586   }
4587 
4588   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
4589     ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4590     return setRange(Trunc, SignHint,
4591                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
4592   }
4593 
4594   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
4595     // If there's no unsigned wrap, the value will never be less than its
4596     // initial value.
4597     if (AddRec->hasNoUnsignedWrap())
4598       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
4599         if (!C->getValue()->isZero())
4600           ConservativeResult = ConservativeResult.intersectWith(
4601               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
4602 
4603     // If there's no signed wrap, and all the operands have the same sign or
4604     // zero, the value won't ever change sign.
4605     if (AddRec->hasNoSignedWrap()) {
4606       bool AllNonNeg = true;
4607       bool AllNonPos = true;
4608       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4609         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4610         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4611       }
4612       if (AllNonNeg)
4613         ConservativeResult = ConservativeResult.intersectWith(
4614           ConstantRange(APInt(BitWidth, 0),
4615                         APInt::getSignedMinValue(BitWidth)));
4616       else if (AllNonPos)
4617         ConservativeResult = ConservativeResult.intersectWith(
4618           ConstantRange(APInt::getSignedMinValue(BitWidth),
4619                         APInt(BitWidth, 1)));
4620     }
4621 
4622     // TODO: non-affine addrec
4623     if (AddRec->isAffine()) {
4624       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
4625       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4626           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
4627         auto RangeFromAffine = getRangeForAffineAR(
4628             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4629             BitWidth);
4630         if (!RangeFromAffine.isFullSet())
4631           ConservativeResult =
4632               ConservativeResult.intersectWith(RangeFromAffine);
4633 
4634         auto RangeFromFactoring = getRangeViaFactoring(
4635             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4636             BitWidth);
4637         if (!RangeFromFactoring.isFullSet())
4638           ConservativeResult =
4639               ConservativeResult.intersectWith(RangeFromFactoring);
4640       }
4641     }
4642 
4643     return setRange(AddRec, SignHint, ConservativeResult);
4644   }
4645 
4646   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4647     // Check if the IR explicitly contains !range metadata.
4648     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4649     if (MDRange.hasValue())
4650       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4651 
4652     // Split here to avoid paying the compile-time cost of calling both
4653     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
4654     // if needed.
4655     const DataLayout &DL = getDataLayout();
4656     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4657       // For a SCEVUnknown, ask ValueTracking.
4658       APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
4659       computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
4660       if (Ones != ~Zeros + 1)
4661         ConservativeResult =
4662             ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4663     } else {
4664       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4665              "generalize as needed!");
4666       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
4667       if (NS > 1)
4668         ConservativeResult = ConservativeResult.intersectWith(
4669             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4670                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
4671     }
4672 
4673     return setRange(U, SignHint, ConservativeResult);
4674   }
4675 
4676   return setRange(S, SignHint, ConservativeResult);
4677 }
4678 
4679 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4680                                                    const SCEV *Step,
4681                                                    const SCEV *MaxBECount,
4682                                                    unsigned BitWidth) {
4683   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4684          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4685          "Precondition!");
4686 
4687   ConstantRange Result(BitWidth, /* isFullSet = */ true);
4688 
4689   // Check for overflow.  This must be done with ConstantRange arithmetic
4690   // because we could be called from within the ScalarEvolution overflow
4691   // checking code.
4692 
4693   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4694   ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4695   ConstantRange ZExtMaxBECountRange = MaxBECountRange.zextOrTrunc(BitWidth * 2);
4696 
4697   ConstantRange StepSRange = getSignedRange(Step);
4698   ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2);
4699 
4700   ConstantRange StartURange = getUnsignedRange(Start);
4701   ConstantRange EndURange =
4702       StartURange.add(MaxBECountRange.multiply(StepSRange));
4703 
4704   // Check for unsigned overflow.
4705   ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2);
4706   ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2);
4707   if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4708       ZExtEndURange) {
4709     APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4710                                EndURange.getUnsignedMin());
4711     APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4712                                EndURange.getUnsignedMax());
4713     bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4714     if (!IsFullRange)
4715       Result =
4716           Result.intersectWith(ConstantRange(Min, Max + 1));
4717   }
4718 
4719   ConstantRange StartSRange = getSignedRange(Start);
4720   ConstantRange EndSRange =
4721       StartSRange.add(MaxBECountRange.multiply(StepSRange));
4722 
4723   // Check for signed overflow. This must be done with ConstantRange
4724   // arithmetic because we could be called from within the ScalarEvolution
4725   // overflow checking code.
4726   ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2);
4727   ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2);
4728   if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4729       SExtEndSRange) {
4730     APInt Min =
4731         APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4732     APInt Max =
4733         APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4734     bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4735     if (!IsFullRange)
4736       Result =
4737           Result.intersectWith(ConstantRange(Min, Max + 1));
4738   }
4739 
4740   return Result;
4741 }
4742 
4743 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4744                                                     const SCEV *Step,
4745                                                     const SCEV *MaxBECount,
4746                                                     unsigned BitWidth) {
4747   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4748   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4749 
4750   struct SelectPattern {
4751     Value *Condition = nullptr;
4752     APInt TrueValue;
4753     APInt FalseValue;
4754 
4755     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4756                            const SCEV *S) {
4757       Optional<unsigned> CastOp;
4758       APInt Offset(BitWidth, 0);
4759 
4760       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4761              "Should be!");
4762 
4763       // Peel off a constant offset:
4764       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4765         // In the future we could consider being smarter here and handle
4766         // {Start+Step,+,Step} too.
4767         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4768           return;
4769 
4770         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4771         S = SA->getOperand(1);
4772       }
4773 
4774       // Peel off a cast operation
4775       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4776         CastOp = SCast->getSCEVType();
4777         S = SCast->getOperand();
4778       }
4779 
4780       using namespace llvm::PatternMatch;
4781 
4782       auto *SU = dyn_cast<SCEVUnknown>(S);
4783       const APInt *TrueVal, *FalseVal;
4784       if (!SU ||
4785           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4786                                           m_APInt(FalseVal)))) {
4787         Condition = nullptr;
4788         return;
4789       }
4790 
4791       TrueValue = *TrueVal;
4792       FalseValue = *FalseVal;
4793 
4794       // Re-apply the cast we peeled off earlier
4795       if (CastOp.hasValue())
4796         switch (*CastOp) {
4797         default:
4798           llvm_unreachable("Unknown SCEV cast type!");
4799 
4800         case scTruncate:
4801           TrueValue = TrueValue.trunc(BitWidth);
4802           FalseValue = FalseValue.trunc(BitWidth);
4803           break;
4804         case scZeroExtend:
4805           TrueValue = TrueValue.zext(BitWidth);
4806           FalseValue = FalseValue.zext(BitWidth);
4807           break;
4808         case scSignExtend:
4809           TrueValue = TrueValue.sext(BitWidth);
4810           FalseValue = FalseValue.sext(BitWidth);
4811           break;
4812         }
4813 
4814       // Re-apply the constant offset we peeled off earlier
4815       TrueValue += Offset;
4816       FalseValue += Offset;
4817     }
4818 
4819     bool isRecognized() { return Condition != nullptr; }
4820   };
4821 
4822   SelectPattern StartPattern(*this, BitWidth, Start);
4823   if (!StartPattern.isRecognized())
4824     return ConstantRange(BitWidth, /* isFullSet = */ true);
4825 
4826   SelectPattern StepPattern(*this, BitWidth, Step);
4827   if (!StepPattern.isRecognized())
4828     return ConstantRange(BitWidth, /* isFullSet = */ true);
4829 
4830   if (StartPattern.Condition != StepPattern.Condition) {
4831     // We don't handle this case today; but we could, by considering four
4832     // possibilities below instead of two. I'm not sure if there are cases where
4833     // that will help over what getRange already does, though.
4834     return ConstantRange(BitWidth, /* isFullSet = */ true);
4835   }
4836 
4837   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4838   // construct arbitrary general SCEV expressions here.  This function is called
4839   // from deep in the call stack, and calling getSCEV (on a sext instruction,
4840   // say) can end up caching a suboptimal value.
4841 
4842   // FIXME: without the explicit `this` receiver below, MSVC errors out with
4843   // C2352 and C2512 (otherwise it isn't needed).
4844 
4845   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
4846   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
4847   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
4848   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
4849 
4850   ConstantRange TrueRange =
4851       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
4852   ConstantRange FalseRange =
4853       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
4854 
4855   return TrueRange.unionWith(FalseRange);
4856 }
4857 
4858 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
4859   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
4860   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4861 
4862   // Return early if there are no flags to propagate to the SCEV.
4863   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4864   if (BinOp->hasNoUnsignedWrap())
4865     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4866   if (BinOp->hasNoSignedWrap())
4867     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
4868   if (Flags == SCEV::FlagAnyWrap)
4869     return SCEV::FlagAnyWrap;
4870 
4871   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
4872 }
4873 
4874 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
4875   // Here we check that I is in the header of the innermost loop containing I,
4876   // since we only deal with instructions in the loop header. The actual loop we
4877   // need to check later will come from an add recurrence, but getting that
4878   // requires computing the SCEV of the operands, which can be expensive. This
4879   // check we can do cheaply to rule out some cases early.
4880   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
4881   if (InnermostContainingLoop == nullptr ||
4882       InnermostContainingLoop->getHeader() != I->getParent())
4883     return false;
4884 
4885   // Only proceed if we can prove that I does not yield poison.
4886   if (!isKnownNotFullPoison(I)) return false;
4887 
4888   // At this point we know that if I is executed, then it does not wrap
4889   // according to at least one of NSW or NUW. If I is not executed, then we do
4890   // not know if the calculation that I represents would wrap. Multiple
4891   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
4892   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4893   // derived from other instructions that map to the same SCEV. We cannot make
4894   // that guarantee for cases where I is not executed. So we need to find the
4895   // loop that I is considered in relation to and prove that I is executed for
4896   // every iteration of that loop. That implies that the value that I
4897   // calculates does not wrap anywhere in the loop, so then we can apply the
4898   // flags to the SCEV.
4899   //
4900   // We check isLoopInvariant to disambiguate in case we are adding recurrences
4901   // from different loops, so that we know which loop to prove that I is
4902   // executed in.
4903   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
4904     // I could be an extractvalue from a call to an overflow intrinsic.
4905     // TODO: We can do better here in some cases.
4906     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
4907       return false;
4908     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
4909     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4910       bool AllOtherOpsLoopInvariant = true;
4911       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
4912            ++OtherOpIndex) {
4913         if (OtherOpIndex != OpIndex) {
4914           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
4915           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
4916             AllOtherOpsLoopInvariant = false;
4917             break;
4918           }
4919         }
4920       }
4921       if (AllOtherOpsLoopInvariant &&
4922           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
4923         return true;
4924     }
4925   }
4926   return false;
4927 }
4928 
4929 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
4930   // If we know that \c I can never be poison period, then that's enough.
4931   if (isSCEVExprNeverPoison(I))
4932     return true;
4933 
4934   // For an add recurrence specifically, we assume that infinite loops without
4935   // side effects are undefined behavior, and then reason as follows:
4936   //
4937   // If the add recurrence is poison in any iteration, it is poison on all
4938   // future iterations (since incrementing poison yields poison). If the result
4939   // of the add recurrence is fed into the loop latch condition and the loop
4940   // does not contain any throws or exiting blocks other than the latch, we now
4941   // have the ability to "choose" whether the backedge is taken or not (by
4942   // choosing a sufficiently evil value for the poison feeding into the branch)
4943   // for every iteration including and after the one in which \p I first became
4944   // poison.  There are two possibilities (let's call the iteration in which \p
4945   // I first became poison as K):
4946   //
4947   //  1. In the set of iterations including and after K, the loop body executes
4948   //     no side effects.  In this case executing the backege an infinte number
4949   //     of times will yield undefined behavior.
4950   //
4951   //  2. In the set of iterations including and after K, the loop body executes
4952   //     at least one side effect.  In this case, that specific instance of side
4953   //     effect is control dependent on poison, which also yields undefined
4954   //     behavior.
4955 
4956   auto *ExitingBB = L->getExitingBlock();
4957   auto *LatchBB = L->getLoopLatch();
4958   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
4959     return false;
4960 
4961   SmallPtrSet<const Instruction *, 16> Pushed;
4962   SmallVector<const Instruction *, 8> PoisonStack;
4963 
4964   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
4965   // things that are known to be fully poison under that assumption go on the
4966   // PoisonStack.
4967   Pushed.insert(I);
4968   PoisonStack.push_back(I);
4969 
4970   bool LatchControlDependentOnPoison = false;
4971   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
4972     const Instruction *Poison = PoisonStack.pop_back_val();
4973 
4974     for (auto *PoisonUser : Poison->users()) {
4975       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
4976         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
4977           PoisonStack.push_back(cast<Instruction>(PoisonUser));
4978       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
4979         assert(BI->isConditional() && "Only possibility!");
4980         if (BI->getParent() == LatchBB) {
4981           LatchControlDependentOnPoison = true;
4982           break;
4983         }
4984       }
4985     }
4986   }
4987 
4988   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
4989 }
4990 
4991 ScalarEvolution::LoopProperties
4992 ScalarEvolution::getLoopProperties(const Loop *L) {
4993   typedef ScalarEvolution::LoopProperties LoopProperties;
4994 
4995   auto Itr = LoopPropertiesCache.find(L);
4996   if (Itr == LoopPropertiesCache.end()) {
4997     auto HasSideEffects = [](Instruction *I) {
4998       if (auto *SI = dyn_cast<StoreInst>(I))
4999         return !SI->isSimple();
5000 
5001       return I->mayHaveSideEffects();
5002     };
5003 
5004     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5005                          /*HasNoSideEffects*/ true};
5006 
5007     for (auto *BB : L->getBlocks())
5008       for (auto &I : *BB) {
5009         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5010           LP.HasNoAbnormalExits = false;
5011         if (HasSideEffects(&I))
5012           LP.HasNoSideEffects = false;
5013         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5014           break; // We're already as pessimistic as we can get.
5015       }
5016 
5017     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5018     assert(InsertPair.second && "We just checked!");
5019     Itr = InsertPair.first;
5020   }
5021 
5022   return Itr->second;
5023 }
5024 
5025 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5026   if (!isSCEVable(V->getType()))
5027     return getUnknown(V);
5028 
5029   if (Instruction *I = dyn_cast<Instruction>(V)) {
5030     // Don't attempt to analyze instructions in blocks that aren't
5031     // reachable. Such instructions don't matter, and they aren't required
5032     // to obey basic rules for definitions dominating uses which this
5033     // analysis depends on.
5034     if (!DT.isReachableFromEntry(I->getParent()))
5035       return getUnknown(V);
5036   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5037     return getConstant(CI);
5038   else if (isa<ConstantPointerNull>(V))
5039     return getZero(V->getType());
5040   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5041     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5042   else if (!isa<ConstantExpr>(V))
5043     return getUnknown(V);
5044 
5045   Operator *U = cast<Operator>(V);
5046   if (auto BO = MatchBinaryOp(U, DT)) {
5047     switch (BO->Opcode) {
5048     case Instruction::Add: {
5049       // The simple thing to do would be to just call getSCEV on both operands
5050       // and call getAddExpr with the result. However if we're looking at a
5051       // bunch of things all added together, this can be quite inefficient,
5052       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5053       // Instead, gather up all the operands and make a single getAddExpr call.
5054       // LLVM IR canonical form means we need only traverse the left operands.
5055       SmallVector<const SCEV *, 4> AddOps;
5056       do {
5057         if (BO->Op) {
5058           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5059             AddOps.push_back(OpSCEV);
5060             break;
5061           }
5062 
5063           // If a NUW or NSW flag can be applied to the SCEV for this
5064           // addition, then compute the SCEV for this addition by itself
5065           // with a separate call to getAddExpr. We need to do that
5066           // instead of pushing the operands of the addition onto AddOps,
5067           // since the flags are only known to apply to this particular
5068           // addition - they may not apply to other additions that can be
5069           // formed with operands from AddOps.
5070           const SCEV *RHS = getSCEV(BO->RHS);
5071           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5072           if (Flags != SCEV::FlagAnyWrap) {
5073             const SCEV *LHS = getSCEV(BO->LHS);
5074             if (BO->Opcode == Instruction::Sub)
5075               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5076             else
5077               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5078             break;
5079           }
5080         }
5081 
5082         if (BO->Opcode == Instruction::Sub)
5083           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5084         else
5085           AddOps.push_back(getSCEV(BO->RHS));
5086 
5087         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5088         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5089                        NewBO->Opcode != Instruction::Sub)) {
5090           AddOps.push_back(getSCEV(BO->LHS));
5091           break;
5092         }
5093         BO = NewBO;
5094       } while (true);
5095 
5096       return getAddExpr(AddOps);
5097     }
5098 
5099     case Instruction::Mul: {
5100       SmallVector<const SCEV *, 4> MulOps;
5101       do {
5102         if (BO->Op) {
5103           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5104             MulOps.push_back(OpSCEV);
5105             break;
5106           }
5107 
5108           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5109           if (Flags != SCEV::FlagAnyWrap) {
5110             MulOps.push_back(
5111                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5112             break;
5113           }
5114         }
5115 
5116         MulOps.push_back(getSCEV(BO->RHS));
5117         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5118         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5119           MulOps.push_back(getSCEV(BO->LHS));
5120           break;
5121         }
5122         BO = NewBO;
5123       } while (true);
5124 
5125       return getMulExpr(MulOps);
5126     }
5127     case Instruction::UDiv:
5128       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5129     case Instruction::Sub: {
5130       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5131       if (BO->Op)
5132         Flags = getNoWrapFlagsFromUB(BO->Op);
5133       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5134     }
5135     case Instruction::And:
5136       // For an expression like x&255 that merely masks off the high bits,
5137       // use zext(trunc(x)) as the SCEV expression.
5138       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5139         if (CI->isNullValue())
5140           return getSCEV(BO->RHS);
5141         if (CI->isAllOnesValue())
5142           return getSCEV(BO->LHS);
5143         const APInt &A = CI->getValue();
5144 
5145         // Instcombine's ShrinkDemandedConstant may strip bits out of
5146         // constants, obscuring what would otherwise be a low-bits mask.
5147         // Use computeKnownBits to compute what ShrinkDemandedConstant
5148         // knew about to reconstruct a low-bits mask value.
5149         unsigned LZ = A.countLeadingZeros();
5150         unsigned TZ = A.countTrailingZeros();
5151         unsigned BitWidth = A.getBitWidth();
5152         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5153         computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
5154                          0, &AC, nullptr, &DT);
5155 
5156         APInt EffectiveMask =
5157             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5158         if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
5159           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5160           const SCEV *LHS = getSCEV(BO->LHS);
5161           const SCEV *ShiftedLHS = nullptr;
5162           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5163             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5164               // For an expression like (x * 8) & 8, simplify the multiply.
5165               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5166               unsigned GCD = std::min(MulZeros, TZ);
5167               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5168               SmallVector<const SCEV*, 4> MulOps;
5169               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5170               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5171               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5172               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5173             }
5174           }
5175           if (!ShiftedLHS)
5176             ShiftedLHS = getUDivExpr(LHS, MulCount);
5177           return getMulExpr(
5178               getZeroExtendExpr(
5179                   getTruncateExpr(ShiftedLHS,
5180                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5181                   BO->LHS->getType()),
5182               MulCount);
5183         }
5184       }
5185       break;
5186 
5187     case Instruction::Or:
5188       // If the RHS of the Or is a constant, we may have something like:
5189       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5190       // optimizations will transparently handle this case.
5191       //
5192       // In order for this transformation to be safe, the LHS must be of the
5193       // form X*(2^n) and the Or constant must be less than 2^n.
5194       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5195         const SCEV *LHS = getSCEV(BO->LHS);
5196         const APInt &CIVal = CI->getValue();
5197         if (GetMinTrailingZeros(LHS) >=
5198             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5199           // Build a plain add SCEV.
5200           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5201           // If the LHS of the add was an addrec and it has no-wrap flags,
5202           // transfer the no-wrap flags, since an or won't introduce a wrap.
5203           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5204             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5205             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5206                 OldAR->getNoWrapFlags());
5207           }
5208           return S;
5209         }
5210       }
5211       break;
5212 
5213     case Instruction::Xor:
5214       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5215         // If the RHS of xor is -1, then this is a not operation.
5216         if (CI->isAllOnesValue())
5217           return getNotSCEV(getSCEV(BO->LHS));
5218 
5219         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5220         // This is a variant of the check for xor with -1, and it handles
5221         // the case where instcombine has trimmed non-demanded bits out
5222         // of an xor with -1.
5223         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5224           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5225             if (LBO->getOpcode() == Instruction::And &&
5226                 LCI->getValue() == CI->getValue())
5227               if (const SCEVZeroExtendExpr *Z =
5228                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5229                 Type *UTy = BO->LHS->getType();
5230                 const SCEV *Z0 = Z->getOperand();
5231                 Type *Z0Ty = Z0->getType();
5232                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5233 
5234                 // If C is a low-bits mask, the zero extend is serving to
5235                 // mask off the high bits. Complement the operand and
5236                 // re-apply the zext.
5237                 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5238                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5239 
5240                 // If C is a single bit, it may be in the sign-bit position
5241                 // before the zero-extend. In this case, represent the xor
5242                 // using an add, which is equivalent, and re-apply the zext.
5243                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5244                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5245                     Trunc.isSignBit())
5246                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5247                                            UTy);
5248               }
5249       }
5250       break;
5251 
5252   case Instruction::Shl:
5253     // Turn shift left of a constant amount into a multiply.
5254     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5255       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5256 
5257       // If the shift count is not less than the bitwidth, the result of
5258       // the shift is undefined. Don't try to analyze it, because the
5259       // resolution chosen here may differ from the resolution chosen in
5260       // other parts of the compiler.
5261       if (SA->getValue().uge(BitWidth))
5262         break;
5263 
5264       // It is currently not resolved how to interpret NSW for left
5265       // shift by BitWidth - 1, so we avoid applying flags in that
5266       // case. Remove this check (or this comment) once the situation
5267       // is resolved. See
5268       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5269       // and http://reviews.llvm.org/D8890 .
5270       auto Flags = SCEV::FlagAnyWrap;
5271       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5272         Flags = getNoWrapFlagsFromUB(BO->Op);
5273 
5274       Constant *X = ConstantInt::get(getContext(),
5275         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5276       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5277     }
5278     break;
5279 
5280     case Instruction::AShr:
5281       // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5282       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5283         if (Operator *L = dyn_cast<Operator>(BO->LHS))
5284           if (L->getOpcode() == Instruction::Shl &&
5285               L->getOperand(1) == BO->RHS) {
5286             uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
5287 
5288             // If the shift count is not less than the bitwidth, the result of
5289             // the shift is undefined. Don't try to analyze it, because the
5290             // resolution chosen here may differ from the resolution chosen in
5291             // other parts of the compiler.
5292             if (CI->getValue().uge(BitWidth))
5293               break;
5294 
5295             uint64_t Amt = BitWidth - CI->getZExtValue();
5296             if (Amt == BitWidth)
5297               return getSCEV(L->getOperand(0)); // shift by zero --> noop
5298             return getSignExtendExpr(
5299                 getTruncateExpr(getSCEV(L->getOperand(0)),
5300                                 IntegerType::get(getContext(), Amt)),
5301                 BO->LHS->getType());
5302           }
5303       break;
5304     }
5305   }
5306 
5307   switch (U->getOpcode()) {
5308   case Instruction::Trunc:
5309     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5310 
5311   case Instruction::ZExt:
5312     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5313 
5314   case Instruction::SExt:
5315     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5316 
5317   case Instruction::BitCast:
5318     // BitCasts are no-op casts so we just eliminate the cast.
5319     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5320       return getSCEV(U->getOperand(0));
5321     break;
5322 
5323   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5324   // lead to pointer expressions which cannot safely be expanded to GEPs,
5325   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5326   // simplifying integer expressions.
5327 
5328   case Instruction::GetElementPtr:
5329     return createNodeForGEP(cast<GEPOperator>(U));
5330 
5331   case Instruction::PHI:
5332     return createNodeForPHI(cast<PHINode>(U));
5333 
5334   case Instruction::Select:
5335     // U can also be a select constant expr, which let fall through.  Since
5336     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5337     // constant expressions cannot have instructions as operands, we'd have
5338     // returned getUnknown for a select constant expressions anyway.
5339     if (isa<Instruction>(U))
5340       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5341                                       U->getOperand(1), U->getOperand(2));
5342     break;
5343 
5344   case Instruction::Call:
5345   case Instruction::Invoke:
5346     if (Value *RV = CallSite(U).getReturnedArgOperand())
5347       return getSCEV(RV);
5348     break;
5349   }
5350 
5351   return getUnknown(V);
5352 }
5353 
5354 
5355 
5356 //===----------------------------------------------------------------------===//
5357 //                   Iteration Count Computation Code
5358 //
5359 
5360 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
5361   if (!ExitCount)
5362     return 0;
5363 
5364   ConstantInt *ExitConst = ExitCount->getValue();
5365 
5366   // Guard against huge trip counts.
5367   if (ExitConst->getValue().getActiveBits() > 32)
5368     return 0;
5369 
5370   // In case of integer overflow, this returns 0, which is correct.
5371   return ((unsigned)ExitConst->getZExtValue()) + 1;
5372 }
5373 
5374 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5375   if (BasicBlock *ExitingBB = L->getExitingBlock())
5376     return getSmallConstantTripCount(L, ExitingBB);
5377 
5378   // No trip count information for multiple exits.
5379   return 0;
5380 }
5381 
5382 unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5383                                                     BasicBlock *ExitingBlock) {
5384   assert(ExitingBlock && "Must pass a non-null exiting block!");
5385   assert(L->isLoopExiting(ExitingBlock) &&
5386          "Exiting block must actually branch out of the loop!");
5387   const SCEVConstant *ExitCount =
5388       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
5389   return getConstantTripCount(ExitCount);
5390 }
5391 
5392 unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) {
5393   const auto *MaxExitCount =
5394       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
5395   return getConstantTripCount(MaxExitCount);
5396 }
5397 
5398 unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5399   if (BasicBlock *ExitingBB = L->getExitingBlock())
5400     return getSmallConstantTripMultiple(L, ExitingBB);
5401 
5402   // No trip multiple information for multiple exits.
5403   return 0;
5404 }
5405 
5406 /// Returns the largest constant divisor of the trip count of this loop as a
5407 /// normal unsigned value, if possible. This means that the actual trip count is
5408 /// always a multiple of the returned value (don't forget the trip count could
5409 /// very well be zero as well!).
5410 ///
5411 /// Returns 1 if the trip count is unknown or not guaranteed to be the
5412 /// multiple of a constant (which is also the case if the trip count is simply
5413 /// constant, use getSmallConstantTripCount for that case), Will also return 1
5414 /// if the trip count is very large (>= 2^32).
5415 ///
5416 /// As explained in the comments for getSmallConstantTripCount, this assumes
5417 /// that control exits the loop via ExitingBlock.
5418 unsigned
5419 ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5420                                               BasicBlock *ExitingBlock) {
5421   assert(ExitingBlock && "Must pass a non-null exiting block!");
5422   assert(L->isLoopExiting(ExitingBlock) &&
5423          "Exiting block must actually branch out of the loop!");
5424   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
5425   if (ExitCount == getCouldNotCompute())
5426     return 1;
5427 
5428   // Get the trip count from the BE count by adding 1.
5429   const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
5430   // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5431   // to factor simple cases.
5432   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5433     TCMul = Mul->getOperand(0);
5434 
5435   const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5436   if (!MulC)
5437     return 1;
5438 
5439   ConstantInt *Result = MulC->getValue();
5440 
5441   // Guard against huge trip counts (this requires checking
5442   // for zero to handle the case where the trip count == -1 and the
5443   // addition wraps).
5444   if (!Result || Result->getValue().getActiveBits() > 32 ||
5445       Result->getValue().getActiveBits() == 0)
5446     return 1;
5447 
5448   return (unsigned)Result->getZExtValue();
5449 }
5450 
5451 /// Get the expression for the number of loop iterations for which this loop is
5452 /// guaranteed not to exit via ExitingBlock. Otherwise return
5453 /// SCEVCouldNotCompute.
5454 const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5455   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
5456 }
5457 
5458 const SCEV *
5459 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5460                                                  SCEVUnionPredicate &Preds) {
5461   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5462 }
5463 
5464 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
5465   return getBackedgeTakenInfo(L).getExact(this);
5466 }
5467 
5468 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
5469 /// known never to be less than the actual backedge taken count.
5470 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
5471   return getBackedgeTakenInfo(L).getMax(this);
5472 }
5473 
5474 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
5475   return getBackedgeTakenInfo(L).isMaxOrZero(this);
5476 }
5477 
5478 /// Push PHI nodes in the header of the given loop onto the given Worklist.
5479 static void
5480 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5481   BasicBlock *Header = L->getHeader();
5482 
5483   // Push all Loop-header PHIs onto the Worklist stack.
5484   for (BasicBlock::iterator I = Header->begin();
5485        PHINode *PN = dyn_cast<PHINode>(I); ++I)
5486     Worklist.push_back(PN);
5487 }
5488 
5489 const ScalarEvolution::BackedgeTakenInfo &
5490 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5491   auto &BTI = getBackedgeTakenInfo(L);
5492   if (BTI.hasFullInfo())
5493     return BTI;
5494 
5495   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5496 
5497   if (!Pair.second)
5498     return Pair.first->second;
5499 
5500   BackedgeTakenInfo Result =
5501       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5502 
5503   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
5504 }
5505 
5506 const ScalarEvolution::BackedgeTakenInfo &
5507 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
5508   // Initially insert an invalid entry for this loop. If the insertion
5509   // succeeds, proceed to actually compute a backedge-taken count and
5510   // update the value. The temporary CouldNotCompute value tells SCEV
5511   // code elsewhere that it shouldn't attempt to request a new
5512   // backedge-taken count, which could result in infinite recursion.
5513   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
5514       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5515   if (!Pair.second)
5516     return Pair.first->second;
5517 
5518   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
5519   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5520   // must be cleared in this scope.
5521   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
5522 
5523   if (Result.getExact(this) != getCouldNotCompute()) {
5524     assert(isLoopInvariant(Result.getExact(this), L) &&
5525            isLoopInvariant(Result.getMax(this), L) &&
5526            "Computed backedge-taken count isn't loop invariant for loop!");
5527     ++NumTripCountsComputed;
5528   }
5529   else if (Result.getMax(this) == getCouldNotCompute() &&
5530            isa<PHINode>(L->getHeader()->begin())) {
5531     // Only count loops that have phi nodes as not being computable.
5532     ++NumTripCountsNotComputed;
5533   }
5534 
5535   // Now that we know more about the trip count for this loop, forget any
5536   // existing SCEV values for PHI nodes in this loop since they are only
5537   // conservative estimates made without the benefit of trip count
5538   // information. This is similar to the code in forgetLoop, except that
5539   // it handles SCEVUnknown PHI nodes specially.
5540   if (Result.hasAnyInfo()) {
5541     SmallVector<Instruction *, 16> Worklist;
5542     PushLoopPHIs(L, Worklist);
5543 
5544     SmallPtrSet<Instruction *, 8> Visited;
5545     while (!Worklist.empty()) {
5546       Instruction *I = Worklist.pop_back_val();
5547       if (!Visited.insert(I).second)
5548         continue;
5549 
5550       ValueExprMapType::iterator It =
5551         ValueExprMap.find_as(static_cast<Value *>(I));
5552       if (It != ValueExprMap.end()) {
5553         const SCEV *Old = It->second;
5554 
5555         // SCEVUnknown for a PHI either means that it has an unrecognized
5556         // structure, or it's a PHI that's in the progress of being computed
5557         // by createNodeForPHI.  In the former case, additional loop trip
5558         // count information isn't going to change anything. In the later
5559         // case, createNodeForPHI will perform the necessary updates on its
5560         // own when it gets to that point.
5561         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5562           eraseValueFromMap(It->first);
5563           forgetMemoizedResults(Old);
5564         }
5565         if (PHINode *PN = dyn_cast<PHINode>(I))
5566           ConstantEvolutionLoopExitValue.erase(PN);
5567       }
5568 
5569       PushDefUseChildren(I, Worklist);
5570     }
5571   }
5572 
5573   // Re-lookup the insert position, since the call to
5574   // computeBackedgeTakenCount above could result in a
5575   // recusive call to getBackedgeTakenInfo (on a different
5576   // loop), which would invalidate the iterator computed
5577   // earlier.
5578   return BackedgeTakenCounts.find(L)->second = std::move(Result);
5579 }
5580 
5581 void ScalarEvolution::forgetLoop(const Loop *L) {
5582   // Drop any stored trip count value.
5583   auto RemoveLoopFromBackedgeMap =
5584       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5585         auto BTCPos = Map.find(L);
5586         if (BTCPos != Map.end()) {
5587           BTCPos->second.clear();
5588           Map.erase(BTCPos);
5589         }
5590       };
5591 
5592   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5593   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
5594 
5595   // Drop information about expressions based on loop-header PHIs.
5596   SmallVector<Instruction *, 16> Worklist;
5597   PushLoopPHIs(L, Worklist);
5598 
5599   SmallPtrSet<Instruction *, 8> Visited;
5600   while (!Worklist.empty()) {
5601     Instruction *I = Worklist.pop_back_val();
5602     if (!Visited.insert(I).second)
5603       continue;
5604 
5605     ValueExprMapType::iterator It =
5606       ValueExprMap.find_as(static_cast<Value *>(I));
5607     if (It != ValueExprMap.end()) {
5608       eraseValueFromMap(It->first);
5609       forgetMemoizedResults(It->second);
5610       if (PHINode *PN = dyn_cast<PHINode>(I))
5611         ConstantEvolutionLoopExitValue.erase(PN);
5612     }
5613 
5614     PushDefUseChildren(I, Worklist);
5615   }
5616 
5617   // Forget all contained loops too, to avoid dangling entries in the
5618   // ValuesAtScopes map.
5619   for (Loop *I : *L)
5620     forgetLoop(I);
5621 
5622   LoopPropertiesCache.erase(L);
5623 }
5624 
5625 void ScalarEvolution::forgetValue(Value *V) {
5626   Instruction *I = dyn_cast<Instruction>(V);
5627   if (!I) return;
5628 
5629   // Drop information about expressions based on loop-header PHIs.
5630   SmallVector<Instruction *, 16> Worklist;
5631   Worklist.push_back(I);
5632 
5633   SmallPtrSet<Instruction *, 8> Visited;
5634   while (!Worklist.empty()) {
5635     I = Worklist.pop_back_val();
5636     if (!Visited.insert(I).second)
5637       continue;
5638 
5639     ValueExprMapType::iterator It =
5640       ValueExprMap.find_as(static_cast<Value *>(I));
5641     if (It != ValueExprMap.end()) {
5642       eraseValueFromMap(It->first);
5643       forgetMemoizedResults(It->second);
5644       if (PHINode *PN = dyn_cast<PHINode>(I))
5645         ConstantEvolutionLoopExitValue.erase(PN);
5646     }
5647 
5648     PushDefUseChildren(I, Worklist);
5649   }
5650 }
5651 
5652 /// Get the exact loop backedge taken count considering all loop exits. A
5653 /// computable result can only be returned for loops with a single exit.
5654 /// Returning the minimum taken count among all exits is incorrect because one
5655 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
5656 /// the limit of each loop test is never skipped. This is a valid assumption as
5657 /// long as the loop exits via that test. For precise results, it is the
5658 /// caller's responsibility to specify the relevant loop exit using
5659 /// getExact(ExitingBlock, SE).
5660 const SCEV *
5661 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
5662                                              SCEVUnionPredicate *Preds) const {
5663   // If any exits were not computable, the loop is not computable.
5664   if (!isComplete() || ExitNotTaken.empty())
5665     return SE->getCouldNotCompute();
5666 
5667   const SCEV *BECount = nullptr;
5668   for (auto &ENT : ExitNotTaken) {
5669     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
5670 
5671     if (!BECount)
5672       BECount = ENT.ExactNotTaken;
5673     else if (BECount != ENT.ExactNotTaken)
5674       return SE->getCouldNotCompute();
5675     if (Preds && !ENT.hasAlwaysTruePredicate())
5676       Preds->add(ENT.Predicate.get());
5677 
5678     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
5679            "Predicate should be always true!");
5680   }
5681 
5682   assert(BECount && "Invalid not taken count for loop exit");
5683   return BECount;
5684 }
5685 
5686 /// Get the exact not taken count for this loop exit.
5687 const SCEV *
5688 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
5689                                              ScalarEvolution *SE) const {
5690   for (auto &ENT : ExitNotTaken)
5691     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
5692       return ENT.ExactNotTaken;
5693 
5694   return SE->getCouldNotCompute();
5695 }
5696 
5697 /// getMax - Get the max backedge taken count for the loop.
5698 const SCEV *
5699 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
5700   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5701     return !ENT.hasAlwaysTruePredicate();
5702   };
5703 
5704   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
5705     return SE->getCouldNotCompute();
5706 
5707   return getMax();
5708 }
5709 
5710 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
5711   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
5712     return !ENT.hasAlwaysTruePredicate();
5713   };
5714   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
5715 }
5716 
5717 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5718                                                     ScalarEvolution *SE) const {
5719   if (getMax() && getMax() != SE->getCouldNotCompute() &&
5720       SE->hasOperand(getMax(), S))
5721     return true;
5722 
5723   for (auto &ENT : ExitNotTaken)
5724     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5725         SE->hasOperand(ENT.ExactNotTaken, S))
5726       return true;
5727 
5728   return false;
5729 }
5730 
5731 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5732 /// computable exit into a persistent ExitNotTakenInfo array.
5733 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
5734     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
5735         &&ExitCounts,
5736     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
5737     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
5738   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5739   ExitNotTaken.reserve(ExitCounts.size());
5740   std::transform(
5741       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
5742       [&](const EdgeExitInfo &EEI) {
5743         BasicBlock *ExitBB = EEI.first;
5744         const ExitLimit &EL = EEI.second;
5745         if (EL.Predicates.empty())
5746           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
5747 
5748         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
5749         for (auto *Pred : EL.Predicates)
5750           Predicate->add(Pred);
5751 
5752         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
5753       });
5754 }
5755 
5756 /// Invalidate this result and free the ExitNotTakenInfo array.
5757 void ScalarEvolution::BackedgeTakenInfo::clear() {
5758   ExitNotTaken.clear();
5759 }
5760 
5761 /// Compute the number of times the backedge of the specified loop will execute.
5762 ScalarEvolution::BackedgeTakenInfo
5763 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5764                                            bool AllowPredicates) {
5765   SmallVector<BasicBlock *, 8> ExitingBlocks;
5766   L->getExitingBlocks(ExitingBlocks);
5767 
5768   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
5769 
5770   SmallVector<EdgeExitInfo, 4> ExitCounts;
5771   bool CouldComputeBECount = true;
5772   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
5773   const SCEV *MustExitMaxBECount = nullptr;
5774   const SCEV *MayExitMaxBECount = nullptr;
5775   bool MustExitMaxOrZero = false;
5776 
5777   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5778   // and compute maxBECount.
5779   // Do a union of all the predicates here.
5780   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
5781     BasicBlock *ExitBB = ExitingBlocks[i];
5782     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5783 
5784     assert((AllowPredicates || EL.Predicates.empty()) &&
5785            "Predicated exit limit when predicates are not allowed!");
5786 
5787     // 1. For each exit that can be computed, add an entry to ExitCounts.
5788     // CouldComputeBECount is true only if all exits can be computed.
5789     if (EL.ExactNotTaken == getCouldNotCompute())
5790       // We couldn't compute an exact value for this exit, so
5791       // we won't be able to compute an exact value for the loop.
5792       CouldComputeBECount = false;
5793     else
5794       ExitCounts.emplace_back(ExitBB, EL);
5795 
5796     // 2. Derive the loop's MaxBECount from each exit's max number of
5797     // non-exiting iterations. Partition the loop exits into two kinds:
5798     // LoopMustExits and LoopMayExits.
5799     //
5800     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5801     // is a LoopMayExit.  If any computable LoopMustExit is found, then
5802     // MaxBECount is the minimum EL.MaxNotTaken of computable
5803     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
5804     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
5805     // computable EL.MaxNotTaken.
5806     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
5807         DT.dominates(ExitBB, Latch)) {
5808       if (!MustExitMaxBECount) {
5809         MustExitMaxBECount = EL.MaxNotTaken;
5810         MustExitMaxOrZero = EL.MaxOrZero;
5811       } else {
5812         MustExitMaxBECount =
5813             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
5814       }
5815     } else if (MayExitMaxBECount != getCouldNotCompute()) {
5816       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
5817         MayExitMaxBECount = EL.MaxNotTaken;
5818       else {
5819         MayExitMaxBECount =
5820             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
5821       }
5822     }
5823   }
5824   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5825     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
5826   // The loop backedge will be taken the maximum or zero times if there's
5827   // a single exit that must be taken the maximum or zero times.
5828   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
5829   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
5830                            MaxBECount, MaxOrZero);
5831 }
5832 
5833 ScalarEvolution::ExitLimit
5834 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5835                                   bool AllowPredicates) {
5836 
5837   // Okay, we've chosen an exiting block.  See what condition causes us to exit
5838   // at this block and remember the exit block and whether all other targets
5839   // lead to the loop header.
5840   bool MustExecuteLoopHeader = true;
5841   BasicBlock *Exit = nullptr;
5842   for (auto *SBB : successors(ExitingBlock))
5843     if (!L->contains(SBB)) {
5844       if (Exit) // Multiple exit successors.
5845         return getCouldNotCompute();
5846       Exit = SBB;
5847     } else if (SBB != L->getHeader()) {
5848       MustExecuteLoopHeader = false;
5849     }
5850 
5851   // At this point, we know we have a conditional branch that determines whether
5852   // the loop is exited.  However, we don't know if the branch is executed each
5853   // time through the loop.  If not, then the execution count of the branch will
5854   // not be equal to the trip count of the loop.
5855   //
5856   // Currently we check for this by checking to see if the Exit branch goes to
5857   // the loop header.  If so, we know it will always execute the same number of
5858   // times as the loop.  We also handle the case where the exit block *is* the
5859   // loop header.  This is common for un-rotated loops.
5860   //
5861   // If both of those tests fail, walk up the unique predecessor chain to the
5862   // header, stopping if there is an edge that doesn't exit the loop. If the
5863   // header is reached, the execution count of the branch will be equal to the
5864   // trip count of the loop.
5865   //
5866   //  More extensive analysis could be done to handle more cases here.
5867   //
5868   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
5869     // The simple checks failed, try climbing the unique predecessor chain
5870     // up to the header.
5871     bool Ok = false;
5872     for (BasicBlock *BB = ExitingBlock; BB; ) {
5873       BasicBlock *Pred = BB->getUniquePredecessor();
5874       if (!Pred)
5875         return getCouldNotCompute();
5876       TerminatorInst *PredTerm = Pred->getTerminator();
5877       for (const BasicBlock *PredSucc : PredTerm->successors()) {
5878         if (PredSucc == BB)
5879           continue;
5880         // If the predecessor has a successor that isn't BB and isn't
5881         // outside the loop, assume the worst.
5882         if (L->contains(PredSucc))
5883           return getCouldNotCompute();
5884       }
5885       if (Pred == L->getHeader()) {
5886         Ok = true;
5887         break;
5888       }
5889       BB = Pred;
5890     }
5891     if (!Ok)
5892       return getCouldNotCompute();
5893   }
5894 
5895   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
5896   TerminatorInst *Term = ExitingBlock->getTerminator();
5897   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5898     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5899     // Proceed to the next level to examine the exit condition expression.
5900     return computeExitLimitFromCond(
5901         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5902         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
5903   }
5904 
5905   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
5906     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
5907                                                 /*ControlsExit=*/IsOnlyExit);
5908 
5909   return getCouldNotCompute();
5910 }
5911 
5912 ScalarEvolution::ExitLimit
5913 ScalarEvolution::computeExitLimitFromCond(const Loop *L,
5914                                           Value *ExitCond,
5915                                           BasicBlock *TBB,
5916                                           BasicBlock *FBB,
5917                                           bool ControlsExit,
5918                                           bool AllowPredicates) {
5919   // Check if the controlling expression for this loop is an And or Or.
5920   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5921     if (BO->getOpcode() == Instruction::And) {
5922       // Recurse on the operands of the and.
5923       bool EitherMayExit = L->contains(TBB);
5924       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5925                                                ControlsExit && !EitherMayExit,
5926                                                AllowPredicates);
5927       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5928                                                ControlsExit && !EitherMayExit,
5929                                                AllowPredicates);
5930       const SCEV *BECount = getCouldNotCompute();
5931       const SCEV *MaxBECount = getCouldNotCompute();
5932       if (EitherMayExit) {
5933         // Both conditions must be true for the loop to continue executing.
5934         // Choose the less conservative count.
5935         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5936             EL1.ExactNotTaken == getCouldNotCompute())
5937           BECount = getCouldNotCompute();
5938         else
5939           BECount =
5940               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5941         if (EL0.MaxNotTaken == getCouldNotCompute())
5942           MaxBECount = EL1.MaxNotTaken;
5943         else if (EL1.MaxNotTaken == getCouldNotCompute())
5944           MaxBECount = EL0.MaxNotTaken;
5945         else
5946           MaxBECount =
5947               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5948       } else {
5949         // Both conditions must be true at the same time for the loop to exit.
5950         // For now, be conservative.
5951         assert(L->contains(FBB) && "Loop block has no successor in loop!");
5952         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
5953           MaxBECount = EL0.MaxNotTaken;
5954         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
5955           BECount = EL0.ExactNotTaken;
5956       }
5957 
5958       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5959       // to be more aggressive when computing BECount than when computing
5960       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
5961       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
5962       // to not.
5963       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5964           !isa<SCEVCouldNotCompute>(BECount))
5965         MaxBECount = BECount;
5966 
5967       return ExitLimit(BECount, MaxBECount, false,
5968                        {&EL0.Predicates, &EL1.Predicates});
5969     }
5970     if (BO->getOpcode() == Instruction::Or) {
5971       // Recurse on the operands of the or.
5972       bool EitherMayExit = L->contains(FBB);
5973       ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
5974                                                ControlsExit && !EitherMayExit,
5975                                                AllowPredicates);
5976       ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
5977                                                ControlsExit && !EitherMayExit,
5978                                                AllowPredicates);
5979       const SCEV *BECount = getCouldNotCompute();
5980       const SCEV *MaxBECount = getCouldNotCompute();
5981       if (EitherMayExit) {
5982         // Both conditions must be false for the loop to continue executing.
5983         // Choose the less conservative count.
5984         if (EL0.ExactNotTaken == getCouldNotCompute() ||
5985             EL1.ExactNotTaken == getCouldNotCompute())
5986           BECount = getCouldNotCompute();
5987         else
5988           BECount =
5989               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
5990         if (EL0.MaxNotTaken == getCouldNotCompute())
5991           MaxBECount = EL1.MaxNotTaken;
5992         else if (EL1.MaxNotTaken == getCouldNotCompute())
5993           MaxBECount = EL0.MaxNotTaken;
5994         else
5995           MaxBECount =
5996               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
5997       } else {
5998         // Both conditions must be false at the same time for the loop to exit.
5999         // For now, be conservative.
6000         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6001         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6002           MaxBECount = EL0.MaxNotTaken;
6003         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6004           BECount = EL0.ExactNotTaken;
6005       }
6006 
6007       return ExitLimit(BECount, MaxBECount, false,
6008                        {&EL0.Predicates, &EL1.Predicates});
6009     }
6010   }
6011 
6012   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6013   // Proceed to the next level to examine the icmp.
6014   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6015     ExitLimit EL =
6016         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6017     if (EL.hasFullInfo() || !AllowPredicates)
6018       return EL;
6019 
6020     // Try again, but use SCEV predicates this time.
6021     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6022                                     /*AllowPredicates=*/true);
6023   }
6024 
6025   // Check for a constant condition. These are normally stripped out by
6026   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6027   // preserve the CFG and is temporarily leaving constant conditions
6028   // in place.
6029   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6030     if (L->contains(FBB) == !CI->getZExtValue())
6031       // The backedge is always taken.
6032       return getCouldNotCompute();
6033     else
6034       // The backedge is never taken.
6035       return getZero(CI->getType());
6036   }
6037 
6038   // If it's not an integer or pointer comparison then compute it the hard way.
6039   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6040 }
6041 
6042 ScalarEvolution::ExitLimit
6043 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6044                                           ICmpInst *ExitCond,
6045                                           BasicBlock *TBB,
6046                                           BasicBlock *FBB,
6047                                           bool ControlsExit,
6048                                           bool AllowPredicates) {
6049 
6050   // If the condition was exit on true, convert the condition to exit on false
6051   ICmpInst::Predicate Cond;
6052   if (!L->contains(FBB))
6053     Cond = ExitCond->getPredicate();
6054   else
6055     Cond = ExitCond->getInversePredicate();
6056 
6057   // Handle common loops like: for (X = "string"; *X; ++X)
6058   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6059     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6060       ExitLimit ItCnt =
6061         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6062       if (ItCnt.hasAnyInfo())
6063         return ItCnt;
6064     }
6065 
6066   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6067   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6068 
6069   // Try to evaluate any dependencies out of the loop.
6070   LHS = getSCEVAtScope(LHS, L);
6071   RHS = getSCEVAtScope(RHS, L);
6072 
6073   // At this point, we would like to compute how many iterations of the
6074   // loop the predicate will return true for these inputs.
6075   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6076     // If there is a loop-invariant, force it into the RHS.
6077     std::swap(LHS, RHS);
6078     Cond = ICmpInst::getSwappedPredicate(Cond);
6079   }
6080 
6081   // Simplify the operands before analyzing them.
6082   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6083 
6084   // If we have a comparison of a chrec against a constant, try to use value
6085   // ranges to answer this query.
6086   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6087     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6088       if (AddRec->getLoop() == L) {
6089         // Form the constant range.
6090         ConstantRange CompRange =
6091             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6092 
6093         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6094         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6095       }
6096 
6097   switch (Cond) {
6098   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6099     // Convert to: while (X-Y != 0)
6100     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6101                                 AllowPredicates);
6102     if (EL.hasAnyInfo()) return EL;
6103     break;
6104   }
6105   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6106     // Convert to: while (X-Y == 0)
6107     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6108     if (EL.hasAnyInfo()) return EL;
6109     break;
6110   }
6111   case ICmpInst::ICMP_SLT:
6112   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6113     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6114     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6115                                     AllowPredicates);
6116     if (EL.hasAnyInfo()) return EL;
6117     break;
6118   }
6119   case ICmpInst::ICMP_SGT:
6120   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6121     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6122     ExitLimit EL =
6123         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6124                             AllowPredicates);
6125     if (EL.hasAnyInfo()) return EL;
6126     break;
6127   }
6128   default:
6129     break;
6130   }
6131 
6132   auto *ExhaustiveCount =
6133       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6134 
6135   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6136     return ExhaustiveCount;
6137 
6138   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6139                                       ExitCond->getOperand(1), L, Cond);
6140 }
6141 
6142 ScalarEvolution::ExitLimit
6143 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6144                                                       SwitchInst *Switch,
6145                                                       BasicBlock *ExitingBlock,
6146                                                       bool ControlsExit) {
6147   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6148 
6149   // Give up if the exit is the default dest of a switch.
6150   if (Switch->getDefaultDest() == ExitingBlock)
6151     return getCouldNotCompute();
6152 
6153   assert(L->contains(Switch->getDefaultDest()) &&
6154          "Default case must not exit the loop!");
6155   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6156   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6157 
6158   // while (X != Y) --> while (X-Y != 0)
6159   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6160   if (EL.hasAnyInfo())
6161     return EL;
6162 
6163   return getCouldNotCompute();
6164 }
6165 
6166 static ConstantInt *
6167 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6168                                 ScalarEvolution &SE) {
6169   const SCEV *InVal = SE.getConstant(C);
6170   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6171   assert(isa<SCEVConstant>(Val) &&
6172          "Evaluation of SCEV at constant didn't fold correctly?");
6173   return cast<SCEVConstant>(Val)->getValue();
6174 }
6175 
6176 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6177 /// compute the backedge execution count.
6178 ScalarEvolution::ExitLimit
6179 ScalarEvolution::computeLoadConstantCompareExitLimit(
6180   LoadInst *LI,
6181   Constant *RHS,
6182   const Loop *L,
6183   ICmpInst::Predicate predicate) {
6184 
6185   if (LI->isVolatile()) return getCouldNotCompute();
6186 
6187   // Check to see if the loaded pointer is a getelementptr of a global.
6188   // TODO: Use SCEV instead of manually grubbing with GEPs.
6189   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6190   if (!GEP) return getCouldNotCompute();
6191 
6192   // Make sure that it is really a constant global we are gepping, with an
6193   // initializer, and make sure the first IDX is really 0.
6194   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6195   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6196       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6197       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6198     return getCouldNotCompute();
6199 
6200   // Okay, we allow one non-constant index into the GEP instruction.
6201   Value *VarIdx = nullptr;
6202   std::vector<Constant*> Indexes;
6203   unsigned VarIdxNum = 0;
6204   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6205     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6206       Indexes.push_back(CI);
6207     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6208       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6209       VarIdx = GEP->getOperand(i);
6210       VarIdxNum = i-2;
6211       Indexes.push_back(nullptr);
6212     }
6213 
6214   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6215   if (!VarIdx)
6216     return getCouldNotCompute();
6217 
6218   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6219   // Check to see if X is a loop variant variable value now.
6220   const SCEV *Idx = getSCEV(VarIdx);
6221   Idx = getSCEVAtScope(Idx, L);
6222 
6223   // We can only recognize very limited forms of loop index expressions, in
6224   // particular, only affine AddRec's like {C1,+,C2}.
6225   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6226   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6227       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6228       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6229     return getCouldNotCompute();
6230 
6231   unsigned MaxSteps = MaxBruteForceIterations;
6232   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6233     ConstantInt *ItCst = ConstantInt::get(
6234                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6235     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6236 
6237     // Form the GEP offset.
6238     Indexes[VarIdxNum] = Val;
6239 
6240     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6241                                                          Indexes);
6242     if (!Result) break;  // Cannot compute!
6243 
6244     // Evaluate the condition for this iteration.
6245     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6246     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6247     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6248       ++NumArrayLenItCounts;
6249       return getConstant(ItCst);   // Found terminating iteration!
6250     }
6251   }
6252   return getCouldNotCompute();
6253 }
6254 
6255 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6256     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6257   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6258   if (!RHS)
6259     return getCouldNotCompute();
6260 
6261   const BasicBlock *Latch = L->getLoopLatch();
6262   if (!Latch)
6263     return getCouldNotCompute();
6264 
6265   const BasicBlock *Predecessor = L->getLoopPredecessor();
6266   if (!Predecessor)
6267     return getCouldNotCompute();
6268 
6269   // Return true if V is of the form "LHS `shift_op` <positive constant>".
6270   // Return LHS in OutLHS and shift_opt in OutOpCode.
6271   auto MatchPositiveShift =
6272       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6273 
6274     using namespace PatternMatch;
6275 
6276     ConstantInt *ShiftAmt;
6277     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6278       OutOpCode = Instruction::LShr;
6279     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6280       OutOpCode = Instruction::AShr;
6281     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6282       OutOpCode = Instruction::Shl;
6283     else
6284       return false;
6285 
6286     return ShiftAmt->getValue().isStrictlyPositive();
6287   };
6288 
6289   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6290   //
6291   // loop:
6292   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6293   //   %iv.shifted = lshr i32 %iv, <positive constant>
6294   //
6295   // Return true on a successful match.  Return the corresponding PHI node (%iv
6296   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6297   auto MatchShiftRecurrence =
6298       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6299     Optional<Instruction::BinaryOps> PostShiftOpCode;
6300 
6301     {
6302       Instruction::BinaryOps OpC;
6303       Value *V;
6304 
6305       // If we encounter a shift instruction, "peel off" the shift operation,
6306       // and remember that we did so.  Later when we inspect %iv's backedge
6307       // value, we will make sure that the backedge value uses the same
6308       // operation.
6309       //
6310       // Note: the peeled shift operation does not have to be the same
6311       // instruction as the one feeding into the PHI's backedge value.  We only
6312       // really care about it being the same *kind* of shift instruction --
6313       // that's all that is required for our later inferences to hold.
6314       if (MatchPositiveShift(LHS, V, OpC)) {
6315         PostShiftOpCode = OpC;
6316         LHS = V;
6317       }
6318     }
6319 
6320     PNOut = dyn_cast<PHINode>(LHS);
6321     if (!PNOut || PNOut->getParent() != L->getHeader())
6322       return false;
6323 
6324     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6325     Value *OpLHS;
6326 
6327     return
6328         // The backedge value for the PHI node must be a shift by a positive
6329         // amount
6330         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6331 
6332         // of the PHI node itself
6333         OpLHS == PNOut &&
6334 
6335         // and the kind of shift should be match the kind of shift we peeled
6336         // off, if any.
6337         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6338   };
6339 
6340   PHINode *PN;
6341   Instruction::BinaryOps OpCode;
6342   if (!MatchShiftRecurrence(LHS, PN, OpCode))
6343     return getCouldNotCompute();
6344 
6345   const DataLayout &DL = getDataLayout();
6346 
6347   // The key rationale for this optimization is that for some kinds of shift
6348   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6349   // within a finite number of iterations.  If the condition guarding the
6350   // backedge (in the sense that the backedge is taken if the condition is true)
6351   // is false for the value the shift recurrence stabilizes to, then we know
6352   // that the backedge is taken only a finite number of times.
6353 
6354   ConstantInt *StableValue = nullptr;
6355   switch (OpCode) {
6356   default:
6357     llvm_unreachable("Impossible case!");
6358 
6359   case Instruction::AShr: {
6360     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6361     // bitwidth(K) iterations.
6362     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6363     bool KnownZero, KnownOne;
6364     ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6365                    Predecessor->getTerminator(), &DT);
6366     auto *Ty = cast<IntegerType>(RHS->getType());
6367     if (KnownZero)
6368       StableValue = ConstantInt::get(Ty, 0);
6369     else if (KnownOne)
6370       StableValue = ConstantInt::get(Ty, -1, true);
6371     else
6372       return getCouldNotCompute();
6373 
6374     break;
6375   }
6376   case Instruction::LShr:
6377   case Instruction::Shl:
6378     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6379     // stabilize to 0 in at most bitwidth(K) iterations.
6380     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6381     break;
6382   }
6383 
6384   auto *Result =
6385       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6386   assert(Result->getType()->isIntegerTy(1) &&
6387          "Otherwise cannot be an operand to a branch instruction");
6388 
6389   if (Result->isZeroValue()) {
6390     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6391     const SCEV *UpperBound =
6392         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
6393     return ExitLimit(getCouldNotCompute(), UpperBound, false);
6394   }
6395 
6396   return getCouldNotCompute();
6397 }
6398 
6399 /// Return true if we can constant fold an instruction of the specified type,
6400 /// assuming that all operands were constants.
6401 static bool CanConstantFold(const Instruction *I) {
6402   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
6403       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6404       isa<LoadInst>(I))
6405     return true;
6406 
6407   if (const CallInst *CI = dyn_cast<CallInst>(I))
6408     if (const Function *F = CI->getCalledFunction())
6409       return canConstantFoldCallTo(F);
6410   return false;
6411 }
6412 
6413 /// Determine whether this instruction can constant evolve within this loop
6414 /// assuming its operands can all constant evolve.
6415 static bool canConstantEvolve(Instruction *I, const Loop *L) {
6416   // An instruction outside of the loop can't be derived from a loop PHI.
6417   if (!L->contains(I)) return false;
6418 
6419   if (isa<PHINode>(I)) {
6420     // We don't currently keep track of the control flow needed to evaluate
6421     // PHIs, so we cannot handle PHIs inside of loops.
6422     return L->getHeader() == I->getParent();
6423   }
6424 
6425   // If we won't be able to constant fold this expression even if the operands
6426   // are constants, bail early.
6427   return CanConstantFold(I);
6428 }
6429 
6430 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6431 /// recursing through each instruction operand until reaching a loop header phi.
6432 static PHINode *
6433 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
6434                                DenseMap<Instruction *, PHINode *> &PHIMap,
6435                                unsigned Depth) {
6436   if (Depth > MaxConstantEvolvingDepth)
6437     return nullptr;
6438 
6439   // Otherwise, we can evaluate this instruction if all of its operands are
6440   // constant or derived from a PHI node themselves.
6441   PHINode *PHI = nullptr;
6442   for (Value *Op : UseInst->operands()) {
6443     if (isa<Constant>(Op)) continue;
6444 
6445     Instruction *OpInst = dyn_cast<Instruction>(Op);
6446     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
6447 
6448     PHINode *P = dyn_cast<PHINode>(OpInst);
6449     if (!P)
6450       // If this operand is already visited, reuse the prior result.
6451       // We may have P != PHI if this is the deepest point at which the
6452       // inconsistent paths meet.
6453       P = PHIMap.lookup(OpInst);
6454     if (!P) {
6455       // Recurse and memoize the results, whether a phi is found or not.
6456       // This recursive call invalidates pointers into PHIMap.
6457       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
6458       PHIMap[OpInst] = P;
6459     }
6460     if (!P)
6461       return nullptr;  // Not evolving from PHI
6462     if (PHI && PHI != P)
6463       return nullptr;  // Evolving from multiple different PHIs.
6464     PHI = P;
6465   }
6466   // This is a expression evolving from a constant PHI!
6467   return PHI;
6468 }
6469 
6470 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6471 /// in the loop that V is derived from.  We allow arbitrary operations along the
6472 /// way, but the operands of an operation must either be constants or a value
6473 /// derived from a constant PHI.  If this expression does not fit with these
6474 /// constraints, return null.
6475 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
6476   Instruction *I = dyn_cast<Instruction>(V);
6477   if (!I || !canConstantEvolve(I, L)) return nullptr;
6478 
6479   if (PHINode *PN = dyn_cast<PHINode>(I))
6480     return PN;
6481 
6482   // Record non-constant instructions contained by the loop.
6483   DenseMap<Instruction *, PHINode *> PHIMap;
6484   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
6485 }
6486 
6487 /// EvaluateExpression - Given an expression that passes the
6488 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6489 /// in the loop has the value PHIVal.  If we can't fold this expression for some
6490 /// reason, return null.
6491 static Constant *EvaluateExpression(Value *V, const Loop *L,
6492                                     DenseMap<Instruction *, Constant *> &Vals,
6493                                     const DataLayout &DL,
6494                                     const TargetLibraryInfo *TLI) {
6495   // Convenient constant check, but redundant for recursive calls.
6496   if (Constant *C = dyn_cast<Constant>(V)) return C;
6497   Instruction *I = dyn_cast<Instruction>(V);
6498   if (!I) return nullptr;
6499 
6500   if (Constant *C = Vals.lookup(I)) return C;
6501 
6502   // An instruction inside the loop depends on a value outside the loop that we
6503   // weren't given a mapping for, or a value such as a call inside the loop.
6504   if (!canConstantEvolve(I, L)) return nullptr;
6505 
6506   // An unmapped PHI can be due to a branch or another loop inside this loop,
6507   // or due to this not being the initial iteration through a loop where we
6508   // couldn't compute the evolution of this particular PHI last time.
6509   if (isa<PHINode>(I)) return nullptr;
6510 
6511   std::vector<Constant*> Operands(I->getNumOperands());
6512 
6513   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
6514     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6515     if (!Operand) {
6516       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
6517       if (!Operands[i]) return nullptr;
6518       continue;
6519     }
6520     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
6521     Vals[Operand] = C;
6522     if (!C) return nullptr;
6523     Operands[i] = C;
6524   }
6525 
6526   if (CmpInst *CI = dyn_cast<CmpInst>(I))
6527     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6528                                            Operands[1], DL, TLI);
6529   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6530     if (!LI->isVolatile())
6531       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6532   }
6533   return ConstantFoldInstOperands(I, Operands, DL, TLI);
6534 }
6535 
6536 
6537 // If every incoming value to PN except the one for BB is a specific Constant,
6538 // return that, else return nullptr.
6539 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6540   Constant *IncomingVal = nullptr;
6541 
6542   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6543     if (PN->getIncomingBlock(i) == BB)
6544       continue;
6545 
6546     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6547     if (!CurrentVal)
6548       return nullptr;
6549 
6550     if (IncomingVal != CurrentVal) {
6551       if (IncomingVal)
6552         return nullptr;
6553       IncomingVal = CurrentVal;
6554     }
6555   }
6556 
6557   return IncomingVal;
6558 }
6559 
6560 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6561 /// in the header of its containing loop, we know the loop executes a
6562 /// constant number of times, and the PHI node is just a recurrence
6563 /// involving constants, fold it.
6564 Constant *
6565 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
6566                                                    const APInt &BEs,
6567                                                    const Loop *L) {
6568   auto I = ConstantEvolutionLoopExitValue.find(PN);
6569   if (I != ConstantEvolutionLoopExitValue.end())
6570     return I->second;
6571 
6572   if (BEs.ugt(MaxBruteForceIterations))
6573     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
6574 
6575   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6576 
6577   DenseMap<Instruction *, Constant *> CurrentIterVals;
6578   BasicBlock *Header = L->getHeader();
6579   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6580 
6581   BasicBlock *Latch = L->getLoopLatch();
6582   if (!Latch)
6583     return nullptr;
6584 
6585   for (auto &I : *Header) {
6586     PHINode *PHI = dyn_cast<PHINode>(&I);
6587     if (!PHI) break;
6588     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6589     if (!StartCST) continue;
6590     CurrentIterVals[PHI] = StartCST;
6591   }
6592   if (!CurrentIterVals.count(PN))
6593     return RetVal = nullptr;
6594 
6595   Value *BEValue = PN->getIncomingValueForBlock(Latch);
6596 
6597   // Execute the loop symbolically to determine the exit value.
6598   if (BEs.getActiveBits() >= 32)
6599     return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
6600 
6601   unsigned NumIterations = BEs.getZExtValue(); // must be in range
6602   unsigned IterationNum = 0;
6603   const DataLayout &DL = getDataLayout();
6604   for (; ; ++IterationNum) {
6605     if (IterationNum == NumIterations)
6606       return RetVal = CurrentIterVals[PN];  // Got exit value!
6607 
6608     // Compute the value of the PHIs for the next iteration.
6609     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
6610     DenseMap<Instruction *, Constant *> NextIterVals;
6611     Constant *NextPHI =
6612         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6613     if (!NextPHI)
6614       return nullptr;        // Couldn't evaluate!
6615     NextIterVals[PN] = NextPHI;
6616 
6617     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6618 
6619     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
6620     // cease to be able to evaluate one of them or if they stop evolving,
6621     // because that doesn't necessarily prevent us from computing PN.
6622     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
6623     for (const auto &I : CurrentIterVals) {
6624       PHINode *PHI = dyn_cast<PHINode>(I.first);
6625       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
6626       PHIsToCompute.emplace_back(PHI, I.second);
6627     }
6628     // We use two distinct loops because EvaluateExpression may invalidate any
6629     // iterators into CurrentIterVals.
6630     for (const auto &I : PHIsToCompute) {
6631       PHINode *PHI = I.first;
6632       Constant *&NextPHI = NextIterVals[PHI];
6633       if (!NextPHI) {   // Not already computed.
6634         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6635         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6636       }
6637       if (NextPHI != I.second)
6638         StoppedEvolving = false;
6639     }
6640 
6641     // If all entries in CurrentIterVals == NextIterVals then we can stop
6642     // iterating, the loop can't continue to change.
6643     if (StoppedEvolving)
6644       return RetVal = CurrentIterVals[PN];
6645 
6646     CurrentIterVals.swap(NextIterVals);
6647   }
6648 }
6649 
6650 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
6651                                                           Value *Cond,
6652                                                           bool ExitWhen) {
6653   PHINode *PN = getConstantEvolvingPHI(Cond, L);
6654   if (!PN) return getCouldNotCompute();
6655 
6656   // If the loop is canonicalized, the PHI will have exactly two entries.
6657   // That's the only form we support here.
6658   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6659 
6660   DenseMap<Instruction *, Constant *> CurrentIterVals;
6661   BasicBlock *Header = L->getHeader();
6662   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6663 
6664   BasicBlock *Latch = L->getLoopLatch();
6665   assert(Latch && "Should follow from NumIncomingValues == 2!");
6666 
6667   for (auto &I : *Header) {
6668     PHINode *PHI = dyn_cast<PHINode>(&I);
6669     if (!PHI)
6670       break;
6671     auto *StartCST = getOtherIncomingValue(PHI, Latch);
6672     if (!StartCST) continue;
6673     CurrentIterVals[PHI] = StartCST;
6674   }
6675   if (!CurrentIterVals.count(PN))
6676     return getCouldNotCompute();
6677 
6678   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
6679   // the loop symbolically to determine when the condition gets a value of
6680   // "ExitWhen".
6681   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
6682   const DataLayout &DL = getDataLayout();
6683   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
6684     auto *CondVal = dyn_cast_or_null<ConstantInt>(
6685         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
6686 
6687     // Couldn't symbolically evaluate.
6688     if (!CondVal) return getCouldNotCompute();
6689 
6690     if (CondVal->getValue() == uint64_t(ExitWhen)) {
6691       ++NumBruteForceTripCountsComputed;
6692       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
6693     }
6694 
6695     // Update all the PHI nodes for the next iteration.
6696     DenseMap<Instruction *, Constant *> NextIterVals;
6697 
6698     // Create a list of which PHIs we need to compute. We want to do this before
6699     // calling EvaluateExpression on them because that may invalidate iterators
6700     // into CurrentIterVals.
6701     SmallVector<PHINode *, 8> PHIsToCompute;
6702     for (const auto &I : CurrentIterVals) {
6703       PHINode *PHI = dyn_cast<PHINode>(I.first);
6704       if (!PHI || PHI->getParent() != Header) continue;
6705       PHIsToCompute.push_back(PHI);
6706     }
6707     for (PHINode *PHI : PHIsToCompute) {
6708       Constant *&NextPHI = NextIterVals[PHI];
6709       if (NextPHI) continue;    // Already computed!
6710 
6711       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
6712       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
6713     }
6714     CurrentIterVals.swap(NextIterVals);
6715   }
6716 
6717   // Too many iterations were needed to evaluate.
6718   return getCouldNotCompute();
6719 }
6720 
6721 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
6722   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6723       ValuesAtScopes[V];
6724   // Check to see if we've folded this expression at this loop before.
6725   for (auto &LS : Values)
6726     if (LS.first == L)
6727       return LS.second ? LS.second : V;
6728 
6729   Values.emplace_back(L, nullptr);
6730 
6731   // Otherwise compute it.
6732   const SCEV *C = computeSCEVAtScope(V, L);
6733   for (auto &LS : reverse(ValuesAtScopes[V]))
6734     if (LS.first == L) {
6735       LS.second = C;
6736       break;
6737     }
6738   return C;
6739 }
6740 
6741 /// This builds up a Constant using the ConstantExpr interface.  That way, we
6742 /// will return Constants for objects which aren't represented by a
6743 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6744 /// Returns NULL if the SCEV isn't representable as a Constant.
6745 static Constant *BuildConstantFromSCEV(const SCEV *V) {
6746   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
6747     case scCouldNotCompute:
6748     case scAddRecExpr:
6749       break;
6750     case scConstant:
6751       return cast<SCEVConstant>(V)->getValue();
6752     case scUnknown:
6753       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6754     case scSignExtend: {
6755       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6756       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6757         return ConstantExpr::getSExt(CastOp, SS->getType());
6758       break;
6759     }
6760     case scZeroExtend: {
6761       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6762       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6763         return ConstantExpr::getZExt(CastOp, SZ->getType());
6764       break;
6765     }
6766     case scTruncate: {
6767       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6768       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6769         return ConstantExpr::getTrunc(CastOp, ST->getType());
6770       break;
6771     }
6772     case scAddExpr: {
6773       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6774       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
6775         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6776           unsigned AS = PTy->getAddressSpace();
6777           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6778           C = ConstantExpr::getBitCast(C, DestPtrTy);
6779         }
6780         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6781           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
6782           if (!C2) return nullptr;
6783 
6784           // First pointer!
6785           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
6786             unsigned AS = C2->getType()->getPointerAddressSpace();
6787             std::swap(C, C2);
6788             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6789             // The offsets have been converted to bytes.  We can add bytes to an
6790             // i8* by GEP with the byte count in the first index.
6791             C = ConstantExpr::getBitCast(C, DestPtrTy);
6792           }
6793 
6794           // Don't bother trying to sum two pointers. We probably can't
6795           // statically compute a load that results from it anyway.
6796           if (C2->getType()->isPointerTy())
6797             return nullptr;
6798 
6799           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6800             if (PTy->getElementType()->isStructTy())
6801               C2 = ConstantExpr::getIntegerCast(
6802                   C2, Type::getInt32Ty(C->getContext()), true);
6803             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
6804           } else
6805             C = ConstantExpr::getAdd(C, C2);
6806         }
6807         return C;
6808       }
6809       break;
6810     }
6811     case scMulExpr: {
6812       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6813       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6814         // Don't bother with pointers at all.
6815         if (C->getType()->isPointerTy()) return nullptr;
6816         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6817           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
6818           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
6819           C = ConstantExpr::getMul(C, C2);
6820         }
6821         return C;
6822       }
6823       break;
6824     }
6825     case scUDivExpr: {
6826       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6827       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6828         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6829           if (LHS->getType() == RHS->getType())
6830             return ConstantExpr::getUDiv(LHS, RHS);
6831       break;
6832     }
6833     case scSMaxExpr:
6834     case scUMaxExpr:
6835       break; // TODO: smax, umax.
6836   }
6837   return nullptr;
6838 }
6839 
6840 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
6841   if (isa<SCEVConstant>(V)) return V;
6842 
6843   // If this instruction is evolved from a constant-evolving PHI, compute the
6844   // exit value from the loop without using SCEVs.
6845   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
6846     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
6847       const Loop *LI = this->LI[I->getParent()];
6848       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
6849         if (PHINode *PN = dyn_cast<PHINode>(I))
6850           if (PN->getParent() == LI->getHeader()) {
6851             // Okay, there is no closed form solution for the PHI node.  Check
6852             // to see if the loop that contains it has a known backedge-taken
6853             // count.  If so, we may be able to force computation of the exit
6854             // value.
6855             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
6856             if (const SCEVConstant *BTCC =
6857                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
6858               // Okay, we know how many times the containing loop executes.  If
6859               // this is a constant evolving PHI node, get the final value at
6860               // the specified iteration number.
6861               Constant *RV =
6862                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
6863               if (RV) return getSCEV(RV);
6864             }
6865           }
6866 
6867       // Okay, this is an expression that we cannot symbolically evaluate
6868       // into a SCEV.  Check to see if it's possible to symbolically evaluate
6869       // the arguments into constants, and if so, try to constant propagate the
6870       // result.  This is particularly useful for computing loop exit values.
6871       if (CanConstantFold(I)) {
6872         SmallVector<Constant *, 4> Operands;
6873         bool MadeImprovement = false;
6874         for (Value *Op : I->operands()) {
6875           if (Constant *C = dyn_cast<Constant>(Op)) {
6876             Operands.push_back(C);
6877             continue;
6878           }
6879 
6880           // If any of the operands is non-constant and if they are
6881           // non-integer and non-pointer, don't even try to analyze them
6882           // with scev techniques.
6883           if (!isSCEVable(Op->getType()))
6884             return V;
6885 
6886           const SCEV *OrigV = getSCEV(Op);
6887           const SCEV *OpV = getSCEVAtScope(OrigV, L);
6888           MadeImprovement |= OrigV != OpV;
6889 
6890           Constant *C = BuildConstantFromSCEV(OpV);
6891           if (!C) return V;
6892           if (C->getType() != Op->getType())
6893             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6894                                                               Op->getType(),
6895                                                               false),
6896                                       C, Op->getType());
6897           Operands.push_back(C);
6898         }
6899 
6900         // Check to see if getSCEVAtScope actually made an improvement.
6901         if (MadeImprovement) {
6902           Constant *C = nullptr;
6903           const DataLayout &DL = getDataLayout();
6904           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
6905             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
6906                                                 Operands[1], DL, &TLI);
6907           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6908             if (!LI->isVolatile())
6909               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
6910           } else
6911             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
6912           if (!C) return V;
6913           return getSCEV(C);
6914         }
6915       }
6916     }
6917 
6918     // This is some other type of SCEVUnknown, just return it.
6919     return V;
6920   }
6921 
6922   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
6923     // Avoid performing the look-up in the common case where the specified
6924     // expression has no loop-variant portions.
6925     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
6926       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6927       if (OpAtScope != Comm->getOperand(i)) {
6928         // Okay, at least one of these operands is loop variant but might be
6929         // foldable.  Build a new instance of the folded commutative expression.
6930         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6931                                             Comm->op_begin()+i);
6932         NewOps.push_back(OpAtScope);
6933 
6934         for (++i; i != e; ++i) {
6935           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
6936           NewOps.push_back(OpAtScope);
6937         }
6938         if (isa<SCEVAddExpr>(Comm))
6939           return getAddExpr(NewOps);
6940         if (isa<SCEVMulExpr>(Comm))
6941           return getMulExpr(NewOps);
6942         if (isa<SCEVSMaxExpr>(Comm))
6943           return getSMaxExpr(NewOps);
6944         if (isa<SCEVUMaxExpr>(Comm))
6945           return getUMaxExpr(NewOps);
6946         llvm_unreachable("Unknown commutative SCEV type!");
6947       }
6948     }
6949     // If we got here, all operands are loop invariant.
6950     return Comm;
6951   }
6952 
6953   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
6954     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6955     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
6956     if (LHS == Div->getLHS() && RHS == Div->getRHS())
6957       return Div;   // must be loop invariant
6958     return getUDivExpr(LHS, RHS);
6959   }
6960 
6961   // If this is a loop recurrence for a loop that does not contain L, then we
6962   // are dealing with the final value computed by the loop.
6963   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
6964     // First, attempt to evaluate each operand.
6965     // Avoid performing the look-up in the common case where the specified
6966     // expression has no loop-variant portions.
6967     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6968       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6969       if (OpAtScope == AddRec->getOperand(i))
6970         continue;
6971 
6972       // Okay, at least one of these operands is loop variant but might be
6973       // foldable.  Build a new instance of the folded commutative expression.
6974       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6975                                           AddRec->op_begin()+i);
6976       NewOps.push_back(OpAtScope);
6977       for (++i; i != e; ++i)
6978         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6979 
6980       const SCEV *FoldedRec =
6981         getAddRecExpr(NewOps, AddRec->getLoop(),
6982                       AddRec->getNoWrapFlags(SCEV::FlagNW));
6983       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
6984       // The addrec may be folded to a nonrecurrence, for example, if the
6985       // induction variable is multiplied by zero after constant folding. Go
6986       // ahead and return the folded value.
6987       if (!AddRec)
6988         return FoldedRec;
6989       break;
6990     }
6991 
6992     // If the scope is outside the addrec's loop, evaluate it by using the
6993     // loop exit value of the addrec.
6994     if (!AddRec->getLoop()->contains(L)) {
6995       // To evaluate this recurrence, we need to know how many times the AddRec
6996       // loop iterates.  Compute this now.
6997       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
6998       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
6999 
7000       // Then, evaluate the AddRec.
7001       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7002     }
7003 
7004     return AddRec;
7005   }
7006 
7007   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7008     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7009     if (Op == Cast->getOperand())
7010       return Cast;  // must be loop invariant
7011     return getZeroExtendExpr(Op, Cast->getType());
7012   }
7013 
7014   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7015     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7016     if (Op == Cast->getOperand())
7017       return Cast;  // must be loop invariant
7018     return getSignExtendExpr(Op, Cast->getType());
7019   }
7020 
7021   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7022     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7023     if (Op == Cast->getOperand())
7024       return Cast;  // must be loop invariant
7025     return getTruncateExpr(Op, Cast->getType());
7026   }
7027 
7028   llvm_unreachable("Unknown SCEV type!");
7029 }
7030 
7031 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7032   return getSCEVAtScope(getSCEV(V), L);
7033 }
7034 
7035 /// Finds the minimum unsigned root of the following equation:
7036 ///
7037 ///     A * X = B (mod N)
7038 ///
7039 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7040 /// A and B isn't important.
7041 ///
7042 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7043 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
7044                                                ScalarEvolution &SE) {
7045   uint32_t BW = A.getBitWidth();
7046   assert(BW == B.getBitWidth() && "Bit widths must be the same.");
7047   assert(A != 0 && "A must be non-zero.");
7048 
7049   // 1. D = gcd(A, N)
7050   //
7051   // The gcd of A and N may have only one prime factor: 2. The number of
7052   // trailing zeros in A is its multiplicity
7053   uint32_t Mult2 = A.countTrailingZeros();
7054   // D = 2^Mult2
7055 
7056   // 2. Check if B is divisible by D.
7057   //
7058   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7059   // is not less than multiplicity of this prime factor for D.
7060   if (B.countTrailingZeros() < Mult2)
7061     return SE.getCouldNotCompute();
7062 
7063   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7064   // modulo (N / D).
7065   //
7066   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7067   // (N / D) in general. The inverse itself always fits into BW bits, though,
7068   // so we immediately truncate it.
7069   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7070   APInt Mod(BW + 1, 0);
7071   Mod.setBit(BW - Mult2);  // Mod = N / D
7072   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7073 
7074   // 4. Compute the minimum unsigned root of the equation:
7075   // I * (B / D) mod (N / D)
7076   // To simplify the computation, we factor out the divide by D:
7077   // (I * B mod N) / D
7078   APInt Result = (I * B).lshr(Mult2);
7079 
7080   return SE.getConstant(Result);
7081 }
7082 
7083 /// Find the roots of the quadratic equation for the given quadratic chrec
7084 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7085 /// two SCEVCouldNotCompute objects.
7086 ///
7087 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7088 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7089   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7090   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7091   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7092   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7093 
7094   // We currently can only solve this if the coefficients are constants.
7095   if (!LC || !MC || !NC)
7096     return None;
7097 
7098   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7099   const APInt &L = LC->getAPInt();
7100   const APInt &M = MC->getAPInt();
7101   const APInt &N = NC->getAPInt();
7102   APInt Two(BitWidth, 2);
7103   APInt Four(BitWidth, 4);
7104 
7105   {
7106     using namespace APIntOps;
7107     const APInt& C = L;
7108     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7109     // The B coefficient is M-N/2
7110     APInt B(M);
7111     B -= sdiv(N,Two);
7112 
7113     // The A coefficient is N/2
7114     APInt A(N.sdiv(Two));
7115 
7116     // Compute the B^2-4ac term.
7117     APInt SqrtTerm(B);
7118     SqrtTerm *= B;
7119     SqrtTerm -= Four * (A * C);
7120 
7121     if (SqrtTerm.isNegative()) {
7122       // The loop is provably infinite.
7123       return None;
7124     }
7125 
7126     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7127     // integer value or else APInt::sqrt() will assert.
7128     APInt SqrtVal(SqrtTerm.sqrt());
7129 
7130     // Compute the two solutions for the quadratic formula.
7131     // The divisions must be performed as signed divisions.
7132     APInt NegB(-B);
7133     APInt TwoA(A << 1);
7134     if (TwoA.isMinValue())
7135       return None;
7136 
7137     LLVMContext &Context = SE.getContext();
7138 
7139     ConstantInt *Solution1 =
7140       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7141     ConstantInt *Solution2 =
7142       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7143 
7144     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7145                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7146   } // end APIntOps namespace
7147 }
7148 
7149 ScalarEvolution::ExitLimit
7150 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7151                               bool AllowPredicates) {
7152 
7153   // This is only used for loops with a "x != y" exit test. The exit condition
7154   // is now expressed as a single expression, V = x-y. So the exit test is
7155   // effectively V != 0.  We know and take advantage of the fact that this
7156   // expression only being used in a comparison by zero context.
7157 
7158   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7159   // If the value is a constant
7160   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7161     // If the value is already zero, the branch will execute zero times.
7162     if (C->getValue()->isZero()) return C;
7163     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7164   }
7165 
7166   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7167   if (!AddRec && AllowPredicates)
7168     // Try to make this an AddRec using runtime tests, in the first X
7169     // iterations of this loop, where X is the SCEV expression found by the
7170     // algorithm below.
7171     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7172 
7173   if (!AddRec || AddRec->getLoop() != L)
7174     return getCouldNotCompute();
7175 
7176   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7177   // the quadratic equation to solve it.
7178   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7179     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7180       const SCEVConstant *R1 = Roots->first;
7181       const SCEVConstant *R2 = Roots->second;
7182       // Pick the smallest positive root value.
7183       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7184               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7185         if (!CB->getZExtValue())
7186           std::swap(R1, R2); // R1 is the minimum root now.
7187 
7188         // We can only use this value if the chrec ends up with an exact zero
7189         // value at this index.  When solving for "X*X != 5", for example, we
7190         // should not accept a root of 2.
7191         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7192         if (Val->isZero())
7193           // We found a quadratic root!
7194           return ExitLimit(R1, R1, false, Predicates);
7195       }
7196     }
7197     return getCouldNotCompute();
7198   }
7199 
7200   // Otherwise we can only handle this if it is affine.
7201   if (!AddRec->isAffine())
7202     return getCouldNotCompute();
7203 
7204   // If this is an affine expression, the execution count of this branch is
7205   // the minimum unsigned root of the following equation:
7206   //
7207   //     Start + Step*N = 0 (mod 2^BW)
7208   //
7209   // equivalent to:
7210   //
7211   //             Step*N = -Start (mod 2^BW)
7212   //
7213   // where BW is the common bit width of Start and Step.
7214 
7215   // Get the initial value for the loop.
7216   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7217   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7218 
7219   // For now we handle only constant steps.
7220   //
7221   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7222   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7223   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7224   // We have not yet seen any such cases.
7225   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7226   if (!StepC || StepC->getValue()->equalsInt(0))
7227     return getCouldNotCompute();
7228 
7229   // For positive steps (counting up until unsigned overflow):
7230   //   N = -Start/Step (as unsigned)
7231   // For negative steps (counting down to zero):
7232   //   N = Start/-Step
7233   // First compute the unsigned distance from zero in the direction of Step.
7234   bool CountDown = StepC->getAPInt().isNegative();
7235   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7236 
7237   // Handle unitary steps, which cannot wraparound.
7238   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7239   //   N = Distance (as unsigned)
7240   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7241     APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7242 
7243     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7244     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7245     // case, and see if we can improve the bound.
7246     //
7247     // Explicitly handling this here is necessary because getUnsignedRange
7248     // isn't context-sensitive; it doesn't know that we only care about the
7249     // range inside the loop.
7250     const SCEV *Zero = getZero(Distance->getType());
7251     const SCEV *One = getOne(Distance->getType());
7252     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7253     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7254       // If Distance + 1 doesn't overflow, we can compute the maximum distance
7255       // as "unsigned_max(Distance + 1) - 1".
7256       ConstantRange CR = getUnsignedRange(DistancePlusOne);
7257       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7258     }
7259     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7260   }
7261 
7262   // As a special case, handle the instance where Step is a positive power of
7263   // two. In this case, determining whether Step divides Distance evenly can be
7264   // done by counting and comparing the number of trailing zeros of Step and
7265   // Distance.
7266   if (!CountDown) {
7267     const APInt &StepV = StepC->getAPInt();
7268     // StepV.isPowerOf2() returns true if StepV is an positive power of two.  It
7269     // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7270     // case is not handled as this code is guarded by !CountDown.
7271     if (StepV.isPowerOf2() &&
7272         GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7273       // Here we've constrained the equation to be of the form
7274       //
7275       //   2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W)  ... (0)
7276       //
7277       // where we're operating on a W bit wide integer domain and k is
7278       // non-negative.  The smallest unsigned solution for X is the trip count.
7279       //
7280       // (0) is equivalent to:
7281       //
7282       //      2^(N + k) * Distance' - 2^N * X = L * 2^W
7283       // <=>  2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7284       // <=>  2^k * Distance' - X = L * 2^(W - N)
7285       // <=>  2^k * Distance'     = L * 2^(W - N) + X    ... (1)
7286       //
7287       // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7288       // by 2^(W - N).
7289       //
7290       // <=>  X = 2^k * Distance' URem 2^(W - N)   ... (2)
7291       //
7292       // E.g. say we're solving
7293       //
7294       //   2 * Val = 2 * X  (in i8)   ... (3)
7295       //
7296       // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7297       //
7298       // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7299       // necessarily the smallest unsigned value of X that satisfies (3).
7300       // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7301       // is i8 1, not i8 -127
7302 
7303       const auto *Limit = getUDivExactExpr(Distance, Step);
7304       return ExitLimit(Limit, Limit, false, Predicates);
7305     }
7306   }
7307 
7308   // If the condition controls loop exit (the loop exits only if the expression
7309   // is true) and the addition is no-wrap we can use unsigned divide to
7310   // compute the backedge count.  In this case, the step may not divide the
7311   // distance, but we don't care because if the condition is "missed" the loop
7312   // will have undefined behavior due to wrapping.
7313   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7314       loopHasNoAbnormalExits(AddRec->getLoop())) {
7315     const SCEV *Exact =
7316         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7317     return ExitLimit(Exact, Exact, false, Predicates);
7318   }
7319 
7320   // Then, try to solve the above equation provided that Start is constant.
7321   if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7322     const SCEV *E = SolveLinEquationWithOverflow(
7323         StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7324     return ExitLimit(E, E, false, Predicates);
7325   }
7326   return getCouldNotCompute();
7327 }
7328 
7329 ScalarEvolution::ExitLimit
7330 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7331   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7332   // handle them yet except for the trivial case.  This could be expanded in the
7333   // future as needed.
7334 
7335   // If the value is a constant, check to see if it is known to be non-zero
7336   // already.  If so, the backedge will execute zero times.
7337   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7338     if (!C->getValue()->isNullValue())
7339       return getZero(C->getType());
7340     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7341   }
7342 
7343   // We could implement others, but I really doubt anyone writes loops like
7344   // this, and if they did, they would already be constant folded.
7345   return getCouldNotCompute();
7346 }
7347 
7348 std::pair<BasicBlock *, BasicBlock *>
7349 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7350   // If the block has a unique predecessor, then there is no path from the
7351   // predecessor to the block that does not go through the direct edge
7352   // from the predecessor to the block.
7353   if (BasicBlock *Pred = BB->getSinglePredecessor())
7354     return {Pred, BB};
7355 
7356   // A loop's header is defined to be a block that dominates the loop.
7357   // If the header has a unique predecessor outside the loop, it must be
7358   // a block that has exactly one successor that can reach the loop.
7359   if (Loop *L = LI.getLoopFor(BB))
7360     return {L->getLoopPredecessor(), L->getHeader()};
7361 
7362   return {nullptr, nullptr};
7363 }
7364 
7365 /// SCEV structural equivalence is usually sufficient for testing whether two
7366 /// expressions are equal, however for the purposes of looking for a condition
7367 /// guarding a loop, it can be useful to be a little more general, since a
7368 /// front-end may have replicated the controlling expression.
7369 ///
7370 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7371   // Quick check to see if they are the same SCEV.
7372   if (A == B) return true;
7373 
7374   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7375     // Not all instructions that are "identical" compute the same value.  For
7376     // instance, two distinct alloca instructions allocating the same type are
7377     // identical and do not read memory; but compute distinct values.
7378     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7379   };
7380 
7381   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7382   // two different instructions with the same value. Check for this case.
7383   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7384     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7385       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7386         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7387           if (ComputesEqualValues(AI, BI))
7388             return true;
7389 
7390   // Otherwise assume they may have a different value.
7391   return false;
7392 }
7393 
7394 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7395                                            const SCEV *&LHS, const SCEV *&RHS,
7396                                            unsigned Depth) {
7397   bool Changed = false;
7398 
7399   // If we hit the max recursion limit bail out.
7400   if (Depth >= 3)
7401     return false;
7402 
7403   // Canonicalize a constant to the right side.
7404   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7405     // Check for both operands constant.
7406     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7407       if (ConstantExpr::getICmp(Pred,
7408                                 LHSC->getValue(),
7409                                 RHSC->getValue())->isNullValue())
7410         goto trivially_false;
7411       else
7412         goto trivially_true;
7413     }
7414     // Otherwise swap the operands to put the constant on the right.
7415     std::swap(LHS, RHS);
7416     Pred = ICmpInst::getSwappedPredicate(Pred);
7417     Changed = true;
7418   }
7419 
7420   // If we're comparing an addrec with a value which is loop-invariant in the
7421   // addrec's loop, put the addrec on the left. Also make a dominance check,
7422   // as both operands could be addrecs loop-invariant in each other's loop.
7423   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7424     const Loop *L = AR->getLoop();
7425     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7426       std::swap(LHS, RHS);
7427       Pred = ICmpInst::getSwappedPredicate(Pred);
7428       Changed = true;
7429     }
7430   }
7431 
7432   // If there's a constant operand, canonicalize comparisons with boundary
7433   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7434   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7435     const APInt &RA = RC->getAPInt();
7436 
7437     bool SimplifiedByConstantRange = false;
7438 
7439     if (!ICmpInst::isEquality(Pred)) {
7440       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7441       if (ExactCR.isFullSet())
7442         goto trivially_true;
7443       else if (ExactCR.isEmptySet())
7444         goto trivially_false;
7445 
7446       APInt NewRHS;
7447       CmpInst::Predicate NewPred;
7448       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7449           ICmpInst::isEquality(NewPred)) {
7450         // We were able to convert an inequality to an equality.
7451         Pred = NewPred;
7452         RHS = getConstant(NewRHS);
7453         Changed = SimplifiedByConstantRange = true;
7454       }
7455     }
7456 
7457     if (!SimplifiedByConstantRange) {
7458       switch (Pred) {
7459       default:
7460         break;
7461       case ICmpInst::ICMP_EQ:
7462       case ICmpInst::ICMP_NE:
7463         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7464         if (!RA)
7465           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7466             if (const SCEVMulExpr *ME =
7467                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7468               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7469                   ME->getOperand(0)->isAllOnesValue()) {
7470                 RHS = AE->getOperand(1);
7471                 LHS = ME->getOperand(1);
7472                 Changed = true;
7473               }
7474         break;
7475 
7476 
7477         // The "Should have been caught earlier!" messages refer to the fact
7478         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7479         // should have fired on the corresponding cases, and canonicalized the
7480         // check to trivially_true or trivially_false.
7481 
7482       case ICmpInst::ICMP_UGE:
7483         assert(!RA.isMinValue() && "Should have been caught earlier!");
7484         Pred = ICmpInst::ICMP_UGT;
7485         RHS = getConstant(RA - 1);
7486         Changed = true;
7487         break;
7488       case ICmpInst::ICMP_ULE:
7489         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7490         Pred = ICmpInst::ICMP_ULT;
7491         RHS = getConstant(RA + 1);
7492         Changed = true;
7493         break;
7494       case ICmpInst::ICMP_SGE:
7495         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7496         Pred = ICmpInst::ICMP_SGT;
7497         RHS = getConstant(RA - 1);
7498         Changed = true;
7499         break;
7500       case ICmpInst::ICMP_SLE:
7501         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7502         Pred = ICmpInst::ICMP_SLT;
7503         RHS = getConstant(RA + 1);
7504         Changed = true;
7505         break;
7506       }
7507     }
7508   }
7509 
7510   // Check for obvious equality.
7511   if (HasSameValue(LHS, RHS)) {
7512     if (ICmpInst::isTrueWhenEqual(Pred))
7513       goto trivially_true;
7514     if (ICmpInst::isFalseWhenEqual(Pred))
7515       goto trivially_false;
7516   }
7517 
7518   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7519   // adding or subtracting 1 from one of the operands.
7520   switch (Pred) {
7521   case ICmpInst::ICMP_SLE:
7522     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7523       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7524                        SCEV::FlagNSW);
7525       Pred = ICmpInst::ICMP_SLT;
7526       Changed = true;
7527     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7528       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7529                        SCEV::FlagNSW);
7530       Pred = ICmpInst::ICMP_SLT;
7531       Changed = true;
7532     }
7533     break;
7534   case ICmpInst::ICMP_SGE:
7535     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7536       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7537                        SCEV::FlagNSW);
7538       Pred = ICmpInst::ICMP_SGT;
7539       Changed = true;
7540     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7541       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7542                        SCEV::FlagNSW);
7543       Pred = ICmpInst::ICMP_SGT;
7544       Changed = true;
7545     }
7546     break;
7547   case ICmpInst::ICMP_ULE:
7548     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7549       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7550                        SCEV::FlagNUW);
7551       Pred = ICmpInst::ICMP_ULT;
7552       Changed = true;
7553     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7554       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7555       Pred = ICmpInst::ICMP_ULT;
7556       Changed = true;
7557     }
7558     break;
7559   case ICmpInst::ICMP_UGE:
7560     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7561       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7562       Pred = ICmpInst::ICMP_UGT;
7563       Changed = true;
7564     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7565       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7566                        SCEV::FlagNUW);
7567       Pred = ICmpInst::ICMP_UGT;
7568       Changed = true;
7569     }
7570     break;
7571   default:
7572     break;
7573   }
7574 
7575   // TODO: More simplifications are possible here.
7576 
7577   // Recursively simplify until we either hit a recursion limit or nothing
7578   // changes.
7579   if (Changed)
7580     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7581 
7582   return Changed;
7583 
7584 trivially_true:
7585   // Return 0 == 0.
7586   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7587   Pred = ICmpInst::ICMP_EQ;
7588   return true;
7589 
7590 trivially_false:
7591   // Return 0 != 0.
7592   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7593   Pred = ICmpInst::ICMP_NE;
7594   return true;
7595 }
7596 
7597 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7598   return getSignedRange(S).getSignedMax().isNegative();
7599 }
7600 
7601 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7602   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7603 }
7604 
7605 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7606   return !getSignedRange(S).getSignedMin().isNegative();
7607 }
7608 
7609 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7610   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7611 }
7612 
7613 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7614   return isKnownNegative(S) || isKnownPositive(S);
7615 }
7616 
7617 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7618                                        const SCEV *LHS, const SCEV *RHS) {
7619   // Canonicalize the inputs first.
7620   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7621 
7622   // If LHS or RHS is an addrec, check to see if the condition is true in
7623   // every iteration of the loop.
7624   // If LHS and RHS are both addrec, both conditions must be true in
7625   // every iteration of the loop.
7626   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7627   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7628   bool LeftGuarded = false;
7629   bool RightGuarded = false;
7630   if (LAR) {
7631     const Loop *L = LAR->getLoop();
7632     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7633         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7634       if (!RAR) return true;
7635       LeftGuarded = true;
7636     }
7637   }
7638   if (RAR) {
7639     const Loop *L = RAR->getLoop();
7640     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7641         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7642       if (!LAR) return true;
7643       RightGuarded = true;
7644     }
7645   }
7646   if (LeftGuarded && RightGuarded)
7647     return true;
7648 
7649   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7650     return true;
7651 
7652   // Otherwise see what can be done with known constant ranges.
7653   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7654 }
7655 
7656 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7657                                            ICmpInst::Predicate Pred,
7658                                            bool &Increasing) {
7659   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7660 
7661 #ifndef NDEBUG
7662   // Verify an invariant: inverting the predicate should turn a monotonically
7663   // increasing change to a monotonically decreasing one, and vice versa.
7664   bool IncreasingSwapped;
7665   bool ResultSwapped = isMonotonicPredicateImpl(
7666       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7667 
7668   assert(Result == ResultSwapped && "should be able to analyze both!");
7669   if (ResultSwapped)
7670     assert(Increasing == !IncreasingSwapped &&
7671            "monotonicity should flip as we flip the predicate");
7672 #endif
7673 
7674   return Result;
7675 }
7676 
7677 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7678                                                ICmpInst::Predicate Pred,
7679                                                bool &Increasing) {
7680 
7681   // A zero step value for LHS means the induction variable is essentially a
7682   // loop invariant value. We don't really depend on the predicate actually
7683   // flipping from false to true (for increasing predicates, and the other way
7684   // around for decreasing predicates), all we care about is that *if* the
7685   // predicate changes then it only changes from false to true.
7686   //
7687   // A zero step value in itself is not very useful, but there may be places
7688   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7689   // as general as possible.
7690 
7691   switch (Pred) {
7692   default:
7693     return false; // Conservative answer
7694 
7695   case ICmpInst::ICMP_UGT:
7696   case ICmpInst::ICMP_UGE:
7697   case ICmpInst::ICMP_ULT:
7698   case ICmpInst::ICMP_ULE:
7699     if (!LHS->hasNoUnsignedWrap())
7700       return false;
7701 
7702     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7703     return true;
7704 
7705   case ICmpInst::ICMP_SGT:
7706   case ICmpInst::ICMP_SGE:
7707   case ICmpInst::ICMP_SLT:
7708   case ICmpInst::ICMP_SLE: {
7709     if (!LHS->hasNoSignedWrap())
7710       return false;
7711 
7712     const SCEV *Step = LHS->getStepRecurrence(*this);
7713 
7714     if (isKnownNonNegative(Step)) {
7715       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7716       return true;
7717     }
7718 
7719     if (isKnownNonPositive(Step)) {
7720       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7721       return true;
7722     }
7723 
7724     return false;
7725   }
7726 
7727   }
7728 
7729   llvm_unreachable("switch has default clause!");
7730 }
7731 
7732 bool ScalarEvolution::isLoopInvariantPredicate(
7733     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7734     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7735     const SCEV *&InvariantRHS) {
7736 
7737   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7738   if (!isLoopInvariant(RHS, L)) {
7739     if (!isLoopInvariant(LHS, L))
7740       return false;
7741 
7742     std::swap(LHS, RHS);
7743     Pred = ICmpInst::getSwappedPredicate(Pred);
7744   }
7745 
7746   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7747   if (!ArLHS || ArLHS->getLoop() != L)
7748     return false;
7749 
7750   bool Increasing;
7751   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7752     return false;
7753 
7754   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7755   // true as the loop iterates, and the backedge is control dependent on
7756   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7757   //
7758   //   * if the predicate was false in the first iteration then the predicate
7759   //     is never evaluated again, since the loop exits without taking the
7760   //     backedge.
7761   //   * if the predicate was true in the first iteration then it will
7762   //     continue to be true for all future iterations since it is
7763   //     monotonically increasing.
7764   //
7765   // For both the above possibilities, we can replace the loop varying
7766   // predicate with its value on the first iteration of the loop (which is
7767   // loop invariant).
7768   //
7769   // A similar reasoning applies for a monotonically decreasing predicate, by
7770   // replacing true with false and false with true in the above two bullets.
7771 
7772   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7773 
7774   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7775     return false;
7776 
7777   InvariantPred = Pred;
7778   InvariantLHS = ArLHS->getStart();
7779   InvariantRHS = RHS;
7780   return true;
7781 }
7782 
7783 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7784     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7785   if (HasSameValue(LHS, RHS))
7786     return ICmpInst::isTrueWhenEqual(Pred);
7787 
7788   // This code is split out from isKnownPredicate because it is called from
7789   // within isLoopEntryGuardedByCond.
7790 
7791   auto CheckRanges =
7792       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7793     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7794         .contains(RangeLHS);
7795   };
7796 
7797   // The check at the top of the function catches the case where the values are
7798   // known to be equal.
7799   if (Pred == CmpInst::ICMP_EQ)
7800     return false;
7801 
7802   if (Pred == CmpInst::ICMP_NE)
7803     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7804            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7805            isKnownNonZero(getMinusSCEV(LHS, RHS));
7806 
7807   if (CmpInst::isSigned(Pred))
7808     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7809 
7810   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7811 }
7812 
7813 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7814                                                     const SCEV *LHS,
7815                                                     const SCEV *RHS) {
7816 
7817   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7818   // Return Y via OutY.
7819   auto MatchBinaryAddToConst =
7820       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7821              SCEV::NoWrapFlags ExpectedFlags) {
7822     const SCEV *NonConstOp, *ConstOp;
7823     SCEV::NoWrapFlags FlagsPresent;
7824 
7825     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7826         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7827       return false;
7828 
7829     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7830     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7831   };
7832 
7833   APInt C;
7834 
7835   switch (Pred) {
7836   default:
7837     break;
7838 
7839   case ICmpInst::ICMP_SGE:
7840     std::swap(LHS, RHS);
7841   case ICmpInst::ICMP_SLE:
7842     // X s<= (X + C)<nsw> if C >= 0
7843     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7844       return true;
7845 
7846     // (X + C)<nsw> s<= X if C <= 0
7847     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7848         !C.isStrictlyPositive())
7849       return true;
7850     break;
7851 
7852   case ICmpInst::ICMP_SGT:
7853     std::swap(LHS, RHS);
7854   case ICmpInst::ICMP_SLT:
7855     // X s< (X + C)<nsw> if C > 0
7856     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7857         C.isStrictlyPositive())
7858       return true;
7859 
7860     // (X + C)<nsw> s< X if C < 0
7861     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7862       return true;
7863     break;
7864   }
7865 
7866   return false;
7867 }
7868 
7869 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7870                                                    const SCEV *LHS,
7871                                                    const SCEV *RHS) {
7872   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7873     return false;
7874 
7875   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7876   // the stack can result in exponential time complexity.
7877   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7878 
7879   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7880   //
7881   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7882   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7883   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7884   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7885   // use isKnownPredicate later if needed.
7886   return isKnownNonNegative(RHS) &&
7887          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7888          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7889 }
7890 
7891 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7892                                         ICmpInst::Predicate Pred,
7893                                         const SCEV *LHS, const SCEV *RHS) {
7894   // No need to even try if we know the module has no guards.
7895   if (!HasGuards)
7896     return false;
7897 
7898   return any_of(*BB, [&](Instruction &I) {
7899     using namespace llvm::PatternMatch;
7900 
7901     Value *Condition;
7902     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7903                          m_Value(Condition))) &&
7904            isImpliedCond(Pred, LHS, RHS, Condition, false);
7905   });
7906 }
7907 
7908 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7909 /// protected by a conditional between LHS and RHS.  This is used to
7910 /// to eliminate casts.
7911 bool
7912 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7913                                              ICmpInst::Predicate Pred,
7914                                              const SCEV *LHS, const SCEV *RHS) {
7915   // Interpret a null as meaning no loop, where there is obviously no guard
7916   // (interprocedural conditions notwithstanding).
7917   if (!L) return true;
7918 
7919   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7920     return true;
7921 
7922   BasicBlock *Latch = L->getLoopLatch();
7923   if (!Latch)
7924     return false;
7925 
7926   BranchInst *LoopContinuePredicate =
7927     dyn_cast<BranchInst>(Latch->getTerminator());
7928   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7929       isImpliedCond(Pred, LHS, RHS,
7930                     LoopContinuePredicate->getCondition(),
7931                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7932     return true;
7933 
7934   // We don't want more than one activation of the following loops on the stack
7935   // -- that can lead to O(n!) time complexity.
7936   if (WalkingBEDominatingConds)
7937     return false;
7938 
7939   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7940 
7941   // See if we can exploit a trip count to prove the predicate.
7942   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7943   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7944   if (LatchBECount != getCouldNotCompute()) {
7945     // We know that Latch branches back to the loop header exactly
7946     // LatchBECount times.  This means the backdege condition at Latch is
7947     // equivalent to  "{0,+,1} u< LatchBECount".
7948     Type *Ty = LatchBECount->getType();
7949     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7950     const SCEV *LoopCounter =
7951       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7952     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7953                       LatchBECount))
7954       return true;
7955   }
7956 
7957   // Check conditions due to any @llvm.assume intrinsics.
7958   for (auto &AssumeVH : AC.assumptions()) {
7959     if (!AssumeVH)
7960       continue;
7961     auto *CI = cast<CallInst>(AssumeVH);
7962     if (!DT.dominates(CI, Latch->getTerminator()))
7963       continue;
7964 
7965     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7966       return true;
7967   }
7968 
7969   // If the loop is not reachable from the entry block, we risk running into an
7970   // infinite loop as we walk up into the dom tree.  These loops do not matter
7971   // anyway, so we just return a conservative answer when we see them.
7972   if (!DT.isReachableFromEntry(L->getHeader()))
7973     return false;
7974 
7975   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7976     return true;
7977 
7978   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7979        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7980 
7981     assert(DTN && "should reach the loop header before reaching the root!");
7982 
7983     BasicBlock *BB = DTN->getBlock();
7984     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7985       return true;
7986 
7987     BasicBlock *PBB = BB->getSinglePredecessor();
7988     if (!PBB)
7989       continue;
7990 
7991     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7992     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7993       continue;
7994 
7995     Value *Condition = ContinuePredicate->getCondition();
7996 
7997     // If we have an edge `E` within the loop body that dominates the only
7998     // latch, the condition guarding `E` also guards the backedge.  This
7999     // reasoning works only for loops with a single latch.
8000 
8001     BasicBlockEdge DominatingEdge(PBB, BB);
8002     if (DominatingEdge.isSingleEdge()) {
8003       // We're constructively (and conservatively) enumerating edges within the
8004       // loop body that dominate the latch.  The dominator tree better agree
8005       // with us on this:
8006       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8007 
8008       if (isImpliedCond(Pred, LHS, RHS, Condition,
8009                         BB != ContinuePredicate->getSuccessor(0)))
8010         return true;
8011     }
8012   }
8013 
8014   return false;
8015 }
8016 
8017 bool
8018 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8019                                           ICmpInst::Predicate Pred,
8020                                           const SCEV *LHS, const SCEV *RHS) {
8021   // Interpret a null as meaning no loop, where there is obviously no guard
8022   // (interprocedural conditions notwithstanding).
8023   if (!L) return false;
8024 
8025   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8026     return true;
8027 
8028   // Starting at the loop predecessor, climb up the predecessor chain, as long
8029   // as there are predecessors that can be found that have unique successors
8030   // leading to the original header.
8031   for (std::pair<BasicBlock *, BasicBlock *>
8032          Pair(L->getLoopPredecessor(), L->getHeader());
8033        Pair.first;
8034        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8035 
8036     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8037       return true;
8038 
8039     BranchInst *LoopEntryPredicate =
8040       dyn_cast<BranchInst>(Pair.first->getTerminator());
8041     if (!LoopEntryPredicate ||
8042         LoopEntryPredicate->isUnconditional())
8043       continue;
8044 
8045     if (isImpliedCond(Pred, LHS, RHS,
8046                       LoopEntryPredicate->getCondition(),
8047                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8048       return true;
8049   }
8050 
8051   // Check conditions due to any @llvm.assume intrinsics.
8052   for (auto &AssumeVH : AC.assumptions()) {
8053     if (!AssumeVH)
8054       continue;
8055     auto *CI = cast<CallInst>(AssumeVH);
8056     if (!DT.dominates(CI, L->getHeader()))
8057       continue;
8058 
8059     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8060       return true;
8061   }
8062 
8063   return false;
8064 }
8065 
8066 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8067                                     const SCEV *LHS, const SCEV *RHS,
8068                                     Value *FoundCondValue,
8069                                     bool Inverse) {
8070   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8071     return false;
8072 
8073   auto ClearOnExit =
8074       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8075 
8076   // Recursively handle And and Or conditions.
8077   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8078     if (BO->getOpcode() == Instruction::And) {
8079       if (!Inverse)
8080         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8081                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8082     } else if (BO->getOpcode() == Instruction::Or) {
8083       if (Inverse)
8084         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8085                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8086     }
8087   }
8088 
8089   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8090   if (!ICI) return false;
8091 
8092   // Now that we found a conditional branch that dominates the loop or controls
8093   // the loop latch. Check to see if it is the comparison we are looking for.
8094   ICmpInst::Predicate FoundPred;
8095   if (Inverse)
8096     FoundPred = ICI->getInversePredicate();
8097   else
8098     FoundPred = ICI->getPredicate();
8099 
8100   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8101   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8102 
8103   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8104 }
8105 
8106 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8107                                     const SCEV *RHS,
8108                                     ICmpInst::Predicate FoundPred,
8109                                     const SCEV *FoundLHS,
8110                                     const SCEV *FoundRHS) {
8111   // Balance the types.
8112   if (getTypeSizeInBits(LHS->getType()) <
8113       getTypeSizeInBits(FoundLHS->getType())) {
8114     if (CmpInst::isSigned(Pred)) {
8115       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8116       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8117     } else {
8118       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8119       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8120     }
8121   } else if (getTypeSizeInBits(LHS->getType()) >
8122       getTypeSizeInBits(FoundLHS->getType())) {
8123     if (CmpInst::isSigned(FoundPred)) {
8124       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8125       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8126     } else {
8127       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8128       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8129     }
8130   }
8131 
8132   // Canonicalize the query to match the way instcombine will have
8133   // canonicalized the comparison.
8134   if (SimplifyICmpOperands(Pred, LHS, RHS))
8135     if (LHS == RHS)
8136       return CmpInst::isTrueWhenEqual(Pred);
8137   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8138     if (FoundLHS == FoundRHS)
8139       return CmpInst::isFalseWhenEqual(FoundPred);
8140 
8141   // Check to see if we can make the LHS or RHS match.
8142   if (LHS == FoundRHS || RHS == FoundLHS) {
8143     if (isa<SCEVConstant>(RHS)) {
8144       std::swap(FoundLHS, FoundRHS);
8145       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8146     } else {
8147       std::swap(LHS, RHS);
8148       Pred = ICmpInst::getSwappedPredicate(Pred);
8149     }
8150   }
8151 
8152   // Check whether the found predicate is the same as the desired predicate.
8153   if (FoundPred == Pred)
8154     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8155 
8156   // Check whether swapping the found predicate makes it the same as the
8157   // desired predicate.
8158   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8159     if (isa<SCEVConstant>(RHS))
8160       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8161     else
8162       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8163                                    RHS, LHS, FoundLHS, FoundRHS);
8164   }
8165 
8166   // Unsigned comparison is the same as signed comparison when both the operands
8167   // are non-negative.
8168   if (CmpInst::isUnsigned(FoundPred) &&
8169       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8170       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8171     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8172 
8173   // Check if we can make progress by sharpening ranges.
8174   if (FoundPred == ICmpInst::ICMP_NE &&
8175       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8176 
8177     const SCEVConstant *C = nullptr;
8178     const SCEV *V = nullptr;
8179 
8180     if (isa<SCEVConstant>(FoundLHS)) {
8181       C = cast<SCEVConstant>(FoundLHS);
8182       V = FoundRHS;
8183     } else {
8184       C = cast<SCEVConstant>(FoundRHS);
8185       V = FoundLHS;
8186     }
8187 
8188     // The guarding predicate tells us that C != V. If the known range
8189     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8190     // range we consider has to correspond to same signedness as the
8191     // predicate we're interested in folding.
8192 
8193     APInt Min = ICmpInst::isSigned(Pred) ?
8194         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8195 
8196     if (Min == C->getAPInt()) {
8197       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8198       // This is true even if (Min + 1) wraps around -- in case of
8199       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8200 
8201       APInt SharperMin = Min + 1;
8202 
8203       switch (Pred) {
8204         case ICmpInst::ICMP_SGE:
8205         case ICmpInst::ICMP_UGE:
8206           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8207           // RHS, we're done.
8208           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8209                                     getConstant(SharperMin)))
8210             return true;
8211 
8212         case ICmpInst::ICMP_SGT:
8213         case ICmpInst::ICMP_UGT:
8214           // We know from the range information that (V `Pred` Min ||
8215           // V == Min).  We know from the guarding condition that !(V
8216           // == Min).  This gives us
8217           //
8218           //       V `Pred` Min || V == Min && !(V == Min)
8219           //   =>  V `Pred` Min
8220           //
8221           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8222 
8223           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8224             return true;
8225 
8226         default:
8227           // No change
8228           break;
8229       }
8230     }
8231   }
8232 
8233   // Check whether the actual condition is beyond sufficient.
8234   if (FoundPred == ICmpInst::ICMP_EQ)
8235     if (ICmpInst::isTrueWhenEqual(Pred))
8236       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8237         return true;
8238   if (Pred == ICmpInst::ICMP_NE)
8239     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8240       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8241         return true;
8242 
8243   // Otherwise assume the worst.
8244   return false;
8245 }
8246 
8247 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8248                                      const SCEV *&L, const SCEV *&R,
8249                                      SCEV::NoWrapFlags &Flags) {
8250   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8251   if (!AE || AE->getNumOperands() != 2)
8252     return false;
8253 
8254   L = AE->getOperand(0);
8255   R = AE->getOperand(1);
8256   Flags = AE->getNoWrapFlags();
8257   return true;
8258 }
8259 
8260 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8261                                                            const SCEV *Less) {
8262   // We avoid subtracting expressions here because this function is usually
8263   // fairly deep in the call stack (i.e. is called many times).
8264 
8265   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8266     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8267     const auto *MAR = cast<SCEVAddRecExpr>(More);
8268 
8269     if (LAR->getLoop() != MAR->getLoop())
8270       return None;
8271 
8272     // We look at affine expressions only; not for correctness but to keep
8273     // getStepRecurrence cheap.
8274     if (!LAR->isAffine() || !MAR->isAffine())
8275       return None;
8276 
8277     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8278       return None;
8279 
8280     Less = LAR->getStart();
8281     More = MAR->getStart();
8282 
8283     // fall through
8284   }
8285 
8286   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8287     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8288     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8289     return M - L;
8290   }
8291 
8292   const SCEV *L, *R;
8293   SCEV::NoWrapFlags Flags;
8294   if (splitBinaryAdd(Less, L, R, Flags))
8295     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8296       if (R == More)
8297         return -(LC->getAPInt());
8298 
8299   if (splitBinaryAdd(More, L, R, Flags))
8300     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8301       if (R == Less)
8302         return LC->getAPInt();
8303 
8304   return None;
8305 }
8306 
8307 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8308     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8309     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8310   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8311     return false;
8312 
8313   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8314   if (!AddRecLHS)
8315     return false;
8316 
8317   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8318   if (!AddRecFoundLHS)
8319     return false;
8320 
8321   // We'd like to let SCEV reason about control dependencies, so we constrain
8322   // both the inequalities to be about add recurrences on the same loop.  This
8323   // way we can use isLoopEntryGuardedByCond later.
8324 
8325   const Loop *L = AddRecFoundLHS->getLoop();
8326   if (L != AddRecLHS->getLoop())
8327     return false;
8328 
8329   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8330   //
8331   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8332   //                                                                  ... (2)
8333   //
8334   // Informal proof for (2), assuming (1) [*]:
8335   //
8336   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8337   //
8338   // Then
8339   //
8340   //       FoundLHS s< FoundRHS s< INT_MIN - C
8341   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8342   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8343   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8344   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8345   // <=>  FoundLHS + C s< FoundRHS + C
8346   //
8347   // [*]: (1) can be proved by ruling out overflow.
8348   //
8349   // [**]: This can be proved by analyzing all the four possibilities:
8350   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8351   //    (A s>= 0, B s>= 0).
8352   //
8353   // Note:
8354   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8355   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8356   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8357   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8358   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8359   // C)".
8360 
8361   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8362   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8363   if (!LDiff || !RDiff || *LDiff != *RDiff)
8364     return false;
8365 
8366   if (LDiff->isMinValue())
8367     return true;
8368 
8369   APInt FoundRHSLimit;
8370 
8371   if (Pred == CmpInst::ICMP_ULT) {
8372     FoundRHSLimit = -(*RDiff);
8373   } else {
8374     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8375     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8376   }
8377 
8378   // Try to prove (1) or (2), as needed.
8379   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8380                                   getConstant(FoundRHSLimit));
8381 }
8382 
8383 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8384                                             const SCEV *LHS, const SCEV *RHS,
8385                                             const SCEV *FoundLHS,
8386                                             const SCEV *FoundRHS) {
8387   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8388     return true;
8389 
8390   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8391     return true;
8392 
8393   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8394                                      FoundLHS, FoundRHS) ||
8395          // ~x < ~y --> x > y
8396          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8397                                      getNotSCEV(FoundRHS),
8398                                      getNotSCEV(FoundLHS));
8399 }
8400 
8401 
8402 /// If Expr computes ~A, return A else return nullptr
8403 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8404   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8405   if (!Add || Add->getNumOperands() != 2 ||
8406       !Add->getOperand(0)->isAllOnesValue())
8407     return nullptr;
8408 
8409   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8410   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8411       !AddRHS->getOperand(0)->isAllOnesValue())
8412     return nullptr;
8413 
8414   return AddRHS->getOperand(1);
8415 }
8416 
8417 
8418 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8419 template<typename MaxExprType>
8420 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8421                               const SCEV *Candidate) {
8422   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8423   if (!MaxExpr) return false;
8424 
8425   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8426 }
8427 
8428 
8429 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8430 template<typename MaxExprType>
8431 static bool IsMinConsistingOf(ScalarEvolution &SE,
8432                               const SCEV *MaybeMinExpr,
8433                               const SCEV *Candidate) {
8434   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8435   if (!MaybeMaxExpr)
8436     return false;
8437 
8438   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8439 }
8440 
8441 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8442                                            ICmpInst::Predicate Pred,
8443                                            const SCEV *LHS, const SCEV *RHS) {
8444 
8445   // If both sides are affine addrecs for the same loop, with equal
8446   // steps, and we know the recurrences don't wrap, then we only
8447   // need to check the predicate on the starting values.
8448 
8449   if (!ICmpInst::isRelational(Pred))
8450     return false;
8451 
8452   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8453   if (!LAR)
8454     return false;
8455   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8456   if (!RAR)
8457     return false;
8458   if (LAR->getLoop() != RAR->getLoop())
8459     return false;
8460   if (!LAR->isAffine() || !RAR->isAffine())
8461     return false;
8462 
8463   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8464     return false;
8465 
8466   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8467                          SCEV::FlagNSW : SCEV::FlagNUW;
8468   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8469     return false;
8470 
8471   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8472 }
8473 
8474 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8475 /// expression?
8476 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8477                                         ICmpInst::Predicate Pred,
8478                                         const SCEV *LHS, const SCEV *RHS) {
8479   switch (Pred) {
8480   default:
8481     return false;
8482 
8483   case ICmpInst::ICMP_SGE:
8484     std::swap(LHS, RHS);
8485     LLVM_FALLTHROUGH;
8486   case ICmpInst::ICMP_SLE:
8487     return
8488       // min(A, ...) <= A
8489       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8490       // A <= max(A, ...)
8491       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8492 
8493   case ICmpInst::ICMP_UGE:
8494     std::swap(LHS, RHS);
8495     LLVM_FALLTHROUGH;
8496   case ICmpInst::ICMP_ULE:
8497     return
8498       // min(A, ...) <= A
8499       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8500       // A <= max(A, ...)
8501       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8502   }
8503 
8504   llvm_unreachable("covered switch fell through?!");
8505 }
8506 
8507 bool
8508 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8509                                              const SCEV *LHS, const SCEV *RHS,
8510                                              const SCEV *FoundLHS,
8511                                              const SCEV *FoundRHS) {
8512   auto IsKnownPredicateFull =
8513       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8514     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8515            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8516            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8517            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8518   };
8519 
8520   switch (Pred) {
8521   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8522   case ICmpInst::ICMP_EQ:
8523   case ICmpInst::ICMP_NE:
8524     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8525       return true;
8526     break;
8527   case ICmpInst::ICMP_SLT:
8528   case ICmpInst::ICMP_SLE:
8529     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8530         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8531       return true;
8532     break;
8533   case ICmpInst::ICMP_SGT:
8534   case ICmpInst::ICMP_SGE:
8535     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8536         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8537       return true;
8538     break;
8539   case ICmpInst::ICMP_ULT:
8540   case ICmpInst::ICMP_ULE:
8541     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8542         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8543       return true;
8544     break;
8545   case ICmpInst::ICMP_UGT:
8546   case ICmpInst::ICMP_UGE:
8547     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8548         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8549       return true;
8550     break;
8551   }
8552 
8553   return false;
8554 }
8555 
8556 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8557                                                      const SCEV *LHS,
8558                                                      const SCEV *RHS,
8559                                                      const SCEV *FoundLHS,
8560                                                      const SCEV *FoundRHS) {
8561   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8562     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8563     // reduce the compile time impact of this optimization.
8564     return false;
8565 
8566   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8567   if (!Addend)
8568     return false;
8569 
8570   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8571 
8572   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8573   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8574   ConstantRange FoundLHSRange =
8575       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8576 
8577   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8578   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8579 
8580   // We can also compute the range of values for `LHS` that satisfy the
8581   // consequent, "`LHS` `Pred` `RHS`":
8582   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8583   ConstantRange SatisfyingLHSRange =
8584       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8585 
8586   // The antecedent implies the consequent if every value of `LHS` that
8587   // satisfies the antecedent also satisfies the consequent.
8588   return SatisfyingLHSRange.contains(LHSRange);
8589 }
8590 
8591 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8592                                          bool IsSigned, bool NoWrap) {
8593   assert(isKnownPositive(Stride) && "Positive stride expected!");
8594 
8595   if (NoWrap) return false;
8596 
8597   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8598   const SCEV *One = getOne(Stride->getType());
8599 
8600   if (IsSigned) {
8601     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8602     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8603     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8604                                 .getSignedMax();
8605 
8606     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8607     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8608   }
8609 
8610   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8611   APInt MaxValue = APInt::getMaxValue(BitWidth);
8612   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8613                               .getUnsignedMax();
8614 
8615   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8616   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8617 }
8618 
8619 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8620                                          bool IsSigned, bool NoWrap) {
8621   if (NoWrap) return false;
8622 
8623   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8624   const SCEV *One = getOne(Stride->getType());
8625 
8626   if (IsSigned) {
8627     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8628     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8629     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8630                                .getSignedMax();
8631 
8632     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8633     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8634   }
8635 
8636   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8637   APInt MinValue = APInt::getMinValue(BitWidth);
8638   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8639                             .getUnsignedMax();
8640 
8641   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8642   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8643 }
8644 
8645 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8646                                             bool Equality) {
8647   const SCEV *One = getOne(Step->getType());
8648   Delta = Equality ? getAddExpr(Delta, Step)
8649                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8650   return getUDivExpr(Delta, Step);
8651 }
8652 
8653 ScalarEvolution::ExitLimit
8654 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8655                                   const Loop *L, bool IsSigned,
8656                                   bool ControlsExit, bool AllowPredicates) {
8657   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8658   // We handle only IV < Invariant
8659   if (!isLoopInvariant(RHS, L))
8660     return getCouldNotCompute();
8661 
8662   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8663   bool PredicatedIV = false;
8664 
8665   if (!IV && AllowPredicates) {
8666     // Try to make this an AddRec using runtime tests, in the first X
8667     // iterations of this loop, where X is the SCEV expression found by the
8668     // algorithm below.
8669     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8670     PredicatedIV = true;
8671   }
8672 
8673   // Avoid weird loops
8674   if (!IV || IV->getLoop() != L || !IV->isAffine())
8675     return getCouldNotCompute();
8676 
8677   bool NoWrap = ControlsExit &&
8678                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8679 
8680   const SCEV *Stride = IV->getStepRecurrence(*this);
8681 
8682   bool PositiveStride = isKnownPositive(Stride);
8683 
8684   // Avoid negative or zero stride values.
8685   if (!PositiveStride) {
8686     // We can compute the correct backedge taken count for loops with unknown
8687     // strides if we can prove that the loop is not an infinite loop with side
8688     // effects. Here's the loop structure we are trying to handle -
8689     //
8690     // i = start
8691     // do {
8692     //   A[i] = i;
8693     //   i += s;
8694     // } while (i < end);
8695     //
8696     // The backedge taken count for such loops is evaluated as -
8697     // (max(end, start + stride) - start - 1) /u stride
8698     //
8699     // The additional preconditions that we need to check to prove correctness
8700     // of the above formula is as follows -
8701     //
8702     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8703     //    NoWrap flag).
8704     // b) loop is single exit with no side effects.
8705     //
8706     //
8707     // Precondition a) implies that if the stride is negative, this is a single
8708     // trip loop. The backedge taken count formula reduces to zero in this case.
8709     //
8710     // Precondition b) implies that the unknown stride cannot be zero otherwise
8711     // we have UB.
8712     //
8713     // The positive stride case is the same as isKnownPositive(Stride) returning
8714     // true (original behavior of the function).
8715     //
8716     // We want to make sure that the stride is truly unknown as there are edge
8717     // cases where ScalarEvolution propagates no wrap flags to the
8718     // post-increment/decrement IV even though the increment/decrement operation
8719     // itself is wrapping. The computed backedge taken count may be wrong in
8720     // such cases. This is prevented by checking that the stride is not known to
8721     // be either positive or non-positive. For example, no wrap flags are
8722     // propagated to the post-increment IV of this loop with a trip count of 2 -
8723     //
8724     // unsigned char i;
8725     // for(i=127; i<128; i+=129)
8726     //   A[i] = i;
8727     //
8728     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8729         !loopHasNoSideEffects(L))
8730       return getCouldNotCompute();
8731 
8732   } else if (!Stride->isOne() &&
8733              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8734     // Avoid proven overflow cases: this will ensure that the backedge taken
8735     // count will not generate any unsigned overflow. Relaxed no-overflow
8736     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8737     // undefined behaviors like the case of C language.
8738     return getCouldNotCompute();
8739 
8740   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8741                                       : ICmpInst::ICMP_ULT;
8742   const SCEV *Start = IV->getStart();
8743   const SCEV *End = RHS;
8744   // If the backedge is taken at least once, then it will be taken
8745   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8746   // is the LHS value of the less-than comparison the first time it is evaluated
8747   // and End is the RHS.
8748   const SCEV *BECountIfBackedgeTaken =
8749     computeBECount(getMinusSCEV(End, Start), Stride, false);
8750   // If the loop entry is guarded by the result of the backedge test of the
8751   // first loop iteration, then we know the backedge will be taken at least
8752   // once and so the backedge taken count is as above. If not then we use the
8753   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8754   // as if the backedge is taken at least once max(End,Start) is End and so the
8755   // result is as above, and if not max(End,Start) is Start so we get a backedge
8756   // count of zero.
8757   const SCEV *BECount;
8758   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8759     BECount = BECountIfBackedgeTaken;
8760   else {
8761     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
8762     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8763   }
8764 
8765   const SCEV *MaxBECount;
8766   bool MaxOrZero = false;
8767   if (isa<SCEVConstant>(BECount))
8768     MaxBECount = BECount;
8769   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
8770     // If we know exactly how many times the backedge will be taken if it's
8771     // taken at least once, then the backedge count will either be that or
8772     // zero.
8773     MaxBECount = BECountIfBackedgeTaken;
8774     MaxOrZero = true;
8775   } else {
8776     // Calculate the maximum backedge count based on the range of values
8777     // permitted by Start, End, and Stride.
8778     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8779                               : getUnsignedRange(Start).getUnsignedMin();
8780 
8781     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8782 
8783     APInt StrideForMaxBECount;
8784 
8785     if (PositiveStride)
8786       StrideForMaxBECount =
8787         IsSigned ? getSignedRange(Stride).getSignedMin()
8788                  : getUnsignedRange(Stride).getUnsignedMin();
8789     else
8790       // Using a stride of 1 is safe when computing max backedge taken count for
8791       // a loop with unknown stride.
8792       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8793 
8794     APInt Limit =
8795       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8796                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8797 
8798     // Although End can be a MAX expression we estimate MaxEnd considering only
8799     // the case End = RHS. This is safe because in the other case (End - Start)
8800     // is zero, leading to a zero maximum backedge taken count.
8801     APInt MaxEnd =
8802       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8803                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8804 
8805     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8806                                 getConstant(StrideForMaxBECount), false);
8807   }
8808 
8809   if (isa<SCEVCouldNotCompute>(MaxBECount))
8810     MaxBECount = BECount;
8811 
8812   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
8813 }
8814 
8815 ScalarEvolution::ExitLimit
8816 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8817                                      const Loop *L, bool IsSigned,
8818                                      bool ControlsExit, bool AllowPredicates) {
8819   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8820   // We handle only IV > Invariant
8821   if (!isLoopInvariant(RHS, L))
8822     return getCouldNotCompute();
8823 
8824   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8825   if (!IV && AllowPredicates)
8826     // Try to make this an AddRec using runtime tests, in the first X
8827     // iterations of this loop, where X is the SCEV expression found by the
8828     // algorithm below.
8829     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8830 
8831   // Avoid weird loops
8832   if (!IV || IV->getLoop() != L || !IV->isAffine())
8833     return getCouldNotCompute();
8834 
8835   bool NoWrap = ControlsExit &&
8836                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8837 
8838   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8839 
8840   // Avoid negative or zero stride values
8841   if (!isKnownPositive(Stride))
8842     return getCouldNotCompute();
8843 
8844   // Avoid proven overflow cases: this will ensure that the backedge taken count
8845   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8846   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8847   // behaviors like the case of C language.
8848   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8849     return getCouldNotCompute();
8850 
8851   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8852                                       : ICmpInst::ICMP_UGT;
8853 
8854   const SCEV *Start = IV->getStart();
8855   const SCEV *End = RHS;
8856   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8857     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
8858 
8859   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8860 
8861   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8862                             : getUnsignedRange(Start).getUnsignedMax();
8863 
8864   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8865                              : getUnsignedRange(Stride).getUnsignedMin();
8866 
8867   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8868   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8869                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8870 
8871   // Although End can be a MIN expression we estimate MinEnd considering only
8872   // the case End = RHS. This is safe because in the other case (Start - End)
8873   // is zero, leading to a zero maximum backedge taken count.
8874   APInt MinEnd =
8875     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8876              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8877 
8878 
8879   const SCEV *MaxBECount = getCouldNotCompute();
8880   if (isa<SCEVConstant>(BECount))
8881     MaxBECount = BECount;
8882   else
8883     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8884                                 getConstant(MinStride), false);
8885 
8886   if (isa<SCEVCouldNotCompute>(MaxBECount))
8887     MaxBECount = BECount;
8888 
8889   return ExitLimit(BECount, MaxBECount, false, Predicates);
8890 }
8891 
8892 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
8893                                                     ScalarEvolution &SE) const {
8894   if (Range.isFullSet())  // Infinite loop.
8895     return SE.getCouldNotCompute();
8896 
8897   // If the start is a non-zero constant, shift the range to simplify things.
8898   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8899     if (!SC->getValue()->isZero()) {
8900       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8901       Operands[0] = SE.getZero(SC->getType());
8902       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8903                                              getNoWrapFlags(FlagNW));
8904       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8905         return ShiftedAddRec->getNumIterationsInRange(
8906             Range.subtract(SC->getAPInt()), SE);
8907       // This is strange and shouldn't happen.
8908       return SE.getCouldNotCompute();
8909     }
8910 
8911   // The only time we can solve this is when we have all constant indices.
8912   // Otherwise, we cannot determine the overflow conditions.
8913   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8914     return SE.getCouldNotCompute();
8915 
8916   // Okay at this point we know that all elements of the chrec are constants and
8917   // that the start element is zero.
8918 
8919   // First check to see if the range contains zero.  If not, the first
8920   // iteration exits.
8921   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8922   if (!Range.contains(APInt(BitWidth, 0)))
8923     return SE.getZero(getType());
8924 
8925   if (isAffine()) {
8926     // If this is an affine expression then we have this situation:
8927     //   Solve {0,+,A} in Range  ===  Ax in Range
8928 
8929     // We know that zero is in the range.  If A is positive then we know that
8930     // the upper value of the range must be the first possible exit value.
8931     // If A is negative then the lower of the range is the last possible loop
8932     // value.  Also note that we already checked for a full range.
8933     APInt One(BitWidth,1);
8934     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8935     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8936 
8937     // The exit value should be (End+A)/A.
8938     APInt ExitVal = (End + A).udiv(A);
8939     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8940 
8941     // Evaluate at the exit value.  If we really did fall out of the valid
8942     // range, then we computed our trip count, otherwise wrap around or other
8943     // things must have happened.
8944     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8945     if (Range.contains(Val->getValue()))
8946       return SE.getCouldNotCompute();  // Something strange happened
8947 
8948     // Ensure that the previous value is in the range.  This is a sanity check.
8949     assert(Range.contains(
8950            EvaluateConstantChrecAtConstant(this,
8951            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8952            "Linear scev computation is off in a bad way!");
8953     return SE.getConstant(ExitValue);
8954   } else if (isQuadratic()) {
8955     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8956     // quadratic equation to solve it.  To do this, we must frame our problem in
8957     // terms of figuring out when zero is crossed, instead of when
8958     // Range.getUpper() is crossed.
8959     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8960     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8961     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
8962 
8963     // Next, solve the constructed addrec
8964     if (auto Roots =
8965             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
8966       const SCEVConstant *R1 = Roots->first;
8967       const SCEVConstant *R2 = Roots->second;
8968       // Pick the smallest positive root value.
8969       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8970               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8971         if (!CB->getZExtValue())
8972           std::swap(R1, R2); // R1 is the minimum root now.
8973 
8974         // Make sure the root is not off by one.  The returned iteration should
8975         // not be in the range, but the previous one should be.  When solving
8976         // for "X*X < 5", for example, we should not return a root of 2.
8977         ConstantInt *R1Val =
8978             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
8979         if (Range.contains(R1Val->getValue())) {
8980           // The next iteration must be out of the range...
8981           ConstantInt *NextVal =
8982               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
8983 
8984           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8985           if (!Range.contains(R1Val->getValue()))
8986             return SE.getConstant(NextVal);
8987           return SE.getCouldNotCompute(); // Something strange happened
8988         }
8989 
8990         // If R1 was not in the range, then it is a good return value.  Make
8991         // sure that R1-1 WAS in the range though, just in case.
8992         ConstantInt *NextVal =
8993             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
8994         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8995         if (Range.contains(R1Val->getValue()))
8996           return R1;
8997         return SE.getCouldNotCompute(); // Something strange happened
8998       }
8999     }
9000   }
9001 
9002   return SE.getCouldNotCompute();
9003 }
9004 
9005 // Return true when S contains at least an undef value.
9006 static inline bool containsUndefs(const SCEV *S) {
9007   return SCEVExprContains(S, [](const SCEV *S) {
9008     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9009       return isa<UndefValue>(SU->getValue());
9010     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9011       return isa<UndefValue>(SC->getValue());
9012     return false;
9013   });
9014 }
9015 
9016 namespace {
9017 // Collect all steps of SCEV expressions.
9018 struct SCEVCollectStrides {
9019   ScalarEvolution &SE;
9020   SmallVectorImpl<const SCEV *> &Strides;
9021 
9022   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9023       : SE(SE), Strides(S) {}
9024 
9025   bool follow(const SCEV *S) {
9026     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9027       Strides.push_back(AR->getStepRecurrence(SE));
9028     return true;
9029   }
9030   bool isDone() const { return false; }
9031 };
9032 
9033 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9034 struct SCEVCollectTerms {
9035   SmallVectorImpl<const SCEV *> &Terms;
9036 
9037   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9038       : Terms(T) {}
9039 
9040   bool follow(const SCEV *S) {
9041     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9042         isa<SCEVSignExtendExpr>(S)) {
9043       if (!containsUndefs(S))
9044         Terms.push_back(S);
9045 
9046       // Stop recursion: once we collected a term, do not walk its operands.
9047       return false;
9048     }
9049 
9050     // Keep looking.
9051     return true;
9052   }
9053   bool isDone() const { return false; }
9054 };
9055 
9056 // Check if a SCEV contains an AddRecExpr.
9057 struct SCEVHasAddRec {
9058   bool &ContainsAddRec;
9059 
9060   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9061    ContainsAddRec = false;
9062   }
9063 
9064   bool follow(const SCEV *S) {
9065     if (isa<SCEVAddRecExpr>(S)) {
9066       ContainsAddRec = true;
9067 
9068       // Stop recursion: once we collected a term, do not walk its operands.
9069       return false;
9070     }
9071 
9072     // Keep looking.
9073     return true;
9074   }
9075   bool isDone() const { return false; }
9076 };
9077 
9078 // Find factors that are multiplied with an expression that (possibly as a
9079 // subexpression) contains an AddRecExpr. In the expression:
9080 //
9081 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9082 //
9083 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9084 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9085 // parameters as they form a product with an induction variable.
9086 //
9087 // This collector expects all array size parameters to be in the same MulExpr.
9088 // It might be necessary to later add support for collecting parameters that are
9089 // spread over different nested MulExpr.
9090 struct SCEVCollectAddRecMultiplies {
9091   SmallVectorImpl<const SCEV *> &Terms;
9092   ScalarEvolution &SE;
9093 
9094   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9095       : Terms(T), SE(SE) {}
9096 
9097   bool follow(const SCEV *S) {
9098     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9099       bool HasAddRec = false;
9100       SmallVector<const SCEV *, 0> Operands;
9101       for (auto Op : Mul->operands()) {
9102         if (isa<SCEVUnknown>(Op)) {
9103           Operands.push_back(Op);
9104         } else {
9105           bool ContainsAddRec;
9106           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9107           visitAll(Op, ContiansAddRec);
9108           HasAddRec |= ContainsAddRec;
9109         }
9110       }
9111       if (Operands.size() == 0)
9112         return true;
9113 
9114       if (!HasAddRec)
9115         return false;
9116 
9117       Terms.push_back(SE.getMulExpr(Operands));
9118       // Stop recursion: once we collected a term, do not walk its operands.
9119       return false;
9120     }
9121 
9122     // Keep looking.
9123     return true;
9124   }
9125   bool isDone() const { return false; }
9126 };
9127 }
9128 
9129 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9130 /// two places:
9131 ///   1) The strides of AddRec expressions.
9132 ///   2) Unknowns that are multiplied with AddRec expressions.
9133 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9134     SmallVectorImpl<const SCEV *> &Terms) {
9135   SmallVector<const SCEV *, 4> Strides;
9136   SCEVCollectStrides StrideCollector(*this, Strides);
9137   visitAll(Expr, StrideCollector);
9138 
9139   DEBUG({
9140       dbgs() << "Strides:\n";
9141       for (const SCEV *S : Strides)
9142         dbgs() << *S << "\n";
9143     });
9144 
9145   for (const SCEV *S : Strides) {
9146     SCEVCollectTerms TermCollector(Terms);
9147     visitAll(S, TermCollector);
9148   }
9149 
9150   DEBUG({
9151       dbgs() << "Terms:\n";
9152       for (const SCEV *T : Terms)
9153         dbgs() << *T << "\n";
9154     });
9155 
9156   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9157   visitAll(Expr, MulCollector);
9158 }
9159 
9160 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9161                                    SmallVectorImpl<const SCEV *> &Terms,
9162                                    SmallVectorImpl<const SCEV *> &Sizes) {
9163   int Last = Terms.size() - 1;
9164   const SCEV *Step = Terms[Last];
9165 
9166   // End of recursion.
9167   if (Last == 0) {
9168     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9169       SmallVector<const SCEV *, 2> Qs;
9170       for (const SCEV *Op : M->operands())
9171         if (!isa<SCEVConstant>(Op))
9172           Qs.push_back(Op);
9173 
9174       Step = SE.getMulExpr(Qs);
9175     }
9176 
9177     Sizes.push_back(Step);
9178     return true;
9179   }
9180 
9181   for (const SCEV *&Term : Terms) {
9182     // Normalize the terms before the next call to findArrayDimensionsRec.
9183     const SCEV *Q, *R;
9184     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9185 
9186     // Bail out when GCD does not evenly divide one of the terms.
9187     if (!R->isZero())
9188       return false;
9189 
9190     Term = Q;
9191   }
9192 
9193   // Remove all SCEVConstants.
9194   Terms.erase(
9195       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9196       Terms.end());
9197 
9198   if (Terms.size() > 0)
9199     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9200       return false;
9201 
9202   Sizes.push_back(Step);
9203   return true;
9204 }
9205 
9206 
9207 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9208 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9209   for (const SCEV *T : Terms)
9210     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9211       return true;
9212   return false;
9213 }
9214 
9215 // Return the number of product terms in S.
9216 static inline int numberOfTerms(const SCEV *S) {
9217   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9218     return Expr->getNumOperands();
9219   return 1;
9220 }
9221 
9222 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9223   if (isa<SCEVConstant>(T))
9224     return nullptr;
9225 
9226   if (isa<SCEVUnknown>(T))
9227     return T;
9228 
9229   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9230     SmallVector<const SCEV *, 2> Factors;
9231     for (const SCEV *Op : M->operands())
9232       if (!isa<SCEVConstant>(Op))
9233         Factors.push_back(Op);
9234 
9235     return SE.getMulExpr(Factors);
9236   }
9237 
9238   return T;
9239 }
9240 
9241 /// Return the size of an element read or written by Inst.
9242 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9243   Type *Ty;
9244   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9245     Ty = Store->getValueOperand()->getType();
9246   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9247     Ty = Load->getType();
9248   else
9249     return nullptr;
9250 
9251   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9252   return getSizeOfExpr(ETy, Ty);
9253 }
9254 
9255 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9256                                           SmallVectorImpl<const SCEV *> &Sizes,
9257                                           const SCEV *ElementSize) const {
9258   if (Terms.size() < 1 || !ElementSize)
9259     return;
9260 
9261   // Early return when Terms do not contain parameters: we do not delinearize
9262   // non parametric SCEVs.
9263   if (!containsParameters(Terms))
9264     return;
9265 
9266   DEBUG({
9267       dbgs() << "Terms:\n";
9268       for (const SCEV *T : Terms)
9269         dbgs() << *T << "\n";
9270     });
9271 
9272   // Remove duplicates.
9273   std::sort(Terms.begin(), Terms.end());
9274   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9275 
9276   // Put larger terms first.
9277   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9278     return numberOfTerms(LHS) > numberOfTerms(RHS);
9279   });
9280 
9281   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9282 
9283   // Try to divide all terms by the element size. If term is not divisible by
9284   // element size, proceed with the original term.
9285   for (const SCEV *&Term : Terms) {
9286     const SCEV *Q, *R;
9287     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9288     if (!Q->isZero())
9289       Term = Q;
9290   }
9291 
9292   SmallVector<const SCEV *, 4> NewTerms;
9293 
9294   // Remove constant factors.
9295   for (const SCEV *T : Terms)
9296     if (const SCEV *NewT = removeConstantFactors(SE, T))
9297       NewTerms.push_back(NewT);
9298 
9299   DEBUG({
9300       dbgs() << "Terms after sorting:\n";
9301       for (const SCEV *T : NewTerms)
9302         dbgs() << *T << "\n";
9303     });
9304 
9305   if (NewTerms.empty() ||
9306       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9307     Sizes.clear();
9308     return;
9309   }
9310 
9311   // The last element to be pushed into Sizes is the size of an element.
9312   Sizes.push_back(ElementSize);
9313 
9314   DEBUG({
9315       dbgs() << "Sizes:\n";
9316       for (const SCEV *S : Sizes)
9317         dbgs() << *S << "\n";
9318     });
9319 }
9320 
9321 void ScalarEvolution::computeAccessFunctions(
9322     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9323     SmallVectorImpl<const SCEV *> &Sizes) {
9324 
9325   // Early exit in case this SCEV is not an affine multivariate function.
9326   if (Sizes.empty())
9327     return;
9328 
9329   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9330     if (!AR->isAffine())
9331       return;
9332 
9333   const SCEV *Res = Expr;
9334   int Last = Sizes.size() - 1;
9335   for (int i = Last; i >= 0; i--) {
9336     const SCEV *Q, *R;
9337     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9338 
9339     DEBUG({
9340         dbgs() << "Res: " << *Res << "\n";
9341         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9342         dbgs() << "Res divided by Sizes[i]:\n";
9343         dbgs() << "Quotient: " << *Q << "\n";
9344         dbgs() << "Remainder: " << *R << "\n";
9345       });
9346 
9347     Res = Q;
9348 
9349     // Do not record the last subscript corresponding to the size of elements in
9350     // the array.
9351     if (i == Last) {
9352 
9353       // Bail out if the remainder is too complex.
9354       if (isa<SCEVAddRecExpr>(R)) {
9355         Subscripts.clear();
9356         Sizes.clear();
9357         return;
9358       }
9359 
9360       continue;
9361     }
9362 
9363     // Record the access function for the current subscript.
9364     Subscripts.push_back(R);
9365   }
9366 
9367   // Also push in last position the remainder of the last division: it will be
9368   // the access function of the innermost dimension.
9369   Subscripts.push_back(Res);
9370 
9371   std::reverse(Subscripts.begin(), Subscripts.end());
9372 
9373   DEBUG({
9374       dbgs() << "Subscripts:\n";
9375       for (const SCEV *S : Subscripts)
9376         dbgs() << *S << "\n";
9377     });
9378 }
9379 
9380 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9381 /// sizes of an array access. Returns the remainder of the delinearization that
9382 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9383 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9384 /// expressions in the stride and base of a SCEV corresponding to the
9385 /// computation of a GCD (greatest common divisor) of base and stride.  When
9386 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9387 ///
9388 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9389 ///
9390 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9391 ///
9392 ///    for (long i = 0; i < n; i++)
9393 ///      for (long j = 0; j < m; j++)
9394 ///        for (long k = 0; k < o; k++)
9395 ///          A[i][j][k] = 1.0;
9396 ///  }
9397 ///
9398 /// the delinearization input is the following AddRec SCEV:
9399 ///
9400 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9401 ///
9402 /// From this SCEV, we are able to say that the base offset of the access is %A
9403 /// because it appears as an offset that does not divide any of the strides in
9404 /// the loops:
9405 ///
9406 ///  CHECK: Base offset: %A
9407 ///
9408 /// and then SCEV->delinearize determines the size of some of the dimensions of
9409 /// the array as these are the multiples by which the strides are happening:
9410 ///
9411 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9412 ///
9413 /// Note that the outermost dimension remains of UnknownSize because there are
9414 /// no strides that would help identifying the size of the last dimension: when
9415 /// the array has been statically allocated, one could compute the size of that
9416 /// dimension by dividing the overall size of the array by the size of the known
9417 /// dimensions: %m * %o * 8.
9418 ///
9419 /// Finally delinearize provides the access functions for the array reference
9420 /// that does correspond to A[i][j][k] of the above C testcase:
9421 ///
9422 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9423 ///
9424 /// The testcases are checking the output of a function pass:
9425 /// DelinearizationPass that walks through all loads and stores of a function
9426 /// asking for the SCEV of the memory access with respect to all enclosing
9427 /// loops, calling SCEV->delinearize on that and printing the results.
9428 
9429 void ScalarEvolution::delinearize(const SCEV *Expr,
9430                                  SmallVectorImpl<const SCEV *> &Subscripts,
9431                                  SmallVectorImpl<const SCEV *> &Sizes,
9432                                  const SCEV *ElementSize) {
9433   // First step: collect parametric terms.
9434   SmallVector<const SCEV *, 4> Terms;
9435   collectParametricTerms(Expr, Terms);
9436 
9437   if (Terms.empty())
9438     return;
9439 
9440   // Second step: find subscript sizes.
9441   findArrayDimensions(Terms, Sizes, ElementSize);
9442 
9443   if (Sizes.empty())
9444     return;
9445 
9446   // Third step: compute the access functions for each subscript.
9447   computeAccessFunctions(Expr, Subscripts, Sizes);
9448 
9449   if (Subscripts.empty())
9450     return;
9451 
9452   DEBUG({
9453       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9454       dbgs() << "ArrayDecl[UnknownSize]";
9455       for (const SCEV *S : Sizes)
9456         dbgs() << "[" << *S << "]";
9457 
9458       dbgs() << "\nArrayRef";
9459       for (const SCEV *S : Subscripts)
9460         dbgs() << "[" << *S << "]";
9461       dbgs() << "\n";
9462     });
9463 }
9464 
9465 //===----------------------------------------------------------------------===//
9466 //                   SCEVCallbackVH Class Implementation
9467 //===----------------------------------------------------------------------===//
9468 
9469 void ScalarEvolution::SCEVCallbackVH::deleted() {
9470   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9471   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9472     SE->ConstantEvolutionLoopExitValue.erase(PN);
9473   SE->eraseValueFromMap(getValPtr());
9474   // this now dangles!
9475 }
9476 
9477 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9478   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9479 
9480   // Forget all the expressions associated with users of the old value,
9481   // so that future queries will recompute the expressions using the new
9482   // value.
9483   Value *Old = getValPtr();
9484   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9485   SmallPtrSet<User *, 8> Visited;
9486   while (!Worklist.empty()) {
9487     User *U = Worklist.pop_back_val();
9488     // Deleting the Old value will cause this to dangle. Postpone
9489     // that until everything else is done.
9490     if (U == Old)
9491       continue;
9492     if (!Visited.insert(U).second)
9493       continue;
9494     if (PHINode *PN = dyn_cast<PHINode>(U))
9495       SE->ConstantEvolutionLoopExitValue.erase(PN);
9496     SE->eraseValueFromMap(U);
9497     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9498   }
9499   // Delete the Old value.
9500   if (PHINode *PN = dyn_cast<PHINode>(Old))
9501     SE->ConstantEvolutionLoopExitValue.erase(PN);
9502   SE->eraseValueFromMap(Old);
9503   // this now dangles!
9504 }
9505 
9506 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9507   : CallbackVH(V), SE(se) {}
9508 
9509 //===----------------------------------------------------------------------===//
9510 //                   ScalarEvolution Class Implementation
9511 //===----------------------------------------------------------------------===//
9512 
9513 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9514                                  AssumptionCache &AC, DominatorTree &DT,
9515                                  LoopInfo &LI)
9516     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9517       CouldNotCompute(new SCEVCouldNotCompute()),
9518       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9519       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9520       FirstUnknown(nullptr) {
9521 
9522   // To use guards for proving predicates, we need to scan every instruction in
9523   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9524   // time if the IR does not actually contain any calls to
9525   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9526   //
9527   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9528   // to _add_ guards to the module when there weren't any before, and wants
9529   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9530   // efficient in lieu of being smart in that rather obscure case.
9531 
9532   auto *GuardDecl = F.getParent()->getFunction(
9533       Intrinsic::getName(Intrinsic::experimental_guard));
9534   HasGuards = GuardDecl && !GuardDecl->use_empty();
9535 }
9536 
9537 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9538     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9539       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9540       ValueExprMap(std::move(Arg.ValueExprMap)),
9541       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9542       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9543       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9544       PredicatedBackedgeTakenCounts(
9545           std::move(Arg.PredicatedBackedgeTakenCounts)),
9546       ConstantEvolutionLoopExitValue(
9547           std::move(Arg.ConstantEvolutionLoopExitValue)),
9548       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9549       LoopDispositions(std::move(Arg.LoopDispositions)),
9550       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9551       BlockDispositions(std::move(Arg.BlockDispositions)),
9552       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9553       SignedRanges(std::move(Arg.SignedRanges)),
9554       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9555       UniquePreds(std::move(Arg.UniquePreds)),
9556       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9557       FirstUnknown(Arg.FirstUnknown) {
9558   Arg.FirstUnknown = nullptr;
9559 }
9560 
9561 ScalarEvolution::~ScalarEvolution() {
9562   // Iterate through all the SCEVUnknown instances and call their
9563   // destructors, so that they release their references to their values.
9564   for (SCEVUnknown *U = FirstUnknown; U;) {
9565     SCEVUnknown *Tmp = U;
9566     U = U->Next;
9567     Tmp->~SCEVUnknown();
9568   }
9569   FirstUnknown = nullptr;
9570 
9571   ExprValueMap.clear();
9572   ValueExprMap.clear();
9573   HasRecMap.clear();
9574 
9575   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9576   // that a loop had multiple computable exits.
9577   for (auto &BTCI : BackedgeTakenCounts)
9578     BTCI.second.clear();
9579   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9580     BTCI.second.clear();
9581 
9582   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9583   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9584   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9585 }
9586 
9587 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9588   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9589 }
9590 
9591 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9592                           const Loop *L) {
9593   // Print all inner loops first
9594   for (Loop *I : *L)
9595     PrintLoopInfo(OS, SE, I);
9596 
9597   OS << "Loop ";
9598   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9599   OS << ": ";
9600 
9601   SmallVector<BasicBlock *, 8> ExitBlocks;
9602   L->getExitBlocks(ExitBlocks);
9603   if (ExitBlocks.size() != 1)
9604     OS << "<multiple exits> ";
9605 
9606   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9607     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9608   } else {
9609     OS << "Unpredictable backedge-taken count. ";
9610   }
9611 
9612   OS << "\n"
9613         "Loop ";
9614   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9615   OS << ": ";
9616 
9617   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9618     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9619     if (SE->isBackedgeTakenCountMaxOrZero(L))
9620       OS << ", actual taken count either this or zero.";
9621   } else {
9622     OS << "Unpredictable max backedge-taken count. ";
9623   }
9624 
9625   OS << "\n"
9626         "Loop ";
9627   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9628   OS << ": ";
9629 
9630   SCEVUnionPredicate Pred;
9631   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9632   if (!isa<SCEVCouldNotCompute>(PBT)) {
9633     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9634     OS << " Predicates:\n";
9635     Pred.print(OS, 4);
9636   } else {
9637     OS << "Unpredictable predicated backedge-taken count. ";
9638   }
9639   OS << "\n";
9640 }
9641 
9642 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9643   switch (LD) {
9644   case ScalarEvolution::LoopVariant:
9645     return "Variant";
9646   case ScalarEvolution::LoopInvariant:
9647     return "Invariant";
9648   case ScalarEvolution::LoopComputable:
9649     return "Computable";
9650   }
9651   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9652 }
9653 
9654 void ScalarEvolution::print(raw_ostream &OS) const {
9655   // ScalarEvolution's implementation of the print method is to print
9656   // out SCEV values of all instructions that are interesting. Doing
9657   // this potentially causes it to create new SCEV objects though,
9658   // which technically conflicts with the const qualifier. This isn't
9659   // observable from outside the class though, so casting away the
9660   // const isn't dangerous.
9661   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9662 
9663   OS << "Classifying expressions for: ";
9664   F.printAsOperand(OS, /*PrintType=*/false);
9665   OS << "\n";
9666   for (Instruction &I : instructions(F))
9667     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9668       OS << I << '\n';
9669       OS << "  -->  ";
9670       const SCEV *SV = SE.getSCEV(&I);
9671       SV->print(OS);
9672       if (!isa<SCEVCouldNotCompute>(SV)) {
9673         OS << " U: ";
9674         SE.getUnsignedRange(SV).print(OS);
9675         OS << " S: ";
9676         SE.getSignedRange(SV).print(OS);
9677       }
9678 
9679       const Loop *L = LI.getLoopFor(I.getParent());
9680 
9681       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9682       if (AtUse != SV) {
9683         OS << "  -->  ";
9684         AtUse->print(OS);
9685         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9686           OS << " U: ";
9687           SE.getUnsignedRange(AtUse).print(OS);
9688           OS << " S: ";
9689           SE.getSignedRange(AtUse).print(OS);
9690         }
9691       }
9692 
9693       if (L) {
9694         OS << "\t\t" "Exits: ";
9695         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9696         if (!SE.isLoopInvariant(ExitValue, L)) {
9697           OS << "<<Unknown>>";
9698         } else {
9699           OS << *ExitValue;
9700         }
9701 
9702         bool First = true;
9703         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9704           if (First) {
9705             OS << "\t\t" "LoopDispositions: { ";
9706             First = false;
9707           } else {
9708             OS << ", ";
9709           }
9710 
9711           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9712           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9713         }
9714 
9715         for (auto *InnerL : depth_first(L)) {
9716           if (InnerL == L)
9717             continue;
9718           if (First) {
9719             OS << "\t\t" "LoopDispositions: { ";
9720             First = false;
9721           } else {
9722             OS << ", ";
9723           }
9724 
9725           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9726           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9727         }
9728 
9729         OS << " }";
9730       }
9731 
9732       OS << "\n";
9733     }
9734 
9735   OS << "Determining loop execution counts for: ";
9736   F.printAsOperand(OS, /*PrintType=*/false);
9737   OS << "\n";
9738   for (Loop *I : LI)
9739     PrintLoopInfo(OS, &SE, I);
9740 }
9741 
9742 ScalarEvolution::LoopDisposition
9743 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9744   auto &Values = LoopDispositions[S];
9745   for (auto &V : Values) {
9746     if (V.getPointer() == L)
9747       return V.getInt();
9748   }
9749   Values.emplace_back(L, LoopVariant);
9750   LoopDisposition D = computeLoopDisposition(S, L);
9751   auto &Values2 = LoopDispositions[S];
9752   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9753     if (V.getPointer() == L) {
9754       V.setInt(D);
9755       break;
9756     }
9757   }
9758   return D;
9759 }
9760 
9761 ScalarEvolution::LoopDisposition
9762 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9763   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9764   case scConstant:
9765     return LoopInvariant;
9766   case scTruncate:
9767   case scZeroExtend:
9768   case scSignExtend:
9769     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9770   case scAddRecExpr: {
9771     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9772 
9773     // If L is the addrec's loop, it's computable.
9774     if (AR->getLoop() == L)
9775       return LoopComputable;
9776 
9777     // Add recurrences are never invariant in the function-body (null loop).
9778     if (!L)
9779       return LoopVariant;
9780 
9781     // This recurrence is variant w.r.t. L if L contains AR's loop.
9782     if (L->contains(AR->getLoop()))
9783       return LoopVariant;
9784 
9785     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9786     if (AR->getLoop()->contains(L))
9787       return LoopInvariant;
9788 
9789     // This recurrence is variant w.r.t. L if any of its operands
9790     // are variant.
9791     for (auto *Op : AR->operands())
9792       if (!isLoopInvariant(Op, L))
9793         return LoopVariant;
9794 
9795     // Otherwise it's loop-invariant.
9796     return LoopInvariant;
9797   }
9798   case scAddExpr:
9799   case scMulExpr:
9800   case scUMaxExpr:
9801   case scSMaxExpr: {
9802     bool HasVarying = false;
9803     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9804       LoopDisposition D = getLoopDisposition(Op, L);
9805       if (D == LoopVariant)
9806         return LoopVariant;
9807       if (D == LoopComputable)
9808         HasVarying = true;
9809     }
9810     return HasVarying ? LoopComputable : LoopInvariant;
9811   }
9812   case scUDivExpr: {
9813     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9814     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9815     if (LD == LoopVariant)
9816       return LoopVariant;
9817     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9818     if (RD == LoopVariant)
9819       return LoopVariant;
9820     return (LD == LoopInvariant && RD == LoopInvariant) ?
9821            LoopInvariant : LoopComputable;
9822   }
9823   case scUnknown:
9824     // All non-instruction values are loop invariant.  All instructions are loop
9825     // invariant if they are not contained in the specified loop.
9826     // Instructions are never considered invariant in the function body
9827     // (null loop) because they are defined within the "loop".
9828     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9829       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9830     return LoopInvariant;
9831   case scCouldNotCompute:
9832     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9833   }
9834   llvm_unreachable("Unknown SCEV kind!");
9835 }
9836 
9837 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9838   return getLoopDisposition(S, L) == LoopInvariant;
9839 }
9840 
9841 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9842   return getLoopDisposition(S, L) == LoopComputable;
9843 }
9844 
9845 ScalarEvolution::BlockDisposition
9846 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9847   auto &Values = BlockDispositions[S];
9848   for (auto &V : Values) {
9849     if (V.getPointer() == BB)
9850       return V.getInt();
9851   }
9852   Values.emplace_back(BB, DoesNotDominateBlock);
9853   BlockDisposition D = computeBlockDisposition(S, BB);
9854   auto &Values2 = BlockDispositions[S];
9855   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9856     if (V.getPointer() == BB) {
9857       V.setInt(D);
9858       break;
9859     }
9860   }
9861   return D;
9862 }
9863 
9864 ScalarEvolution::BlockDisposition
9865 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9866   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9867   case scConstant:
9868     return ProperlyDominatesBlock;
9869   case scTruncate:
9870   case scZeroExtend:
9871   case scSignExtend:
9872     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9873   case scAddRecExpr: {
9874     // This uses a "dominates" query instead of "properly dominates" query
9875     // to test for proper dominance too, because the instruction which
9876     // produces the addrec's value is a PHI, and a PHI effectively properly
9877     // dominates its entire containing block.
9878     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9879     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9880       return DoesNotDominateBlock;
9881 
9882     // Fall through into SCEVNAryExpr handling.
9883     LLVM_FALLTHROUGH;
9884   }
9885   case scAddExpr:
9886   case scMulExpr:
9887   case scUMaxExpr:
9888   case scSMaxExpr: {
9889     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9890     bool Proper = true;
9891     for (const SCEV *NAryOp : NAry->operands()) {
9892       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9893       if (D == DoesNotDominateBlock)
9894         return DoesNotDominateBlock;
9895       if (D == DominatesBlock)
9896         Proper = false;
9897     }
9898     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9899   }
9900   case scUDivExpr: {
9901     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9902     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9903     BlockDisposition LD = getBlockDisposition(LHS, BB);
9904     if (LD == DoesNotDominateBlock)
9905       return DoesNotDominateBlock;
9906     BlockDisposition RD = getBlockDisposition(RHS, BB);
9907     if (RD == DoesNotDominateBlock)
9908       return DoesNotDominateBlock;
9909     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9910       ProperlyDominatesBlock : DominatesBlock;
9911   }
9912   case scUnknown:
9913     if (Instruction *I =
9914           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9915       if (I->getParent() == BB)
9916         return DominatesBlock;
9917       if (DT.properlyDominates(I->getParent(), BB))
9918         return ProperlyDominatesBlock;
9919       return DoesNotDominateBlock;
9920     }
9921     return ProperlyDominatesBlock;
9922   case scCouldNotCompute:
9923     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9924   }
9925   llvm_unreachable("Unknown SCEV kind!");
9926 }
9927 
9928 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9929   return getBlockDisposition(S, BB) >= DominatesBlock;
9930 }
9931 
9932 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9933   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9934 }
9935 
9936 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9937   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
9938 }
9939 
9940 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9941   ValuesAtScopes.erase(S);
9942   LoopDispositions.erase(S);
9943   BlockDispositions.erase(S);
9944   UnsignedRanges.erase(S);
9945   SignedRanges.erase(S);
9946   ExprValueMap.erase(S);
9947   HasRecMap.erase(S);
9948 
9949   auto RemoveSCEVFromBackedgeMap =
9950       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9951         for (auto I = Map.begin(), E = Map.end(); I != E;) {
9952           BackedgeTakenInfo &BEInfo = I->second;
9953           if (BEInfo.hasOperand(S, this)) {
9954             BEInfo.clear();
9955             Map.erase(I++);
9956           } else
9957             ++I;
9958         }
9959       };
9960 
9961   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9962   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
9963 }
9964 
9965 typedef DenseMap<const Loop *, std::string> VerifyMap;
9966 
9967 /// replaceSubString - Replaces all occurrences of From in Str with To.
9968 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9969   size_t Pos = 0;
9970   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9971     Str.replace(Pos, From.size(), To.data(), To.size());
9972     Pos += To.size();
9973   }
9974 }
9975 
9976 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9977 static void
9978 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9979   std::string &S = Map[L];
9980   if (S.empty()) {
9981     raw_string_ostream OS(S);
9982     SE.getBackedgeTakenCount(L)->print(OS);
9983 
9984     // false and 0 are semantically equivalent. This can happen in dead loops.
9985     replaceSubString(OS.str(), "false", "0");
9986     // Remove wrap flags, their use in SCEV is highly fragile.
9987     // FIXME: Remove this when SCEV gets smarter about them.
9988     replaceSubString(OS.str(), "<nw>", "");
9989     replaceSubString(OS.str(), "<nsw>", "");
9990     replaceSubString(OS.str(), "<nuw>", "");
9991   }
9992 
9993   for (auto *R : reverse(*L))
9994     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
9995 }
9996 
9997 void ScalarEvolution::verify() const {
9998   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9999 
10000   // Gather stringified backedge taken counts for all loops using SCEV's caches.
10001   // FIXME: It would be much better to store actual values instead of strings,
10002   //        but SCEV pointers will change if we drop the caches.
10003   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
10004   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10005     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
10006 
10007   // Gather stringified backedge taken counts for all loops using a fresh
10008   // ScalarEvolution object.
10009   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10010   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
10011     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
10012 
10013   // Now compare whether they're the same with and without caches. This allows
10014   // verifying that no pass changed the cache.
10015   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
10016          "New loops suddenly appeared!");
10017 
10018   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
10019                            OldE = BackedgeDumpsOld.end(),
10020                            NewI = BackedgeDumpsNew.begin();
10021        OldI != OldE; ++OldI, ++NewI) {
10022     assert(OldI->first == NewI->first && "Loop order changed!");
10023 
10024     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
10025     // changes.
10026     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
10027     // means that a pass is buggy or SCEV has to learn a new pattern but is
10028     // usually not harmful.
10029     if (OldI->second != NewI->second &&
10030         OldI->second.find("undef") == std::string::npos &&
10031         NewI->second.find("undef") == std::string::npos &&
10032         OldI->second != "***COULDNOTCOMPUTE***" &&
10033         NewI->second != "***COULDNOTCOMPUTE***") {
10034       dbgs() << "SCEVValidator: SCEV for loop '"
10035              << OldI->first->getHeader()->getName()
10036              << "' changed from '" << OldI->second
10037              << "' to '" << NewI->second << "'!\n";
10038       std::abort();
10039     }
10040   }
10041 
10042   // TODO: Verify more things.
10043 }
10044 
10045 bool ScalarEvolution::invalidate(
10046     Function &F, const PreservedAnalyses &PA,
10047     FunctionAnalysisManager::Invalidator &Inv) {
10048   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10049   // of its dependencies is invalidated.
10050   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10051   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10052          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10053          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10054          Inv.invalidate<LoopAnalysis>(F, PA);
10055 }
10056 
10057 AnalysisKey ScalarEvolutionAnalysis::Key;
10058 
10059 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10060                                              FunctionAnalysisManager &AM) {
10061   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10062                          AM.getResult<AssumptionAnalysis>(F),
10063                          AM.getResult<DominatorTreeAnalysis>(F),
10064                          AM.getResult<LoopAnalysis>(F));
10065 }
10066 
10067 PreservedAnalyses
10068 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10069   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10070   return PreservedAnalyses::all();
10071 }
10072 
10073 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10074                       "Scalar Evolution Analysis", false, true)
10075 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10076 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10077 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10078 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10079 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10080                     "Scalar Evolution Analysis", false, true)
10081 char ScalarEvolutionWrapperPass::ID = 0;
10082 
10083 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10084   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10085 }
10086 
10087 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10088   SE.reset(new ScalarEvolution(
10089       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10090       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10091       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10092       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10093   return false;
10094 }
10095 
10096 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10097 
10098 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10099   SE->print(OS);
10100 }
10101 
10102 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10103   if (!VerifySCEV)
10104     return;
10105 
10106   SE->verify();
10107 }
10108 
10109 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10110   AU.setPreservesAll();
10111   AU.addRequiredTransitive<AssumptionCacheTracker>();
10112   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10113   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10114   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10115 }
10116 
10117 const SCEVPredicate *
10118 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10119                                    const SCEVConstant *RHS) {
10120   FoldingSetNodeID ID;
10121   // Unique this node based on the arguments
10122   ID.AddInteger(SCEVPredicate::P_Equal);
10123   ID.AddPointer(LHS);
10124   ID.AddPointer(RHS);
10125   void *IP = nullptr;
10126   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10127     return S;
10128   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10129       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10130   UniquePreds.InsertNode(Eq, IP);
10131   return Eq;
10132 }
10133 
10134 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10135     const SCEVAddRecExpr *AR,
10136     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10137   FoldingSetNodeID ID;
10138   // Unique this node based on the arguments
10139   ID.AddInteger(SCEVPredicate::P_Wrap);
10140   ID.AddPointer(AR);
10141   ID.AddInteger(AddedFlags);
10142   void *IP = nullptr;
10143   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10144     return S;
10145   auto *OF = new (SCEVAllocator)
10146       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10147   UniquePreds.InsertNode(OF, IP);
10148   return OF;
10149 }
10150 
10151 namespace {
10152 
10153 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10154 public:
10155   /// Rewrites \p S in the context of a loop L and the SCEV predication
10156   /// infrastructure.
10157   ///
10158   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10159   /// equivalences present in \p Pred.
10160   ///
10161   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10162   /// \p NewPreds such that the result will be an AddRecExpr.
10163   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10164                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10165                              SCEVUnionPredicate *Pred) {
10166     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10167     return Rewriter.visit(S);
10168   }
10169 
10170   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10171                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10172                         SCEVUnionPredicate *Pred)
10173       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10174 
10175   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10176     if (Pred) {
10177       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10178       for (auto *Pred : ExprPreds)
10179         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10180           if (IPred->getLHS() == Expr)
10181             return IPred->getRHS();
10182     }
10183 
10184     return Expr;
10185   }
10186 
10187   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10188     const SCEV *Operand = visit(Expr->getOperand());
10189     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10190     if (AR && AR->getLoop() == L && AR->isAffine()) {
10191       // This couldn't be folded because the operand didn't have the nuw
10192       // flag. Add the nusw flag as an assumption that we could make.
10193       const SCEV *Step = AR->getStepRecurrence(SE);
10194       Type *Ty = Expr->getType();
10195       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10196         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10197                                 SE.getSignExtendExpr(Step, Ty), L,
10198                                 AR->getNoWrapFlags());
10199     }
10200     return SE.getZeroExtendExpr(Operand, Expr->getType());
10201   }
10202 
10203   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10204     const SCEV *Operand = visit(Expr->getOperand());
10205     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10206     if (AR && AR->getLoop() == L && AR->isAffine()) {
10207       // This couldn't be folded because the operand didn't have the nsw
10208       // flag. Add the nssw flag as an assumption that we could make.
10209       const SCEV *Step = AR->getStepRecurrence(SE);
10210       Type *Ty = Expr->getType();
10211       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10212         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10213                                 SE.getSignExtendExpr(Step, Ty), L,
10214                                 AR->getNoWrapFlags());
10215     }
10216     return SE.getSignExtendExpr(Operand, Expr->getType());
10217   }
10218 
10219 private:
10220   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10221                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10222     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10223     if (!NewPreds) {
10224       // Check if we've already made this assumption.
10225       return Pred && Pred->implies(A);
10226     }
10227     NewPreds->insert(A);
10228     return true;
10229   }
10230 
10231   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10232   SCEVUnionPredicate *Pred;
10233   const Loop *L;
10234 };
10235 } // end anonymous namespace
10236 
10237 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10238                                                    SCEVUnionPredicate &Preds) {
10239   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10240 }
10241 
10242 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10243     const SCEV *S, const Loop *L,
10244     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10245 
10246   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10247   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10248   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10249 
10250   if (!AddRec)
10251     return nullptr;
10252 
10253   // Since the transformation was successful, we can now transfer the SCEV
10254   // predicates.
10255   for (auto *P : TransformPreds)
10256     Preds.insert(P);
10257 
10258   return AddRec;
10259 }
10260 
10261 /// SCEV predicates
10262 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10263                              SCEVPredicateKind Kind)
10264     : FastID(ID), Kind(Kind) {}
10265 
10266 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10267                                        const SCEVUnknown *LHS,
10268                                        const SCEVConstant *RHS)
10269     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10270 
10271 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10272   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10273 
10274   if (!Op)
10275     return false;
10276 
10277   return Op->LHS == LHS && Op->RHS == RHS;
10278 }
10279 
10280 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10281 
10282 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10283 
10284 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10285   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10286 }
10287 
10288 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10289                                      const SCEVAddRecExpr *AR,
10290                                      IncrementWrapFlags Flags)
10291     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10292 
10293 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10294 
10295 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10296   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10297 
10298   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10299 }
10300 
10301 bool SCEVWrapPredicate::isAlwaysTrue() const {
10302   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10303   IncrementWrapFlags IFlags = Flags;
10304 
10305   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10306     IFlags = clearFlags(IFlags, IncrementNSSW);
10307 
10308   return IFlags == IncrementAnyWrap;
10309 }
10310 
10311 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10312   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10313   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10314     OS << "<nusw>";
10315   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10316     OS << "<nssw>";
10317   OS << "\n";
10318 }
10319 
10320 SCEVWrapPredicate::IncrementWrapFlags
10321 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10322                                    ScalarEvolution &SE) {
10323   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10324   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10325 
10326   // We can safely transfer the NSW flag as NSSW.
10327   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10328     ImpliedFlags = IncrementNSSW;
10329 
10330   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10331     // If the increment is positive, the SCEV NUW flag will also imply the
10332     // WrapPredicate NUSW flag.
10333     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10334       if (Step->getValue()->getValue().isNonNegative())
10335         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10336   }
10337 
10338   return ImpliedFlags;
10339 }
10340 
10341 /// Union predicates don't get cached so create a dummy set ID for it.
10342 SCEVUnionPredicate::SCEVUnionPredicate()
10343     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10344 
10345 bool SCEVUnionPredicate::isAlwaysTrue() const {
10346   return all_of(Preds,
10347                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10348 }
10349 
10350 ArrayRef<const SCEVPredicate *>
10351 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10352   auto I = SCEVToPreds.find(Expr);
10353   if (I == SCEVToPreds.end())
10354     return ArrayRef<const SCEVPredicate *>();
10355   return I->second;
10356 }
10357 
10358 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10359   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10360     return all_of(Set->Preds,
10361                   [this](const SCEVPredicate *I) { return this->implies(I); });
10362 
10363   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10364   if (ScevPredsIt == SCEVToPreds.end())
10365     return false;
10366   auto &SCEVPreds = ScevPredsIt->second;
10367 
10368   return any_of(SCEVPreds,
10369                 [N](const SCEVPredicate *I) { return I->implies(N); });
10370 }
10371 
10372 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10373 
10374 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10375   for (auto Pred : Preds)
10376     Pred->print(OS, Depth);
10377 }
10378 
10379 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10380   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10381     for (auto Pred : Set->Preds)
10382       add(Pred);
10383     return;
10384   }
10385 
10386   if (implies(N))
10387     return;
10388 
10389   const SCEV *Key = N->getExpr();
10390   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10391                 " associated expression!");
10392 
10393   SCEVToPreds[Key].push_back(N);
10394   Preds.push_back(N);
10395 }
10396 
10397 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10398                                                      Loop &L)
10399     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10400 
10401 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10402   const SCEV *Expr = SE.getSCEV(V);
10403   RewriteEntry &Entry = RewriteMap[Expr];
10404 
10405   // If we already have an entry and the version matches, return it.
10406   if (Entry.second && Generation == Entry.first)
10407     return Entry.second;
10408 
10409   // We found an entry but it's stale. Rewrite the stale entry
10410   // according to the current predicate.
10411   if (Entry.second)
10412     Expr = Entry.second;
10413 
10414   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10415   Entry = {Generation, NewSCEV};
10416 
10417   return NewSCEV;
10418 }
10419 
10420 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10421   if (!BackedgeCount) {
10422     SCEVUnionPredicate BackedgePred;
10423     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10424     addPredicate(BackedgePred);
10425   }
10426   return BackedgeCount;
10427 }
10428 
10429 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10430   if (Preds.implies(&Pred))
10431     return;
10432   Preds.add(&Pred);
10433   updateGeneration();
10434 }
10435 
10436 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10437   return Preds;
10438 }
10439 
10440 void PredicatedScalarEvolution::updateGeneration() {
10441   // If the generation number wrapped recompute everything.
10442   if (++Generation == 0) {
10443     for (auto &II : RewriteMap) {
10444       const SCEV *Rewritten = II.second.second;
10445       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10446     }
10447   }
10448 }
10449 
10450 void PredicatedScalarEvolution::setNoOverflow(
10451     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10452   const SCEV *Expr = getSCEV(V);
10453   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10454 
10455   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10456 
10457   // Clear the statically implied flags.
10458   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10459   addPredicate(*SE.getWrapPredicate(AR, Flags));
10460 
10461   auto II = FlagsMap.insert({V, Flags});
10462   if (!II.second)
10463     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10464 }
10465 
10466 bool PredicatedScalarEvolution::hasNoOverflow(
10467     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10468   const SCEV *Expr = getSCEV(V);
10469   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10470 
10471   Flags = SCEVWrapPredicate::clearFlags(
10472       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10473 
10474   auto II = FlagsMap.find(V);
10475 
10476   if (II != FlagsMap.end())
10477     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10478 
10479   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10480 }
10481 
10482 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10483   const SCEV *Expr = this->getSCEV(V);
10484   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10485   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10486 
10487   if (!New)
10488     return nullptr;
10489 
10490   for (auto *P : NewPreds)
10491     Preds.add(P);
10492 
10493   updateGeneration();
10494   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10495   return New;
10496 }
10497 
10498 PredicatedScalarEvolution::PredicatedScalarEvolution(
10499     const PredicatedScalarEvolution &Init)
10500     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10501       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10502   for (const auto &I : Init.FlagsMap)
10503     FlagsMap.insert(I);
10504 }
10505 
10506 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10507   // For each block.
10508   for (auto *BB : L.getBlocks())
10509     for (auto &I : *BB) {
10510       if (!SE.isSCEVable(I.getType()))
10511         continue;
10512 
10513       auto *Expr = SE.getSCEV(&I);
10514       auto II = RewriteMap.find(Expr);
10515 
10516       if (II == RewriteMap.end())
10517         continue;
10518 
10519       // Don't print things that are not interesting.
10520       if (II->second.second == Expr)
10521         continue;
10522 
10523       OS.indent(Depth) << "[PSE]" << I << ":\n";
10524       OS.indent(Depth + 2) << *Expr << "\n";
10525       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10526     }
10527 }
10528