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 SCEV *B,
7044                                                ScalarEvolution &SE) {
7045   uint32_t BW = A.getBitWidth();
7046   assert(BW == SE.getTypeSizeInBits(B->getType()));
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 (SE.GetMinTrailingZeros(B) < 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   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7079   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7080 }
7081 
7082 /// Find the roots of the quadratic equation for the given quadratic chrec
7083 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7084 /// two SCEVCouldNotCompute objects.
7085 ///
7086 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7087 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7088   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7089   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7090   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7091   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7092 
7093   // We currently can only solve this if the coefficients are constants.
7094   if (!LC || !MC || !NC)
7095     return None;
7096 
7097   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7098   const APInt &L = LC->getAPInt();
7099   const APInt &M = MC->getAPInt();
7100   const APInt &N = NC->getAPInt();
7101   APInt Two(BitWidth, 2);
7102   APInt Four(BitWidth, 4);
7103 
7104   {
7105     using namespace APIntOps;
7106     const APInt& C = L;
7107     // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7108     // The B coefficient is M-N/2
7109     APInt B(M);
7110     B -= sdiv(N,Two);
7111 
7112     // The A coefficient is N/2
7113     APInt A(N.sdiv(Two));
7114 
7115     // Compute the B^2-4ac term.
7116     APInt SqrtTerm(B);
7117     SqrtTerm *= B;
7118     SqrtTerm -= Four * (A * C);
7119 
7120     if (SqrtTerm.isNegative()) {
7121       // The loop is provably infinite.
7122       return None;
7123     }
7124 
7125     // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7126     // integer value or else APInt::sqrt() will assert.
7127     APInt SqrtVal(SqrtTerm.sqrt());
7128 
7129     // Compute the two solutions for the quadratic formula.
7130     // The divisions must be performed as signed divisions.
7131     APInt NegB(-B);
7132     APInt TwoA(A << 1);
7133     if (TwoA.isMinValue())
7134       return None;
7135 
7136     LLVMContext &Context = SE.getContext();
7137 
7138     ConstantInt *Solution1 =
7139       ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7140     ConstantInt *Solution2 =
7141       ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7142 
7143     return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7144                           cast<SCEVConstant>(SE.getConstant(Solution2)));
7145   } // end APIntOps namespace
7146 }
7147 
7148 ScalarEvolution::ExitLimit
7149 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7150                               bool AllowPredicates) {
7151 
7152   // This is only used for loops with a "x != y" exit test. The exit condition
7153   // is now expressed as a single expression, V = x-y. So the exit test is
7154   // effectively V != 0.  We know and take advantage of the fact that this
7155   // expression only being used in a comparison by zero context.
7156 
7157   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7158   // If the value is a constant
7159   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7160     // If the value is already zero, the branch will execute zero times.
7161     if (C->getValue()->isZero()) return C;
7162     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7163   }
7164 
7165   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7166   if (!AddRec && AllowPredicates)
7167     // Try to make this an AddRec using runtime tests, in the first X
7168     // iterations of this loop, where X is the SCEV expression found by the
7169     // algorithm below.
7170     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7171 
7172   if (!AddRec || AddRec->getLoop() != L)
7173     return getCouldNotCompute();
7174 
7175   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7176   // the quadratic equation to solve it.
7177   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7178     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7179       const SCEVConstant *R1 = Roots->first;
7180       const SCEVConstant *R2 = Roots->second;
7181       // Pick the smallest positive root value.
7182       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7183               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7184         if (!CB->getZExtValue())
7185           std::swap(R1, R2); // R1 is the minimum root now.
7186 
7187         // We can only use this value if the chrec ends up with an exact zero
7188         // value at this index.  When solving for "X*X != 5", for example, we
7189         // should not accept a root of 2.
7190         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7191         if (Val->isZero())
7192           // We found a quadratic root!
7193           return ExitLimit(R1, R1, false, Predicates);
7194       }
7195     }
7196     return getCouldNotCompute();
7197   }
7198 
7199   // Otherwise we can only handle this if it is affine.
7200   if (!AddRec->isAffine())
7201     return getCouldNotCompute();
7202 
7203   // If this is an affine expression, the execution count of this branch is
7204   // the minimum unsigned root of the following equation:
7205   //
7206   //     Start + Step*N = 0 (mod 2^BW)
7207   //
7208   // equivalent to:
7209   //
7210   //             Step*N = -Start (mod 2^BW)
7211   //
7212   // where BW is the common bit width of Start and Step.
7213 
7214   // Get the initial value for the loop.
7215   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7216   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7217 
7218   // For now we handle only constant steps.
7219   //
7220   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7221   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7222   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7223   // We have not yet seen any such cases.
7224   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7225   if (!StepC || StepC->getValue()->equalsInt(0))
7226     return getCouldNotCompute();
7227 
7228   // For positive steps (counting up until unsigned overflow):
7229   //   N = -Start/Step (as unsigned)
7230   // For negative steps (counting down to zero):
7231   //   N = Start/-Step
7232   // First compute the unsigned distance from zero in the direction of Step.
7233   bool CountDown = StepC->getAPInt().isNegative();
7234   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7235 
7236   // Handle unitary steps, which cannot wraparound.
7237   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7238   //   N = Distance (as unsigned)
7239   if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7240     APInt MaxBECount = getUnsignedRange(Distance).getUnsignedMax();
7241 
7242     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
7243     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
7244     // case, and see if we can improve the bound.
7245     //
7246     // Explicitly handling this here is necessary because getUnsignedRange
7247     // isn't context-sensitive; it doesn't know that we only care about the
7248     // range inside the loop.
7249     const SCEV *Zero = getZero(Distance->getType());
7250     const SCEV *One = getOne(Distance->getType());
7251     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
7252     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
7253       // If Distance + 1 doesn't overflow, we can compute the maximum distance
7254       // as "unsigned_max(Distance + 1) - 1".
7255       ConstantRange CR = getUnsignedRange(DistancePlusOne);
7256       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
7257     }
7258     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
7259   }
7260 
7261   // If the condition controls loop exit (the loop exits only if the expression
7262   // is true) and the addition is no-wrap we can use unsigned divide to
7263   // compute the backedge count.  In this case, the step may not divide the
7264   // distance, but we don't care because if the condition is "missed" the loop
7265   // will have undefined behavior due to wrapping.
7266   if (ControlsExit && AddRec->hasNoSelfWrap() &&
7267       loopHasNoAbnormalExits(AddRec->getLoop())) {
7268     const SCEV *Exact =
7269         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
7270     return ExitLimit(Exact, Exact, false, Predicates);
7271   }
7272 
7273   // Solve the general equation.
7274   const SCEV *E = SolveLinEquationWithOverflow(
7275       StepC->getAPInt(), getNegativeSCEV(Start), *this);
7276   return ExitLimit(E, E, false, Predicates);
7277 }
7278 
7279 ScalarEvolution::ExitLimit
7280 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
7281   // Loops that look like: while (X == 0) are very strange indeed.  We don't
7282   // handle them yet except for the trivial case.  This could be expanded in the
7283   // future as needed.
7284 
7285   // If the value is a constant, check to see if it is known to be non-zero
7286   // already.  If so, the backedge will execute zero times.
7287   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7288     if (!C->getValue()->isNullValue())
7289       return getZero(C->getType());
7290     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7291   }
7292 
7293   // We could implement others, but I really doubt anyone writes loops like
7294   // this, and if they did, they would already be constant folded.
7295   return getCouldNotCompute();
7296 }
7297 
7298 std::pair<BasicBlock *, BasicBlock *>
7299 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
7300   // If the block has a unique predecessor, then there is no path from the
7301   // predecessor to the block that does not go through the direct edge
7302   // from the predecessor to the block.
7303   if (BasicBlock *Pred = BB->getSinglePredecessor())
7304     return {Pred, BB};
7305 
7306   // A loop's header is defined to be a block that dominates the loop.
7307   // If the header has a unique predecessor outside the loop, it must be
7308   // a block that has exactly one successor that can reach the loop.
7309   if (Loop *L = LI.getLoopFor(BB))
7310     return {L->getLoopPredecessor(), L->getHeader()};
7311 
7312   return {nullptr, nullptr};
7313 }
7314 
7315 /// SCEV structural equivalence is usually sufficient for testing whether two
7316 /// expressions are equal, however for the purposes of looking for a condition
7317 /// guarding a loop, it can be useful to be a little more general, since a
7318 /// front-end may have replicated the controlling expression.
7319 ///
7320 static bool HasSameValue(const SCEV *A, const SCEV *B) {
7321   // Quick check to see if they are the same SCEV.
7322   if (A == B) return true;
7323 
7324   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7325     // Not all instructions that are "identical" compute the same value.  For
7326     // instance, two distinct alloca instructions allocating the same type are
7327     // identical and do not read memory; but compute distinct values.
7328     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7329   };
7330 
7331   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7332   // two different instructions with the same value. Check for this case.
7333   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7334     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7335       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7336         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
7337           if (ComputesEqualValues(AI, BI))
7338             return true;
7339 
7340   // Otherwise assume they may have a different value.
7341   return false;
7342 }
7343 
7344 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
7345                                            const SCEV *&LHS, const SCEV *&RHS,
7346                                            unsigned Depth) {
7347   bool Changed = false;
7348 
7349   // If we hit the max recursion limit bail out.
7350   if (Depth >= 3)
7351     return false;
7352 
7353   // Canonicalize a constant to the right side.
7354   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7355     // Check for both operands constant.
7356     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7357       if (ConstantExpr::getICmp(Pred,
7358                                 LHSC->getValue(),
7359                                 RHSC->getValue())->isNullValue())
7360         goto trivially_false;
7361       else
7362         goto trivially_true;
7363     }
7364     // Otherwise swap the operands to put the constant on the right.
7365     std::swap(LHS, RHS);
7366     Pred = ICmpInst::getSwappedPredicate(Pred);
7367     Changed = true;
7368   }
7369 
7370   // If we're comparing an addrec with a value which is loop-invariant in the
7371   // addrec's loop, put the addrec on the left. Also make a dominance check,
7372   // as both operands could be addrecs loop-invariant in each other's loop.
7373   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7374     const Loop *L = AR->getLoop();
7375     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
7376       std::swap(LHS, RHS);
7377       Pred = ICmpInst::getSwappedPredicate(Pred);
7378       Changed = true;
7379     }
7380   }
7381 
7382   // If there's a constant operand, canonicalize comparisons with boundary
7383   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7384   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
7385     const APInt &RA = RC->getAPInt();
7386 
7387     bool SimplifiedByConstantRange = false;
7388 
7389     if (!ICmpInst::isEquality(Pred)) {
7390       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
7391       if (ExactCR.isFullSet())
7392         goto trivially_true;
7393       else if (ExactCR.isEmptySet())
7394         goto trivially_false;
7395 
7396       APInt NewRHS;
7397       CmpInst::Predicate NewPred;
7398       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
7399           ICmpInst::isEquality(NewPred)) {
7400         // We were able to convert an inequality to an equality.
7401         Pred = NewPred;
7402         RHS = getConstant(NewRHS);
7403         Changed = SimplifiedByConstantRange = true;
7404       }
7405     }
7406 
7407     if (!SimplifiedByConstantRange) {
7408       switch (Pred) {
7409       default:
7410         break;
7411       case ICmpInst::ICMP_EQ:
7412       case ICmpInst::ICMP_NE:
7413         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7414         if (!RA)
7415           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7416             if (const SCEVMulExpr *ME =
7417                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
7418               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7419                   ME->getOperand(0)->isAllOnesValue()) {
7420                 RHS = AE->getOperand(1);
7421                 LHS = ME->getOperand(1);
7422                 Changed = true;
7423               }
7424         break;
7425 
7426 
7427         // The "Should have been caught earlier!" messages refer to the fact
7428         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
7429         // should have fired on the corresponding cases, and canonicalized the
7430         // check to trivially_true or trivially_false.
7431 
7432       case ICmpInst::ICMP_UGE:
7433         assert(!RA.isMinValue() && "Should have been caught earlier!");
7434         Pred = ICmpInst::ICMP_UGT;
7435         RHS = getConstant(RA - 1);
7436         Changed = true;
7437         break;
7438       case ICmpInst::ICMP_ULE:
7439         assert(!RA.isMaxValue() && "Should have been caught earlier!");
7440         Pred = ICmpInst::ICMP_ULT;
7441         RHS = getConstant(RA + 1);
7442         Changed = true;
7443         break;
7444       case ICmpInst::ICMP_SGE:
7445         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
7446         Pred = ICmpInst::ICMP_SGT;
7447         RHS = getConstant(RA - 1);
7448         Changed = true;
7449         break;
7450       case ICmpInst::ICMP_SLE:
7451         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
7452         Pred = ICmpInst::ICMP_SLT;
7453         RHS = getConstant(RA + 1);
7454         Changed = true;
7455         break;
7456       }
7457     }
7458   }
7459 
7460   // Check for obvious equality.
7461   if (HasSameValue(LHS, RHS)) {
7462     if (ICmpInst::isTrueWhenEqual(Pred))
7463       goto trivially_true;
7464     if (ICmpInst::isFalseWhenEqual(Pred))
7465       goto trivially_false;
7466   }
7467 
7468   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7469   // adding or subtracting 1 from one of the operands.
7470   switch (Pred) {
7471   case ICmpInst::ICMP_SLE:
7472     if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7473       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7474                        SCEV::FlagNSW);
7475       Pred = ICmpInst::ICMP_SLT;
7476       Changed = true;
7477     } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
7478       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
7479                        SCEV::FlagNSW);
7480       Pred = ICmpInst::ICMP_SLT;
7481       Changed = true;
7482     }
7483     break;
7484   case ICmpInst::ICMP_SGE:
7485     if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
7486       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
7487                        SCEV::FlagNSW);
7488       Pred = ICmpInst::ICMP_SGT;
7489       Changed = true;
7490     } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7491       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7492                        SCEV::FlagNSW);
7493       Pred = ICmpInst::ICMP_SGT;
7494       Changed = true;
7495     }
7496     break;
7497   case ICmpInst::ICMP_ULE:
7498     if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
7499       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
7500                        SCEV::FlagNUW);
7501       Pred = ICmpInst::ICMP_ULT;
7502       Changed = true;
7503     } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
7504       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
7505       Pred = ICmpInst::ICMP_ULT;
7506       Changed = true;
7507     }
7508     break;
7509   case ICmpInst::ICMP_UGE:
7510     if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
7511       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
7512       Pred = ICmpInst::ICMP_UGT;
7513       Changed = true;
7514     } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
7515       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
7516                        SCEV::FlagNUW);
7517       Pred = ICmpInst::ICMP_UGT;
7518       Changed = true;
7519     }
7520     break;
7521   default:
7522     break;
7523   }
7524 
7525   // TODO: More simplifications are possible here.
7526 
7527   // Recursively simplify until we either hit a recursion limit or nothing
7528   // changes.
7529   if (Changed)
7530     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7531 
7532   return Changed;
7533 
7534 trivially_true:
7535   // Return 0 == 0.
7536   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7537   Pred = ICmpInst::ICMP_EQ;
7538   return true;
7539 
7540 trivially_false:
7541   // Return 0 != 0.
7542   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
7543   Pred = ICmpInst::ICMP_NE;
7544   return true;
7545 }
7546 
7547 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7548   return getSignedRange(S).getSignedMax().isNegative();
7549 }
7550 
7551 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7552   return getSignedRange(S).getSignedMin().isStrictlyPositive();
7553 }
7554 
7555 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7556   return !getSignedRange(S).getSignedMin().isNegative();
7557 }
7558 
7559 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7560   return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7561 }
7562 
7563 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7564   return isKnownNegative(S) || isKnownPositive(S);
7565 }
7566 
7567 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7568                                        const SCEV *LHS, const SCEV *RHS) {
7569   // Canonicalize the inputs first.
7570   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7571 
7572   // If LHS or RHS is an addrec, check to see if the condition is true in
7573   // every iteration of the loop.
7574   // If LHS and RHS are both addrec, both conditions must be true in
7575   // every iteration of the loop.
7576   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7577   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7578   bool LeftGuarded = false;
7579   bool RightGuarded = false;
7580   if (LAR) {
7581     const Loop *L = LAR->getLoop();
7582     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7583         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7584       if (!RAR) return true;
7585       LeftGuarded = true;
7586     }
7587   }
7588   if (RAR) {
7589     const Loop *L = RAR->getLoop();
7590     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7591         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7592       if (!LAR) return true;
7593       RightGuarded = true;
7594     }
7595   }
7596   if (LeftGuarded && RightGuarded)
7597     return true;
7598 
7599   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7600     return true;
7601 
7602   // Otherwise see what can be done with known constant ranges.
7603   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
7604 }
7605 
7606 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7607                                            ICmpInst::Predicate Pred,
7608                                            bool &Increasing) {
7609   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7610 
7611 #ifndef NDEBUG
7612   // Verify an invariant: inverting the predicate should turn a monotonically
7613   // increasing change to a monotonically decreasing one, and vice versa.
7614   bool IncreasingSwapped;
7615   bool ResultSwapped = isMonotonicPredicateImpl(
7616       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7617 
7618   assert(Result == ResultSwapped && "should be able to analyze both!");
7619   if (ResultSwapped)
7620     assert(Increasing == !IncreasingSwapped &&
7621            "monotonicity should flip as we flip the predicate");
7622 #endif
7623 
7624   return Result;
7625 }
7626 
7627 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7628                                                ICmpInst::Predicate Pred,
7629                                                bool &Increasing) {
7630 
7631   // A zero step value for LHS means the induction variable is essentially a
7632   // loop invariant value. We don't really depend on the predicate actually
7633   // flipping from false to true (for increasing predicates, and the other way
7634   // around for decreasing predicates), all we care about is that *if* the
7635   // predicate changes then it only changes from false to true.
7636   //
7637   // A zero step value in itself is not very useful, but there may be places
7638   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7639   // as general as possible.
7640 
7641   switch (Pred) {
7642   default:
7643     return false; // Conservative answer
7644 
7645   case ICmpInst::ICMP_UGT:
7646   case ICmpInst::ICMP_UGE:
7647   case ICmpInst::ICMP_ULT:
7648   case ICmpInst::ICMP_ULE:
7649     if (!LHS->hasNoUnsignedWrap())
7650       return false;
7651 
7652     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
7653     return true;
7654 
7655   case ICmpInst::ICMP_SGT:
7656   case ICmpInst::ICMP_SGE:
7657   case ICmpInst::ICMP_SLT:
7658   case ICmpInst::ICMP_SLE: {
7659     if (!LHS->hasNoSignedWrap())
7660       return false;
7661 
7662     const SCEV *Step = LHS->getStepRecurrence(*this);
7663 
7664     if (isKnownNonNegative(Step)) {
7665       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7666       return true;
7667     }
7668 
7669     if (isKnownNonPositive(Step)) {
7670       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7671       return true;
7672     }
7673 
7674     return false;
7675   }
7676 
7677   }
7678 
7679   llvm_unreachable("switch has default clause!");
7680 }
7681 
7682 bool ScalarEvolution::isLoopInvariantPredicate(
7683     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7684     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7685     const SCEV *&InvariantRHS) {
7686 
7687   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7688   if (!isLoopInvariant(RHS, L)) {
7689     if (!isLoopInvariant(LHS, L))
7690       return false;
7691 
7692     std::swap(LHS, RHS);
7693     Pred = ICmpInst::getSwappedPredicate(Pred);
7694   }
7695 
7696   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7697   if (!ArLHS || ArLHS->getLoop() != L)
7698     return false;
7699 
7700   bool Increasing;
7701   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7702     return false;
7703 
7704   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7705   // true as the loop iterates, and the backedge is control dependent on
7706   // "ArLHS `Pred` RHS" == true then we can reason as follows:
7707   //
7708   //   * if the predicate was false in the first iteration then the predicate
7709   //     is never evaluated again, since the loop exits without taking the
7710   //     backedge.
7711   //   * if the predicate was true in the first iteration then it will
7712   //     continue to be true for all future iterations since it is
7713   //     monotonically increasing.
7714   //
7715   // For both the above possibilities, we can replace the loop varying
7716   // predicate with its value on the first iteration of the loop (which is
7717   // loop invariant).
7718   //
7719   // A similar reasoning applies for a monotonically decreasing predicate, by
7720   // replacing true with false and false with true in the above two bullets.
7721 
7722   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7723 
7724   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7725     return false;
7726 
7727   InvariantPred = Pred;
7728   InvariantLHS = ArLHS->getStart();
7729   InvariantRHS = RHS;
7730   return true;
7731 }
7732 
7733 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7734     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
7735   if (HasSameValue(LHS, RHS))
7736     return ICmpInst::isTrueWhenEqual(Pred);
7737 
7738   // This code is split out from isKnownPredicate because it is called from
7739   // within isLoopEntryGuardedByCond.
7740 
7741   auto CheckRanges =
7742       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7743     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7744         .contains(RangeLHS);
7745   };
7746 
7747   // The check at the top of the function catches the case where the values are
7748   // known to be equal.
7749   if (Pred == CmpInst::ICMP_EQ)
7750     return false;
7751 
7752   if (Pred == CmpInst::ICMP_NE)
7753     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7754            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7755            isKnownNonZero(getMinusSCEV(LHS, RHS));
7756 
7757   if (CmpInst::isSigned(Pred))
7758     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7759 
7760   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
7761 }
7762 
7763 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7764                                                     const SCEV *LHS,
7765                                                     const SCEV *RHS) {
7766 
7767   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7768   // Return Y via OutY.
7769   auto MatchBinaryAddToConst =
7770       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7771              SCEV::NoWrapFlags ExpectedFlags) {
7772     const SCEV *NonConstOp, *ConstOp;
7773     SCEV::NoWrapFlags FlagsPresent;
7774 
7775     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7776         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7777       return false;
7778 
7779     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
7780     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7781   };
7782 
7783   APInt C;
7784 
7785   switch (Pred) {
7786   default:
7787     break;
7788 
7789   case ICmpInst::ICMP_SGE:
7790     std::swap(LHS, RHS);
7791   case ICmpInst::ICMP_SLE:
7792     // X s<= (X + C)<nsw> if C >= 0
7793     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7794       return true;
7795 
7796     // (X + C)<nsw> s<= X if C <= 0
7797     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7798         !C.isStrictlyPositive())
7799       return true;
7800     break;
7801 
7802   case ICmpInst::ICMP_SGT:
7803     std::swap(LHS, RHS);
7804   case ICmpInst::ICMP_SLT:
7805     // X s< (X + C)<nsw> if C > 0
7806     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7807         C.isStrictlyPositive())
7808       return true;
7809 
7810     // (X + C)<nsw> s< X if C < 0
7811     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7812       return true;
7813     break;
7814   }
7815 
7816   return false;
7817 }
7818 
7819 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7820                                                    const SCEV *LHS,
7821                                                    const SCEV *RHS) {
7822   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
7823     return false;
7824 
7825   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7826   // the stack can result in exponential time complexity.
7827   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7828 
7829   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7830   //
7831   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7832   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
7833   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7834   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
7835   // use isKnownPredicate later if needed.
7836   return isKnownNonNegative(RHS) &&
7837          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7838          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
7839 }
7840 
7841 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
7842                                         ICmpInst::Predicate Pred,
7843                                         const SCEV *LHS, const SCEV *RHS) {
7844   // No need to even try if we know the module has no guards.
7845   if (!HasGuards)
7846     return false;
7847 
7848   return any_of(*BB, [&](Instruction &I) {
7849     using namespace llvm::PatternMatch;
7850 
7851     Value *Condition;
7852     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
7853                          m_Value(Condition))) &&
7854            isImpliedCond(Pred, LHS, RHS, Condition, false);
7855   });
7856 }
7857 
7858 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7859 /// protected by a conditional between LHS and RHS.  This is used to
7860 /// to eliminate casts.
7861 bool
7862 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7863                                              ICmpInst::Predicate Pred,
7864                                              const SCEV *LHS, const SCEV *RHS) {
7865   // Interpret a null as meaning no loop, where there is obviously no guard
7866   // (interprocedural conditions notwithstanding).
7867   if (!L) return true;
7868 
7869   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7870     return true;
7871 
7872   BasicBlock *Latch = L->getLoopLatch();
7873   if (!Latch)
7874     return false;
7875 
7876   BranchInst *LoopContinuePredicate =
7877     dyn_cast<BranchInst>(Latch->getTerminator());
7878   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7879       isImpliedCond(Pred, LHS, RHS,
7880                     LoopContinuePredicate->getCondition(),
7881                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7882     return true;
7883 
7884   // We don't want more than one activation of the following loops on the stack
7885   // -- that can lead to O(n!) time complexity.
7886   if (WalkingBEDominatingConds)
7887     return false;
7888 
7889   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
7890 
7891   // See if we can exploit a trip count to prove the predicate.
7892   const auto &BETakenInfo = getBackedgeTakenInfo(L);
7893   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7894   if (LatchBECount != getCouldNotCompute()) {
7895     // We know that Latch branches back to the loop header exactly
7896     // LatchBECount times.  This means the backdege condition at Latch is
7897     // equivalent to  "{0,+,1} u< LatchBECount".
7898     Type *Ty = LatchBECount->getType();
7899     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7900     const SCEV *LoopCounter =
7901       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7902     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7903                       LatchBECount))
7904       return true;
7905   }
7906 
7907   // Check conditions due to any @llvm.assume intrinsics.
7908   for (auto &AssumeVH : AC.assumptions()) {
7909     if (!AssumeVH)
7910       continue;
7911     auto *CI = cast<CallInst>(AssumeVH);
7912     if (!DT.dominates(CI, Latch->getTerminator()))
7913       continue;
7914 
7915     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7916       return true;
7917   }
7918 
7919   // If the loop is not reachable from the entry block, we risk running into an
7920   // infinite loop as we walk up into the dom tree.  These loops do not matter
7921   // anyway, so we just return a conservative answer when we see them.
7922   if (!DT.isReachableFromEntry(L->getHeader()))
7923     return false;
7924 
7925   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
7926     return true;
7927 
7928   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7929        DTN != HeaderDTN; DTN = DTN->getIDom()) {
7930 
7931     assert(DTN && "should reach the loop header before reaching the root!");
7932 
7933     BasicBlock *BB = DTN->getBlock();
7934     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
7935       return true;
7936 
7937     BasicBlock *PBB = BB->getSinglePredecessor();
7938     if (!PBB)
7939       continue;
7940 
7941     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7942     if (!ContinuePredicate || !ContinuePredicate->isConditional())
7943       continue;
7944 
7945     Value *Condition = ContinuePredicate->getCondition();
7946 
7947     // If we have an edge `E` within the loop body that dominates the only
7948     // latch, the condition guarding `E` also guards the backedge.  This
7949     // reasoning works only for loops with a single latch.
7950 
7951     BasicBlockEdge DominatingEdge(PBB, BB);
7952     if (DominatingEdge.isSingleEdge()) {
7953       // We're constructively (and conservatively) enumerating edges within the
7954       // loop body that dominate the latch.  The dominator tree better agree
7955       // with us on this:
7956       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
7957 
7958       if (isImpliedCond(Pred, LHS, RHS, Condition,
7959                         BB != ContinuePredicate->getSuccessor(0)))
7960         return true;
7961     }
7962   }
7963 
7964   return false;
7965 }
7966 
7967 bool
7968 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7969                                           ICmpInst::Predicate Pred,
7970                                           const SCEV *LHS, const SCEV *RHS) {
7971   // Interpret a null as meaning no loop, where there is obviously no guard
7972   // (interprocedural conditions notwithstanding).
7973   if (!L) return false;
7974 
7975   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7976     return true;
7977 
7978   // Starting at the loop predecessor, climb up the predecessor chain, as long
7979   // as there are predecessors that can be found that have unique successors
7980   // leading to the original header.
7981   for (std::pair<BasicBlock *, BasicBlock *>
7982          Pair(L->getLoopPredecessor(), L->getHeader());
7983        Pair.first;
7984        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
7985 
7986     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
7987       return true;
7988 
7989     BranchInst *LoopEntryPredicate =
7990       dyn_cast<BranchInst>(Pair.first->getTerminator());
7991     if (!LoopEntryPredicate ||
7992         LoopEntryPredicate->isUnconditional())
7993       continue;
7994 
7995     if (isImpliedCond(Pred, LHS, RHS,
7996                       LoopEntryPredicate->getCondition(),
7997                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
7998       return true;
7999   }
8000 
8001   // Check conditions due to any @llvm.assume intrinsics.
8002   for (auto &AssumeVH : AC.assumptions()) {
8003     if (!AssumeVH)
8004       continue;
8005     auto *CI = cast<CallInst>(AssumeVH);
8006     if (!DT.dominates(CI, L->getHeader()))
8007       continue;
8008 
8009     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8010       return true;
8011   }
8012 
8013   return false;
8014 }
8015 
8016 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8017                                     const SCEV *LHS, const SCEV *RHS,
8018                                     Value *FoundCondValue,
8019                                     bool Inverse) {
8020   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8021     return false;
8022 
8023   auto ClearOnExit =
8024       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8025 
8026   // Recursively handle And and Or conditions.
8027   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8028     if (BO->getOpcode() == Instruction::And) {
8029       if (!Inverse)
8030         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8031                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8032     } else if (BO->getOpcode() == Instruction::Or) {
8033       if (Inverse)
8034         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8035                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8036     }
8037   }
8038 
8039   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8040   if (!ICI) return false;
8041 
8042   // Now that we found a conditional branch that dominates the loop or controls
8043   // the loop latch. Check to see if it is the comparison we are looking for.
8044   ICmpInst::Predicate FoundPred;
8045   if (Inverse)
8046     FoundPred = ICI->getInversePredicate();
8047   else
8048     FoundPred = ICI->getPredicate();
8049 
8050   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8051   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8052 
8053   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8054 }
8055 
8056 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8057                                     const SCEV *RHS,
8058                                     ICmpInst::Predicate FoundPred,
8059                                     const SCEV *FoundLHS,
8060                                     const SCEV *FoundRHS) {
8061   // Balance the types.
8062   if (getTypeSizeInBits(LHS->getType()) <
8063       getTypeSizeInBits(FoundLHS->getType())) {
8064     if (CmpInst::isSigned(Pred)) {
8065       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8066       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8067     } else {
8068       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8069       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8070     }
8071   } else if (getTypeSizeInBits(LHS->getType()) >
8072       getTypeSizeInBits(FoundLHS->getType())) {
8073     if (CmpInst::isSigned(FoundPred)) {
8074       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8075       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8076     } else {
8077       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8078       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8079     }
8080   }
8081 
8082   // Canonicalize the query to match the way instcombine will have
8083   // canonicalized the comparison.
8084   if (SimplifyICmpOperands(Pred, LHS, RHS))
8085     if (LHS == RHS)
8086       return CmpInst::isTrueWhenEqual(Pred);
8087   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8088     if (FoundLHS == FoundRHS)
8089       return CmpInst::isFalseWhenEqual(FoundPred);
8090 
8091   // Check to see if we can make the LHS or RHS match.
8092   if (LHS == FoundRHS || RHS == FoundLHS) {
8093     if (isa<SCEVConstant>(RHS)) {
8094       std::swap(FoundLHS, FoundRHS);
8095       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8096     } else {
8097       std::swap(LHS, RHS);
8098       Pred = ICmpInst::getSwappedPredicate(Pred);
8099     }
8100   }
8101 
8102   // Check whether the found predicate is the same as the desired predicate.
8103   if (FoundPred == Pred)
8104     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8105 
8106   // Check whether swapping the found predicate makes it the same as the
8107   // desired predicate.
8108   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8109     if (isa<SCEVConstant>(RHS))
8110       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8111     else
8112       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8113                                    RHS, LHS, FoundLHS, FoundRHS);
8114   }
8115 
8116   // Unsigned comparison is the same as signed comparison when both the operands
8117   // are non-negative.
8118   if (CmpInst::isUnsigned(FoundPred) &&
8119       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8120       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8121     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8122 
8123   // Check if we can make progress by sharpening ranges.
8124   if (FoundPred == ICmpInst::ICMP_NE &&
8125       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8126 
8127     const SCEVConstant *C = nullptr;
8128     const SCEV *V = nullptr;
8129 
8130     if (isa<SCEVConstant>(FoundLHS)) {
8131       C = cast<SCEVConstant>(FoundLHS);
8132       V = FoundRHS;
8133     } else {
8134       C = cast<SCEVConstant>(FoundRHS);
8135       V = FoundLHS;
8136     }
8137 
8138     // The guarding predicate tells us that C != V. If the known range
8139     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8140     // range we consider has to correspond to same signedness as the
8141     // predicate we're interested in folding.
8142 
8143     APInt Min = ICmpInst::isSigned(Pred) ?
8144         getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8145 
8146     if (Min == C->getAPInt()) {
8147       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8148       // This is true even if (Min + 1) wraps around -- in case of
8149       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8150 
8151       APInt SharperMin = Min + 1;
8152 
8153       switch (Pred) {
8154         case ICmpInst::ICMP_SGE:
8155         case ICmpInst::ICMP_UGE:
8156           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8157           // RHS, we're done.
8158           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8159                                     getConstant(SharperMin)))
8160             return true;
8161 
8162         case ICmpInst::ICMP_SGT:
8163         case ICmpInst::ICMP_UGT:
8164           // We know from the range information that (V `Pred` Min ||
8165           // V == Min).  We know from the guarding condition that !(V
8166           // == Min).  This gives us
8167           //
8168           //       V `Pred` Min || V == Min && !(V == Min)
8169           //   =>  V `Pred` Min
8170           //
8171           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8172 
8173           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8174             return true;
8175 
8176         default:
8177           // No change
8178           break;
8179       }
8180     }
8181   }
8182 
8183   // Check whether the actual condition is beyond sufficient.
8184   if (FoundPred == ICmpInst::ICMP_EQ)
8185     if (ICmpInst::isTrueWhenEqual(Pred))
8186       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8187         return true;
8188   if (Pred == ICmpInst::ICMP_NE)
8189     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8190       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8191         return true;
8192 
8193   // Otherwise assume the worst.
8194   return false;
8195 }
8196 
8197 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8198                                      const SCEV *&L, const SCEV *&R,
8199                                      SCEV::NoWrapFlags &Flags) {
8200   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8201   if (!AE || AE->getNumOperands() != 2)
8202     return false;
8203 
8204   L = AE->getOperand(0);
8205   R = AE->getOperand(1);
8206   Flags = AE->getNoWrapFlags();
8207   return true;
8208 }
8209 
8210 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8211                                                            const SCEV *Less) {
8212   // We avoid subtracting expressions here because this function is usually
8213   // fairly deep in the call stack (i.e. is called many times).
8214 
8215   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8216     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8217     const auto *MAR = cast<SCEVAddRecExpr>(More);
8218 
8219     if (LAR->getLoop() != MAR->getLoop())
8220       return None;
8221 
8222     // We look at affine expressions only; not for correctness but to keep
8223     // getStepRecurrence cheap.
8224     if (!LAR->isAffine() || !MAR->isAffine())
8225       return None;
8226 
8227     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
8228       return None;
8229 
8230     Less = LAR->getStart();
8231     More = MAR->getStart();
8232 
8233     // fall through
8234   }
8235 
8236   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
8237     const auto &M = cast<SCEVConstant>(More)->getAPInt();
8238     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
8239     return M - L;
8240   }
8241 
8242   const SCEV *L, *R;
8243   SCEV::NoWrapFlags Flags;
8244   if (splitBinaryAdd(Less, L, R, Flags))
8245     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8246       if (R == More)
8247         return -(LC->getAPInt());
8248 
8249   if (splitBinaryAdd(More, L, R, Flags))
8250     if (const auto *LC = dyn_cast<SCEVConstant>(L))
8251       if (R == Less)
8252         return LC->getAPInt();
8253 
8254   return None;
8255 }
8256 
8257 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8258     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8259     const SCEV *FoundLHS, const SCEV *FoundRHS) {
8260   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8261     return false;
8262 
8263   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8264   if (!AddRecLHS)
8265     return false;
8266 
8267   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8268   if (!AddRecFoundLHS)
8269     return false;
8270 
8271   // We'd like to let SCEV reason about control dependencies, so we constrain
8272   // both the inequalities to be about add recurrences on the same loop.  This
8273   // way we can use isLoopEntryGuardedByCond later.
8274 
8275   const Loop *L = AddRecFoundLHS->getLoop();
8276   if (L != AddRecLHS->getLoop())
8277     return false;
8278 
8279   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
8280   //
8281   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8282   //                                                                  ... (2)
8283   //
8284   // Informal proof for (2), assuming (1) [*]:
8285   //
8286   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8287   //
8288   // Then
8289   //
8290   //       FoundLHS s< FoundRHS s< INT_MIN - C
8291   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
8292   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8293   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
8294   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8295   // <=>  FoundLHS + C s< FoundRHS + C
8296   //
8297   // [*]: (1) can be proved by ruling out overflow.
8298   //
8299   // [**]: This can be proved by analyzing all the four possibilities:
8300   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8301   //    (A s>= 0, B s>= 0).
8302   //
8303   // Note:
8304   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8305   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
8306   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
8307   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
8308   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8309   // C)".
8310 
8311   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
8312   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
8313   if (!LDiff || !RDiff || *LDiff != *RDiff)
8314     return false;
8315 
8316   if (LDiff->isMinValue())
8317     return true;
8318 
8319   APInt FoundRHSLimit;
8320 
8321   if (Pred == CmpInst::ICMP_ULT) {
8322     FoundRHSLimit = -(*RDiff);
8323   } else {
8324     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
8325     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
8326   }
8327 
8328   // Try to prove (1) or (2), as needed.
8329   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8330                                   getConstant(FoundRHSLimit));
8331 }
8332 
8333 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8334                                             const SCEV *LHS, const SCEV *RHS,
8335                                             const SCEV *FoundLHS,
8336                                             const SCEV *FoundRHS) {
8337   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8338     return true;
8339 
8340   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8341     return true;
8342 
8343   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8344                                      FoundLHS, FoundRHS) ||
8345          // ~x < ~y --> x > y
8346          isImpliedCondOperandsHelper(Pred, LHS, RHS,
8347                                      getNotSCEV(FoundRHS),
8348                                      getNotSCEV(FoundLHS));
8349 }
8350 
8351 
8352 /// If Expr computes ~A, return A else return nullptr
8353 static const SCEV *MatchNotExpr(const SCEV *Expr) {
8354   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
8355   if (!Add || Add->getNumOperands() != 2 ||
8356       !Add->getOperand(0)->isAllOnesValue())
8357     return nullptr;
8358 
8359   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
8360   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8361       !AddRHS->getOperand(0)->isAllOnesValue())
8362     return nullptr;
8363 
8364   return AddRHS->getOperand(1);
8365 }
8366 
8367 
8368 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8369 template<typename MaxExprType>
8370 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8371                               const SCEV *Candidate) {
8372   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8373   if (!MaxExpr) return false;
8374 
8375   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
8376 }
8377 
8378 
8379 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8380 template<typename MaxExprType>
8381 static bool IsMinConsistingOf(ScalarEvolution &SE,
8382                               const SCEV *MaybeMinExpr,
8383                               const SCEV *Candidate) {
8384   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8385   if (!MaybeMaxExpr)
8386     return false;
8387 
8388   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8389 }
8390 
8391 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8392                                            ICmpInst::Predicate Pred,
8393                                            const SCEV *LHS, const SCEV *RHS) {
8394 
8395   // If both sides are affine addrecs for the same loop, with equal
8396   // steps, and we know the recurrences don't wrap, then we only
8397   // need to check the predicate on the starting values.
8398 
8399   if (!ICmpInst::isRelational(Pred))
8400     return false;
8401 
8402   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8403   if (!LAR)
8404     return false;
8405   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8406   if (!RAR)
8407     return false;
8408   if (LAR->getLoop() != RAR->getLoop())
8409     return false;
8410   if (!LAR->isAffine() || !RAR->isAffine())
8411     return false;
8412 
8413   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8414     return false;
8415 
8416   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8417                          SCEV::FlagNSW : SCEV::FlagNUW;
8418   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
8419     return false;
8420 
8421   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8422 }
8423 
8424 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8425 /// expression?
8426 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8427                                         ICmpInst::Predicate Pred,
8428                                         const SCEV *LHS, const SCEV *RHS) {
8429   switch (Pred) {
8430   default:
8431     return false;
8432 
8433   case ICmpInst::ICMP_SGE:
8434     std::swap(LHS, RHS);
8435     LLVM_FALLTHROUGH;
8436   case ICmpInst::ICMP_SLE:
8437     return
8438       // min(A, ...) <= A
8439       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8440       // A <= max(A, ...)
8441       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8442 
8443   case ICmpInst::ICMP_UGE:
8444     std::swap(LHS, RHS);
8445     LLVM_FALLTHROUGH;
8446   case ICmpInst::ICMP_ULE:
8447     return
8448       // min(A, ...) <= A
8449       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8450       // A <= max(A, ...)
8451       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8452   }
8453 
8454   llvm_unreachable("covered switch fell through?!");
8455 }
8456 
8457 bool
8458 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8459                                              const SCEV *LHS, const SCEV *RHS,
8460                                              const SCEV *FoundLHS,
8461                                              const SCEV *FoundRHS) {
8462   auto IsKnownPredicateFull =
8463       [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8464     return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
8465            IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
8466            IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8467            isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
8468   };
8469 
8470   switch (Pred) {
8471   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8472   case ICmpInst::ICMP_EQ:
8473   case ICmpInst::ICMP_NE:
8474     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8475       return true;
8476     break;
8477   case ICmpInst::ICMP_SLT:
8478   case ICmpInst::ICMP_SLE:
8479     if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8480         IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
8481       return true;
8482     break;
8483   case ICmpInst::ICMP_SGT:
8484   case ICmpInst::ICMP_SGE:
8485     if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8486         IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
8487       return true;
8488     break;
8489   case ICmpInst::ICMP_ULT:
8490   case ICmpInst::ICMP_ULE:
8491     if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8492         IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
8493       return true;
8494     break;
8495   case ICmpInst::ICMP_UGT:
8496   case ICmpInst::ICMP_UGE:
8497     if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8498         IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
8499       return true;
8500     break;
8501   }
8502 
8503   return false;
8504 }
8505 
8506 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8507                                                      const SCEV *LHS,
8508                                                      const SCEV *RHS,
8509                                                      const SCEV *FoundLHS,
8510                                                      const SCEV *FoundRHS) {
8511   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8512     // The restriction on `FoundRHS` be lifted easily -- it exists only to
8513     // reduce the compile time impact of this optimization.
8514     return false;
8515 
8516   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
8517   if (!Addend)
8518     return false;
8519 
8520   APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
8521 
8522   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8523   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8524   ConstantRange FoundLHSRange =
8525       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8526 
8527   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
8528   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
8529 
8530   // We can also compute the range of values for `LHS` that satisfy the
8531   // consequent, "`LHS` `Pred` `RHS`":
8532   APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
8533   ConstantRange SatisfyingLHSRange =
8534       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8535 
8536   // The antecedent implies the consequent if every value of `LHS` that
8537   // satisfies the antecedent also satisfies the consequent.
8538   return SatisfyingLHSRange.contains(LHSRange);
8539 }
8540 
8541 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8542                                          bool IsSigned, bool NoWrap) {
8543   assert(isKnownPositive(Stride) && "Positive stride expected!");
8544 
8545   if (NoWrap) return false;
8546 
8547   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8548   const SCEV *One = getOne(Stride->getType());
8549 
8550   if (IsSigned) {
8551     APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8552     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8553     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8554                                 .getSignedMax();
8555 
8556     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8557     return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
8558   }
8559 
8560   APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8561   APInt MaxValue = APInt::getMaxValue(BitWidth);
8562   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8563                               .getUnsignedMax();
8564 
8565   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8566   return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8567 }
8568 
8569 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8570                                          bool IsSigned, bool NoWrap) {
8571   if (NoWrap) return false;
8572 
8573   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
8574   const SCEV *One = getOne(Stride->getType());
8575 
8576   if (IsSigned) {
8577     APInt MinRHS = getSignedRange(RHS).getSignedMin();
8578     APInt MinValue = APInt::getSignedMinValue(BitWidth);
8579     APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8580                                .getSignedMax();
8581 
8582     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8583     return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8584   }
8585 
8586   APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8587   APInt MinValue = APInt::getMinValue(BitWidth);
8588   APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8589                             .getUnsignedMax();
8590 
8591   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8592   return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8593 }
8594 
8595 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
8596                                             bool Equality) {
8597   const SCEV *One = getOne(Step->getType());
8598   Delta = Equality ? getAddExpr(Delta, Step)
8599                    : getAddExpr(Delta, getMinusSCEV(Step, One));
8600   return getUDivExpr(Delta, Step);
8601 }
8602 
8603 ScalarEvolution::ExitLimit
8604 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
8605                                   const Loop *L, bool IsSigned,
8606                                   bool ControlsExit, bool AllowPredicates) {
8607   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8608   // We handle only IV < Invariant
8609   if (!isLoopInvariant(RHS, L))
8610     return getCouldNotCompute();
8611 
8612   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8613   bool PredicatedIV = false;
8614 
8615   if (!IV && AllowPredicates) {
8616     // Try to make this an AddRec using runtime tests, in the first X
8617     // iterations of this loop, where X is the SCEV expression found by the
8618     // algorithm below.
8619     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8620     PredicatedIV = true;
8621   }
8622 
8623   // Avoid weird loops
8624   if (!IV || IV->getLoop() != L || !IV->isAffine())
8625     return getCouldNotCompute();
8626 
8627   bool NoWrap = ControlsExit &&
8628                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8629 
8630   const SCEV *Stride = IV->getStepRecurrence(*this);
8631 
8632   bool PositiveStride = isKnownPositive(Stride);
8633 
8634   // Avoid negative or zero stride values.
8635   if (!PositiveStride) {
8636     // We can compute the correct backedge taken count for loops with unknown
8637     // strides if we can prove that the loop is not an infinite loop with side
8638     // effects. Here's the loop structure we are trying to handle -
8639     //
8640     // i = start
8641     // do {
8642     //   A[i] = i;
8643     //   i += s;
8644     // } while (i < end);
8645     //
8646     // The backedge taken count for such loops is evaluated as -
8647     // (max(end, start + stride) - start - 1) /u stride
8648     //
8649     // The additional preconditions that we need to check to prove correctness
8650     // of the above formula is as follows -
8651     //
8652     // a) IV is either nuw or nsw depending upon signedness (indicated by the
8653     //    NoWrap flag).
8654     // b) loop is single exit with no side effects.
8655     //
8656     //
8657     // Precondition a) implies that if the stride is negative, this is a single
8658     // trip loop. The backedge taken count formula reduces to zero in this case.
8659     //
8660     // Precondition b) implies that the unknown stride cannot be zero otherwise
8661     // we have UB.
8662     //
8663     // The positive stride case is the same as isKnownPositive(Stride) returning
8664     // true (original behavior of the function).
8665     //
8666     // We want to make sure that the stride is truly unknown as there are edge
8667     // cases where ScalarEvolution propagates no wrap flags to the
8668     // post-increment/decrement IV even though the increment/decrement operation
8669     // itself is wrapping. The computed backedge taken count may be wrong in
8670     // such cases. This is prevented by checking that the stride is not known to
8671     // be either positive or non-positive. For example, no wrap flags are
8672     // propagated to the post-increment IV of this loop with a trip count of 2 -
8673     //
8674     // unsigned char i;
8675     // for(i=127; i<128; i+=129)
8676     //   A[i] = i;
8677     //
8678     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
8679         !loopHasNoSideEffects(L))
8680       return getCouldNotCompute();
8681 
8682   } else if (!Stride->isOne() &&
8683              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8684     // Avoid proven overflow cases: this will ensure that the backedge taken
8685     // count will not generate any unsigned overflow. Relaxed no-overflow
8686     // conditions exploit NoWrapFlags, allowing to optimize in presence of
8687     // undefined behaviors like the case of C language.
8688     return getCouldNotCompute();
8689 
8690   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8691                                       : ICmpInst::ICMP_ULT;
8692   const SCEV *Start = IV->getStart();
8693   const SCEV *End = RHS;
8694   // If the backedge is taken at least once, then it will be taken
8695   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
8696   // is the LHS value of the less-than comparison the first time it is evaluated
8697   // and End is the RHS.
8698   const SCEV *BECountIfBackedgeTaken =
8699     computeBECount(getMinusSCEV(End, Start), Stride, false);
8700   // If the loop entry is guarded by the result of the backedge test of the
8701   // first loop iteration, then we know the backedge will be taken at least
8702   // once and so the backedge taken count is as above. If not then we use the
8703   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
8704   // as if the backedge is taken at least once max(End,Start) is End and so the
8705   // result is as above, and if not max(End,Start) is Start so we get a backedge
8706   // count of zero.
8707   const SCEV *BECount;
8708   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
8709     BECount = BECountIfBackedgeTaken;
8710   else {
8711     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
8712     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
8713   }
8714 
8715   const SCEV *MaxBECount;
8716   bool MaxOrZero = false;
8717   if (isa<SCEVConstant>(BECount))
8718     MaxBECount = BECount;
8719   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
8720     // If we know exactly how many times the backedge will be taken if it's
8721     // taken at least once, then the backedge count will either be that or
8722     // zero.
8723     MaxBECount = BECountIfBackedgeTaken;
8724     MaxOrZero = true;
8725   } else {
8726     // Calculate the maximum backedge count based on the range of values
8727     // permitted by Start, End, and Stride.
8728     APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8729                               : getUnsignedRange(Start).getUnsignedMin();
8730 
8731     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8732 
8733     APInt StrideForMaxBECount;
8734 
8735     if (PositiveStride)
8736       StrideForMaxBECount =
8737         IsSigned ? getSignedRange(Stride).getSignedMin()
8738                  : getUnsignedRange(Stride).getUnsignedMin();
8739     else
8740       // Using a stride of 1 is safe when computing max backedge taken count for
8741       // a loop with unknown stride.
8742       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
8743 
8744     APInt Limit =
8745       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
8746                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
8747 
8748     // Although End can be a MAX expression we estimate MaxEnd considering only
8749     // the case End = RHS. This is safe because in the other case (End - Start)
8750     // is zero, leading to a zero maximum backedge taken count.
8751     APInt MaxEnd =
8752       IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8753                : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8754 
8755     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8756                                 getConstant(StrideForMaxBECount), false);
8757   }
8758 
8759   if (isa<SCEVCouldNotCompute>(MaxBECount))
8760     MaxBECount = BECount;
8761 
8762   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
8763 }
8764 
8765 ScalarEvolution::ExitLimit
8766 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8767                                      const Loop *L, bool IsSigned,
8768                                      bool ControlsExit, bool AllowPredicates) {
8769   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8770   // We handle only IV > Invariant
8771   if (!isLoopInvariant(RHS, L))
8772     return getCouldNotCompute();
8773 
8774   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
8775   if (!IV && AllowPredicates)
8776     // Try to make this an AddRec using runtime tests, in the first X
8777     // iterations of this loop, where X is the SCEV expression found by the
8778     // algorithm below.
8779     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
8780 
8781   // Avoid weird loops
8782   if (!IV || IV->getLoop() != L || !IV->isAffine())
8783     return getCouldNotCompute();
8784 
8785   bool NoWrap = ControlsExit &&
8786                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8787 
8788   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8789 
8790   // Avoid negative or zero stride values
8791   if (!isKnownPositive(Stride))
8792     return getCouldNotCompute();
8793 
8794   // Avoid proven overflow cases: this will ensure that the backedge taken count
8795   // will not generate any unsigned overflow. Relaxed no-overflow conditions
8796   // exploit NoWrapFlags, allowing to optimize in presence of undefined
8797   // behaviors like the case of C language.
8798   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8799     return getCouldNotCompute();
8800 
8801   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8802                                       : ICmpInst::ICMP_UGT;
8803 
8804   const SCEV *Start = IV->getStart();
8805   const SCEV *End = RHS;
8806   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
8807     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
8808 
8809   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8810 
8811   APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8812                             : getUnsignedRange(Start).getUnsignedMax();
8813 
8814   APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8815                              : getUnsignedRange(Stride).getUnsignedMin();
8816 
8817   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8818   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8819                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
8820 
8821   // Although End can be a MIN expression we estimate MinEnd considering only
8822   // the case End = RHS. This is safe because in the other case (Start - End)
8823   // is zero, leading to a zero maximum backedge taken count.
8824   APInt MinEnd =
8825     IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8826              : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8827 
8828 
8829   const SCEV *MaxBECount = getCouldNotCompute();
8830   if (isa<SCEVConstant>(BECount))
8831     MaxBECount = BECount;
8832   else
8833     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
8834                                 getConstant(MinStride), false);
8835 
8836   if (isa<SCEVCouldNotCompute>(MaxBECount))
8837     MaxBECount = BECount;
8838 
8839   return ExitLimit(BECount, MaxBECount, false, Predicates);
8840 }
8841 
8842 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
8843                                                     ScalarEvolution &SE) const {
8844   if (Range.isFullSet())  // Infinite loop.
8845     return SE.getCouldNotCompute();
8846 
8847   // If the start is a non-zero constant, shift the range to simplify things.
8848   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
8849     if (!SC->getValue()->isZero()) {
8850       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
8851       Operands[0] = SE.getZero(SC->getType());
8852       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
8853                                              getNoWrapFlags(FlagNW));
8854       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
8855         return ShiftedAddRec->getNumIterationsInRange(
8856             Range.subtract(SC->getAPInt()), SE);
8857       // This is strange and shouldn't happen.
8858       return SE.getCouldNotCompute();
8859     }
8860 
8861   // The only time we can solve this is when we have all constant indices.
8862   // Otherwise, we cannot determine the overflow conditions.
8863   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
8864     return SE.getCouldNotCompute();
8865 
8866   // Okay at this point we know that all elements of the chrec are constants and
8867   // that the start element is zero.
8868 
8869   // First check to see if the range contains zero.  If not, the first
8870   // iteration exits.
8871   unsigned BitWidth = SE.getTypeSizeInBits(getType());
8872   if (!Range.contains(APInt(BitWidth, 0)))
8873     return SE.getZero(getType());
8874 
8875   if (isAffine()) {
8876     // If this is an affine expression then we have this situation:
8877     //   Solve {0,+,A} in Range  ===  Ax in Range
8878 
8879     // We know that zero is in the range.  If A is positive then we know that
8880     // the upper value of the range must be the first possible exit value.
8881     // If A is negative then the lower of the range is the last possible loop
8882     // value.  Also note that we already checked for a full range.
8883     APInt One(BitWidth,1);
8884     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
8885     APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
8886 
8887     // The exit value should be (End+A)/A.
8888     APInt ExitVal = (End + A).udiv(A);
8889     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
8890 
8891     // Evaluate at the exit value.  If we really did fall out of the valid
8892     // range, then we computed our trip count, otherwise wrap around or other
8893     // things must have happened.
8894     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
8895     if (Range.contains(Val->getValue()))
8896       return SE.getCouldNotCompute();  // Something strange happened
8897 
8898     // Ensure that the previous value is in the range.  This is a sanity check.
8899     assert(Range.contains(
8900            EvaluateConstantChrecAtConstant(this,
8901            ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
8902            "Linear scev computation is off in a bad way!");
8903     return SE.getConstant(ExitValue);
8904   } else if (isQuadratic()) {
8905     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8906     // quadratic equation to solve it.  To do this, we must frame our problem in
8907     // terms of figuring out when zero is crossed, instead of when
8908     // Range.getUpper() is crossed.
8909     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
8910     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
8911     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
8912 
8913     // Next, solve the constructed addrec
8914     if (auto Roots =
8915             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
8916       const SCEVConstant *R1 = Roots->first;
8917       const SCEVConstant *R2 = Roots->second;
8918       // Pick the smallest positive root value.
8919       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8920               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8921         if (!CB->getZExtValue())
8922           std::swap(R1, R2); // R1 is the minimum root now.
8923 
8924         // Make sure the root is not off by one.  The returned iteration should
8925         // not be in the range, but the previous one should be.  When solving
8926         // for "X*X < 5", for example, we should not return a root of 2.
8927         ConstantInt *R1Val =
8928             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
8929         if (Range.contains(R1Val->getValue())) {
8930           // The next iteration must be out of the range...
8931           ConstantInt *NextVal =
8932               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
8933 
8934           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8935           if (!Range.contains(R1Val->getValue()))
8936             return SE.getConstant(NextVal);
8937           return SE.getCouldNotCompute(); // Something strange happened
8938         }
8939 
8940         // If R1 was not in the range, then it is a good return value.  Make
8941         // sure that R1-1 WAS in the range though, just in case.
8942         ConstantInt *NextVal =
8943             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
8944         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
8945         if (Range.contains(R1Val->getValue()))
8946           return R1;
8947         return SE.getCouldNotCompute(); // Something strange happened
8948       }
8949     }
8950   }
8951 
8952   return SE.getCouldNotCompute();
8953 }
8954 
8955 // Return true when S contains at least an undef value.
8956 static inline bool containsUndefs(const SCEV *S) {
8957   return SCEVExprContains(S, [](const SCEV *S) {
8958     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
8959       return isa<UndefValue>(SU->getValue());
8960     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
8961       return isa<UndefValue>(SC->getValue());
8962     return false;
8963   });
8964 }
8965 
8966 namespace {
8967 // Collect all steps of SCEV expressions.
8968 struct SCEVCollectStrides {
8969   ScalarEvolution &SE;
8970   SmallVectorImpl<const SCEV *> &Strides;
8971 
8972   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8973       : SE(SE), Strides(S) {}
8974 
8975   bool follow(const SCEV *S) {
8976     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8977       Strides.push_back(AR->getStepRecurrence(SE));
8978     return true;
8979   }
8980   bool isDone() const { return false; }
8981 };
8982 
8983 // Collect all SCEVUnknown and SCEVMulExpr expressions.
8984 struct SCEVCollectTerms {
8985   SmallVectorImpl<const SCEV *> &Terms;
8986 
8987   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8988       : Terms(T) {}
8989 
8990   bool follow(const SCEV *S) {
8991     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
8992         isa<SCEVSignExtendExpr>(S)) {
8993       if (!containsUndefs(S))
8994         Terms.push_back(S);
8995 
8996       // Stop recursion: once we collected a term, do not walk its operands.
8997       return false;
8998     }
8999 
9000     // Keep looking.
9001     return true;
9002   }
9003   bool isDone() const { return false; }
9004 };
9005 
9006 // Check if a SCEV contains an AddRecExpr.
9007 struct SCEVHasAddRec {
9008   bool &ContainsAddRec;
9009 
9010   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9011    ContainsAddRec = false;
9012   }
9013 
9014   bool follow(const SCEV *S) {
9015     if (isa<SCEVAddRecExpr>(S)) {
9016       ContainsAddRec = true;
9017 
9018       // Stop recursion: once we collected a term, do not walk its operands.
9019       return false;
9020     }
9021 
9022     // Keep looking.
9023     return true;
9024   }
9025   bool isDone() const { return false; }
9026 };
9027 
9028 // Find factors that are multiplied with an expression that (possibly as a
9029 // subexpression) contains an AddRecExpr. In the expression:
9030 //
9031 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9032 //
9033 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9034 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9035 // parameters as they form a product with an induction variable.
9036 //
9037 // This collector expects all array size parameters to be in the same MulExpr.
9038 // It might be necessary to later add support for collecting parameters that are
9039 // spread over different nested MulExpr.
9040 struct SCEVCollectAddRecMultiplies {
9041   SmallVectorImpl<const SCEV *> &Terms;
9042   ScalarEvolution &SE;
9043 
9044   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9045       : Terms(T), SE(SE) {}
9046 
9047   bool follow(const SCEV *S) {
9048     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9049       bool HasAddRec = false;
9050       SmallVector<const SCEV *, 0> Operands;
9051       for (auto Op : Mul->operands()) {
9052         if (isa<SCEVUnknown>(Op)) {
9053           Operands.push_back(Op);
9054         } else {
9055           bool ContainsAddRec;
9056           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9057           visitAll(Op, ContiansAddRec);
9058           HasAddRec |= ContainsAddRec;
9059         }
9060       }
9061       if (Operands.size() == 0)
9062         return true;
9063 
9064       if (!HasAddRec)
9065         return false;
9066 
9067       Terms.push_back(SE.getMulExpr(Operands));
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 
9079 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9080 /// two places:
9081 ///   1) The strides of AddRec expressions.
9082 ///   2) Unknowns that are multiplied with AddRec expressions.
9083 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9084     SmallVectorImpl<const SCEV *> &Terms) {
9085   SmallVector<const SCEV *, 4> Strides;
9086   SCEVCollectStrides StrideCollector(*this, Strides);
9087   visitAll(Expr, StrideCollector);
9088 
9089   DEBUG({
9090       dbgs() << "Strides:\n";
9091       for (const SCEV *S : Strides)
9092         dbgs() << *S << "\n";
9093     });
9094 
9095   for (const SCEV *S : Strides) {
9096     SCEVCollectTerms TermCollector(Terms);
9097     visitAll(S, TermCollector);
9098   }
9099 
9100   DEBUG({
9101       dbgs() << "Terms:\n";
9102       for (const SCEV *T : Terms)
9103         dbgs() << *T << "\n";
9104     });
9105 
9106   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9107   visitAll(Expr, MulCollector);
9108 }
9109 
9110 static bool findArrayDimensionsRec(ScalarEvolution &SE,
9111                                    SmallVectorImpl<const SCEV *> &Terms,
9112                                    SmallVectorImpl<const SCEV *> &Sizes) {
9113   int Last = Terms.size() - 1;
9114   const SCEV *Step = Terms[Last];
9115 
9116   // End of recursion.
9117   if (Last == 0) {
9118     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
9119       SmallVector<const SCEV *, 2> Qs;
9120       for (const SCEV *Op : M->operands())
9121         if (!isa<SCEVConstant>(Op))
9122           Qs.push_back(Op);
9123 
9124       Step = SE.getMulExpr(Qs);
9125     }
9126 
9127     Sizes.push_back(Step);
9128     return true;
9129   }
9130 
9131   for (const SCEV *&Term : Terms) {
9132     // Normalize the terms before the next call to findArrayDimensionsRec.
9133     const SCEV *Q, *R;
9134     SCEVDivision::divide(SE, Term, Step, &Q, &R);
9135 
9136     // Bail out when GCD does not evenly divide one of the terms.
9137     if (!R->isZero())
9138       return false;
9139 
9140     Term = Q;
9141   }
9142 
9143   // Remove all SCEVConstants.
9144   Terms.erase(
9145       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
9146       Terms.end());
9147 
9148   if (Terms.size() > 0)
9149     if (!findArrayDimensionsRec(SE, Terms, Sizes))
9150       return false;
9151 
9152   Sizes.push_back(Step);
9153   return true;
9154 }
9155 
9156 
9157 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9158 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9159   for (const SCEV *T : Terms)
9160     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
9161       return true;
9162   return false;
9163 }
9164 
9165 // Return the number of product terms in S.
9166 static inline int numberOfTerms(const SCEV *S) {
9167   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9168     return Expr->getNumOperands();
9169   return 1;
9170 }
9171 
9172 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9173   if (isa<SCEVConstant>(T))
9174     return nullptr;
9175 
9176   if (isa<SCEVUnknown>(T))
9177     return T;
9178 
9179   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9180     SmallVector<const SCEV *, 2> Factors;
9181     for (const SCEV *Op : M->operands())
9182       if (!isa<SCEVConstant>(Op))
9183         Factors.push_back(Op);
9184 
9185     return SE.getMulExpr(Factors);
9186   }
9187 
9188   return T;
9189 }
9190 
9191 /// Return the size of an element read or written by Inst.
9192 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9193   Type *Ty;
9194   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9195     Ty = Store->getValueOperand()->getType();
9196   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
9197     Ty = Load->getType();
9198   else
9199     return nullptr;
9200 
9201   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9202   return getSizeOfExpr(ETy, Ty);
9203 }
9204 
9205 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9206                                           SmallVectorImpl<const SCEV *> &Sizes,
9207                                           const SCEV *ElementSize) const {
9208   if (Terms.size() < 1 || !ElementSize)
9209     return;
9210 
9211   // Early return when Terms do not contain parameters: we do not delinearize
9212   // non parametric SCEVs.
9213   if (!containsParameters(Terms))
9214     return;
9215 
9216   DEBUG({
9217       dbgs() << "Terms:\n";
9218       for (const SCEV *T : Terms)
9219         dbgs() << *T << "\n";
9220     });
9221 
9222   // Remove duplicates.
9223   std::sort(Terms.begin(), Terms.end());
9224   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9225 
9226   // Put larger terms first.
9227   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9228     return numberOfTerms(LHS) > numberOfTerms(RHS);
9229   });
9230 
9231   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9232 
9233   // Try to divide all terms by the element size. If term is not divisible by
9234   // element size, proceed with the original term.
9235   for (const SCEV *&Term : Terms) {
9236     const SCEV *Q, *R;
9237     SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
9238     if (!Q->isZero())
9239       Term = Q;
9240   }
9241 
9242   SmallVector<const SCEV *, 4> NewTerms;
9243 
9244   // Remove constant factors.
9245   for (const SCEV *T : Terms)
9246     if (const SCEV *NewT = removeConstantFactors(SE, T))
9247       NewTerms.push_back(NewT);
9248 
9249   DEBUG({
9250       dbgs() << "Terms after sorting:\n";
9251       for (const SCEV *T : NewTerms)
9252         dbgs() << *T << "\n";
9253     });
9254 
9255   if (NewTerms.empty() ||
9256       !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
9257     Sizes.clear();
9258     return;
9259   }
9260 
9261   // The last element to be pushed into Sizes is the size of an element.
9262   Sizes.push_back(ElementSize);
9263 
9264   DEBUG({
9265       dbgs() << "Sizes:\n";
9266       for (const SCEV *S : Sizes)
9267         dbgs() << *S << "\n";
9268     });
9269 }
9270 
9271 void ScalarEvolution::computeAccessFunctions(
9272     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9273     SmallVectorImpl<const SCEV *> &Sizes) {
9274 
9275   // Early exit in case this SCEV is not an affine multivariate function.
9276   if (Sizes.empty())
9277     return;
9278 
9279   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
9280     if (!AR->isAffine())
9281       return;
9282 
9283   const SCEV *Res = Expr;
9284   int Last = Sizes.size() - 1;
9285   for (int i = Last; i >= 0; i--) {
9286     const SCEV *Q, *R;
9287     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
9288 
9289     DEBUG({
9290         dbgs() << "Res: " << *Res << "\n";
9291         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9292         dbgs() << "Res divided by Sizes[i]:\n";
9293         dbgs() << "Quotient: " << *Q << "\n";
9294         dbgs() << "Remainder: " << *R << "\n";
9295       });
9296 
9297     Res = Q;
9298 
9299     // Do not record the last subscript corresponding to the size of elements in
9300     // the array.
9301     if (i == Last) {
9302 
9303       // Bail out if the remainder is too complex.
9304       if (isa<SCEVAddRecExpr>(R)) {
9305         Subscripts.clear();
9306         Sizes.clear();
9307         return;
9308       }
9309 
9310       continue;
9311     }
9312 
9313     // Record the access function for the current subscript.
9314     Subscripts.push_back(R);
9315   }
9316 
9317   // Also push in last position the remainder of the last division: it will be
9318   // the access function of the innermost dimension.
9319   Subscripts.push_back(Res);
9320 
9321   std::reverse(Subscripts.begin(), Subscripts.end());
9322 
9323   DEBUG({
9324       dbgs() << "Subscripts:\n";
9325       for (const SCEV *S : Subscripts)
9326         dbgs() << *S << "\n";
9327     });
9328 }
9329 
9330 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9331 /// sizes of an array access. Returns the remainder of the delinearization that
9332 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
9333 /// the multiples of SCEV coefficients: that is a pattern matching of sub
9334 /// expressions in the stride and base of a SCEV corresponding to the
9335 /// computation of a GCD (greatest common divisor) of base and stride.  When
9336 /// SCEV->delinearize fails, it returns the SCEV unchanged.
9337 ///
9338 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
9339 ///
9340 ///  void foo(long n, long m, long o, double A[n][m][o]) {
9341 ///
9342 ///    for (long i = 0; i < n; i++)
9343 ///      for (long j = 0; j < m; j++)
9344 ///        for (long k = 0; k < o; k++)
9345 ///          A[i][j][k] = 1.0;
9346 ///  }
9347 ///
9348 /// the delinearization input is the following AddRec SCEV:
9349 ///
9350 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9351 ///
9352 /// From this SCEV, we are able to say that the base offset of the access is %A
9353 /// because it appears as an offset that does not divide any of the strides in
9354 /// the loops:
9355 ///
9356 ///  CHECK: Base offset: %A
9357 ///
9358 /// and then SCEV->delinearize determines the size of some of the dimensions of
9359 /// the array as these are the multiples by which the strides are happening:
9360 ///
9361 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9362 ///
9363 /// Note that the outermost dimension remains of UnknownSize because there are
9364 /// no strides that would help identifying the size of the last dimension: when
9365 /// the array has been statically allocated, one could compute the size of that
9366 /// dimension by dividing the overall size of the array by the size of the known
9367 /// dimensions: %m * %o * 8.
9368 ///
9369 /// Finally delinearize provides the access functions for the array reference
9370 /// that does correspond to A[i][j][k] of the above C testcase:
9371 ///
9372 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9373 ///
9374 /// The testcases are checking the output of a function pass:
9375 /// DelinearizationPass that walks through all loads and stores of a function
9376 /// asking for the SCEV of the memory access with respect to all enclosing
9377 /// loops, calling SCEV->delinearize on that and printing the results.
9378 
9379 void ScalarEvolution::delinearize(const SCEV *Expr,
9380                                  SmallVectorImpl<const SCEV *> &Subscripts,
9381                                  SmallVectorImpl<const SCEV *> &Sizes,
9382                                  const SCEV *ElementSize) {
9383   // First step: collect parametric terms.
9384   SmallVector<const SCEV *, 4> Terms;
9385   collectParametricTerms(Expr, Terms);
9386 
9387   if (Terms.empty())
9388     return;
9389 
9390   // Second step: find subscript sizes.
9391   findArrayDimensions(Terms, Sizes, ElementSize);
9392 
9393   if (Sizes.empty())
9394     return;
9395 
9396   // Third step: compute the access functions for each subscript.
9397   computeAccessFunctions(Expr, Subscripts, Sizes);
9398 
9399   if (Subscripts.empty())
9400     return;
9401 
9402   DEBUG({
9403       dbgs() << "succeeded to delinearize " << *Expr << "\n";
9404       dbgs() << "ArrayDecl[UnknownSize]";
9405       for (const SCEV *S : Sizes)
9406         dbgs() << "[" << *S << "]";
9407 
9408       dbgs() << "\nArrayRef";
9409       for (const SCEV *S : Subscripts)
9410         dbgs() << "[" << *S << "]";
9411       dbgs() << "\n";
9412     });
9413 }
9414 
9415 //===----------------------------------------------------------------------===//
9416 //                   SCEVCallbackVH Class Implementation
9417 //===----------------------------------------------------------------------===//
9418 
9419 void ScalarEvolution::SCEVCallbackVH::deleted() {
9420   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9421   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9422     SE->ConstantEvolutionLoopExitValue.erase(PN);
9423   SE->eraseValueFromMap(getValPtr());
9424   // this now dangles!
9425 }
9426 
9427 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
9428   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
9429 
9430   // Forget all the expressions associated with users of the old value,
9431   // so that future queries will recompute the expressions using the new
9432   // value.
9433   Value *Old = getValPtr();
9434   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
9435   SmallPtrSet<User *, 8> Visited;
9436   while (!Worklist.empty()) {
9437     User *U = Worklist.pop_back_val();
9438     // Deleting the Old value will cause this to dangle. Postpone
9439     // that until everything else is done.
9440     if (U == Old)
9441       continue;
9442     if (!Visited.insert(U).second)
9443       continue;
9444     if (PHINode *PN = dyn_cast<PHINode>(U))
9445       SE->ConstantEvolutionLoopExitValue.erase(PN);
9446     SE->eraseValueFromMap(U);
9447     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
9448   }
9449   // Delete the Old value.
9450   if (PHINode *PN = dyn_cast<PHINode>(Old))
9451     SE->ConstantEvolutionLoopExitValue.erase(PN);
9452   SE->eraseValueFromMap(Old);
9453   // this now dangles!
9454 }
9455 
9456 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
9457   : CallbackVH(V), SE(se) {}
9458 
9459 //===----------------------------------------------------------------------===//
9460 //                   ScalarEvolution Class Implementation
9461 //===----------------------------------------------------------------------===//
9462 
9463 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9464                                  AssumptionCache &AC, DominatorTree &DT,
9465                                  LoopInfo &LI)
9466     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9467       CouldNotCompute(new SCEVCouldNotCompute()),
9468       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9469       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9470       FirstUnknown(nullptr) {
9471 
9472   // To use guards for proving predicates, we need to scan every instruction in
9473   // relevant basic blocks, and not just terminators.  Doing this is a waste of
9474   // time if the IR does not actually contain any calls to
9475   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
9476   //
9477   // This pessimizes the case where a pass that preserves ScalarEvolution wants
9478   // to _add_ guards to the module when there weren't any before, and wants
9479   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
9480   // efficient in lieu of being smart in that rather obscure case.
9481 
9482   auto *GuardDecl = F.getParent()->getFunction(
9483       Intrinsic::getName(Intrinsic::experimental_guard));
9484   HasGuards = GuardDecl && !GuardDecl->use_empty();
9485 }
9486 
9487 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9488     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
9489       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
9490       ValueExprMap(std::move(Arg.ValueExprMap)),
9491       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
9492       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9493       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
9494       PredicatedBackedgeTakenCounts(
9495           std::move(Arg.PredicatedBackedgeTakenCounts)),
9496       ConstantEvolutionLoopExitValue(
9497           std::move(Arg.ConstantEvolutionLoopExitValue)),
9498       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9499       LoopDispositions(std::move(Arg.LoopDispositions)),
9500       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
9501       BlockDispositions(std::move(Arg.BlockDispositions)),
9502       UnsignedRanges(std::move(Arg.UnsignedRanges)),
9503       SignedRanges(std::move(Arg.SignedRanges)),
9504       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
9505       UniquePreds(std::move(Arg.UniquePreds)),
9506       SCEVAllocator(std::move(Arg.SCEVAllocator)),
9507       FirstUnknown(Arg.FirstUnknown) {
9508   Arg.FirstUnknown = nullptr;
9509 }
9510 
9511 ScalarEvolution::~ScalarEvolution() {
9512   // Iterate through all the SCEVUnknown instances and call their
9513   // destructors, so that they release their references to their values.
9514   for (SCEVUnknown *U = FirstUnknown; U;) {
9515     SCEVUnknown *Tmp = U;
9516     U = U->Next;
9517     Tmp->~SCEVUnknown();
9518   }
9519   FirstUnknown = nullptr;
9520 
9521   ExprValueMap.clear();
9522   ValueExprMap.clear();
9523   HasRecMap.clear();
9524 
9525   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9526   // that a loop had multiple computable exits.
9527   for (auto &BTCI : BackedgeTakenCounts)
9528     BTCI.second.clear();
9529   for (auto &BTCI : PredicatedBackedgeTakenCounts)
9530     BTCI.second.clear();
9531 
9532   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
9533   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
9534   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
9535 }
9536 
9537 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
9538   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
9539 }
9540 
9541 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
9542                           const Loop *L) {
9543   // Print all inner loops first
9544   for (Loop *I : *L)
9545     PrintLoopInfo(OS, SE, I);
9546 
9547   OS << "Loop ";
9548   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9549   OS << ": ";
9550 
9551   SmallVector<BasicBlock *, 8> ExitBlocks;
9552   L->getExitBlocks(ExitBlocks);
9553   if (ExitBlocks.size() != 1)
9554     OS << "<multiple exits> ";
9555 
9556   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9557     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
9558   } else {
9559     OS << "Unpredictable backedge-taken count. ";
9560   }
9561 
9562   OS << "\n"
9563         "Loop ";
9564   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9565   OS << ": ";
9566 
9567   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9568     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9569     if (SE->isBackedgeTakenCountMaxOrZero(L))
9570       OS << ", actual taken count either this or zero.";
9571   } else {
9572     OS << "Unpredictable max backedge-taken count. ";
9573   }
9574 
9575   OS << "\n"
9576         "Loop ";
9577   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9578   OS << ": ";
9579 
9580   SCEVUnionPredicate Pred;
9581   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9582   if (!isa<SCEVCouldNotCompute>(PBT)) {
9583     OS << "Predicated backedge-taken count is " << *PBT << "\n";
9584     OS << " Predicates:\n";
9585     Pred.print(OS, 4);
9586   } else {
9587     OS << "Unpredictable predicated backedge-taken count. ";
9588   }
9589   OS << "\n";
9590 }
9591 
9592 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
9593   switch (LD) {
9594   case ScalarEvolution::LoopVariant:
9595     return "Variant";
9596   case ScalarEvolution::LoopInvariant:
9597     return "Invariant";
9598   case ScalarEvolution::LoopComputable:
9599     return "Computable";
9600   }
9601   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
9602 }
9603 
9604 void ScalarEvolution::print(raw_ostream &OS) const {
9605   // ScalarEvolution's implementation of the print method is to print
9606   // out SCEV values of all instructions that are interesting. Doing
9607   // this potentially causes it to create new SCEV objects though,
9608   // which technically conflicts with the const qualifier. This isn't
9609   // observable from outside the class though, so casting away the
9610   // const isn't dangerous.
9611   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9612 
9613   OS << "Classifying expressions for: ";
9614   F.printAsOperand(OS, /*PrintType=*/false);
9615   OS << "\n";
9616   for (Instruction &I : instructions(F))
9617     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9618       OS << I << '\n';
9619       OS << "  -->  ";
9620       const SCEV *SV = SE.getSCEV(&I);
9621       SV->print(OS);
9622       if (!isa<SCEVCouldNotCompute>(SV)) {
9623         OS << " U: ";
9624         SE.getUnsignedRange(SV).print(OS);
9625         OS << " S: ";
9626         SE.getSignedRange(SV).print(OS);
9627       }
9628 
9629       const Loop *L = LI.getLoopFor(I.getParent());
9630 
9631       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
9632       if (AtUse != SV) {
9633         OS << "  -->  ";
9634         AtUse->print(OS);
9635         if (!isa<SCEVCouldNotCompute>(AtUse)) {
9636           OS << " U: ";
9637           SE.getUnsignedRange(AtUse).print(OS);
9638           OS << " S: ";
9639           SE.getSignedRange(AtUse).print(OS);
9640         }
9641       }
9642 
9643       if (L) {
9644         OS << "\t\t" "Exits: ";
9645         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
9646         if (!SE.isLoopInvariant(ExitValue, L)) {
9647           OS << "<<Unknown>>";
9648         } else {
9649           OS << *ExitValue;
9650         }
9651 
9652         bool First = true;
9653         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
9654           if (First) {
9655             OS << "\t\t" "LoopDispositions: { ";
9656             First = false;
9657           } else {
9658             OS << ", ";
9659           }
9660 
9661           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9662           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
9663         }
9664 
9665         for (auto *InnerL : depth_first(L)) {
9666           if (InnerL == L)
9667             continue;
9668           if (First) {
9669             OS << "\t\t" "LoopDispositions: { ";
9670             First = false;
9671           } else {
9672             OS << ", ";
9673           }
9674 
9675           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9676           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
9677         }
9678 
9679         OS << " }";
9680       }
9681 
9682       OS << "\n";
9683     }
9684 
9685   OS << "Determining loop execution counts for: ";
9686   F.printAsOperand(OS, /*PrintType=*/false);
9687   OS << "\n";
9688   for (Loop *I : LI)
9689     PrintLoopInfo(OS, &SE, I);
9690 }
9691 
9692 ScalarEvolution::LoopDisposition
9693 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
9694   auto &Values = LoopDispositions[S];
9695   for (auto &V : Values) {
9696     if (V.getPointer() == L)
9697       return V.getInt();
9698   }
9699   Values.emplace_back(L, LoopVariant);
9700   LoopDisposition D = computeLoopDisposition(S, L);
9701   auto &Values2 = LoopDispositions[S];
9702   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9703     if (V.getPointer() == L) {
9704       V.setInt(D);
9705       break;
9706     }
9707   }
9708   return D;
9709 }
9710 
9711 ScalarEvolution::LoopDisposition
9712 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
9713   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9714   case scConstant:
9715     return LoopInvariant;
9716   case scTruncate:
9717   case scZeroExtend:
9718   case scSignExtend:
9719     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
9720   case scAddRecExpr: {
9721     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9722 
9723     // If L is the addrec's loop, it's computable.
9724     if (AR->getLoop() == L)
9725       return LoopComputable;
9726 
9727     // Add recurrences are never invariant in the function-body (null loop).
9728     if (!L)
9729       return LoopVariant;
9730 
9731     // This recurrence is variant w.r.t. L if L contains AR's loop.
9732     if (L->contains(AR->getLoop()))
9733       return LoopVariant;
9734 
9735     // This recurrence is invariant w.r.t. L if AR's loop contains L.
9736     if (AR->getLoop()->contains(L))
9737       return LoopInvariant;
9738 
9739     // This recurrence is variant w.r.t. L if any of its operands
9740     // are variant.
9741     for (auto *Op : AR->operands())
9742       if (!isLoopInvariant(Op, L))
9743         return LoopVariant;
9744 
9745     // Otherwise it's loop-invariant.
9746     return LoopInvariant;
9747   }
9748   case scAddExpr:
9749   case scMulExpr:
9750   case scUMaxExpr:
9751   case scSMaxExpr: {
9752     bool HasVarying = false;
9753     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9754       LoopDisposition D = getLoopDisposition(Op, L);
9755       if (D == LoopVariant)
9756         return LoopVariant;
9757       if (D == LoopComputable)
9758         HasVarying = true;
9759     }
9760     return HasVarying ? LoopComputable : LoopInvariant;
9761   }
9762   case scUDivExpr: {
9763     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9764     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9765     if (LD == LoopVariant)
9766       return LoopVariant;
9767     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9768     if (RD == LoopVariant)
9769       return LoopVariant;
9770     return (LD == LoopInvariant && RD == LoopInvariant) ?
9771            LoopInvariant : LoopComputable;
9772   }
9773   case scUnknown:
9774     // All non-instruction values are loop invariant.  All instructions are loop
9775     // invariant if they are not contained in the specified loop.
9776     // Instructions are never considered invariant in the function body
9777     // (null loop) because they are defined within the "loop".
9778     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
9779       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9780     return LoopInvariant;
9781   case scCouldNotCompute:
9782     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9783   }
9784   llvm_unreachable("Unknown SCEV kind!");
9785 }
9786 
9787 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9788   return getLoopDisposition(S, L) == LoopInvariant;
9789 }
9790 
9791 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9792   return getLoopDisposition(S, L) == LoopComputable;
9793 }
9794 
9795 ScalarEvolution::BlockDisposition
9796 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9797   auto &Values = BlockDispositions[S];
9798   for (auto &V : Values) {
9799     if (V.getPointer() == BB)
9800       return V.getInt();
9801   }
9802   Values.emplace_back(BB, DoesNotDominateBlock);
9803   BlockDisposition D = computeBlockDisposition(S, BB);
9804   auto &Values2 = BlockDispositions[S];
9805   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9806     if (V.getPointer() == BB) {
9807       V.setInt(D);
9808       break;
9809     }
9810   }
9811   return D;
9812 }
9813 
9814 ScalarEvolution::BlockDisposition
9815 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
9816   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
9817   case scConstant:
9818     return ProperlyDominatesBlock;
9819   case scTruncate:
9820   case scZeroExtend:
9821   case scSignExtend:
9822     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
9823   case scAddRecExpr: {
9824     // This uses a "dominates" query instead of "properly dominates" query
9825     // to test for proper dominance too, because the instruction which
9826     // produces the addrec's value is a PHI, and a PHI effectively properly
9827     // dominates its entire containing block.
9828     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9829     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
9830       return DoesNotDominateBlock;
9831 
9832     // Fall through into SCEVNAryExpr handling.
9833     LLVM_FALLTHROUGH;
9834   }
9835   case scAddExpr:
9836   case scMulExpr:
9837   case scUMaxExpr:
9838   case scSMaxExpr: {
9839     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
9840     bool Proper = true;
9841     for (const SCEV *NAryOp : NAry->operands()) {
9842       BlockDisposition D = getBlockDisposition(NAryOp, BB);
9843       if (D == DoesNotDominateBlock)
9844         return DoesNotDominateBlock;
9845       if (D == DominatesBlock)
9846         Proper = false;
9847     }
9848     return Proper ? ProperlyDominatesBlock : DominatesBlock;
9849   }
9850   case scUDivExpr: {
9851     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
9852     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9853     BlockDisposition LD = getBlockDisposition(LHS, BB);
9854     if (LD == DoesNotDominateBlock)
9855       return DoesNotDominateBlock;
9856     BlockDisposition RD = getBlockDisposition(RHS, BB);
9857     if (RD == DoesNotDominateBlock)
9858       return DoesNotDominateBlock;
9859     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9860       ProperlyDominatesBlock : DominatesBlock;
9861   }
9862   case scUnknown:
9863     if (Instruction *I =
9864           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9865       if (I->getParent() == BB)
9866         return DominatesBlock;
9867       if (DT.properlyDominates(I->getParent(), BB))
9868         return ProperlyDominatesBlock;
9869       return DoesNotDominateBlock;
9870     }
9871     return ProperlyDominatesBlock;
9872   case scCouldNotCompute:
9873     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9874   }
9875   llvm_unreachable("Unknown SCEV kind!");
9876 }
9877 
9878 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9879   return getBlockDisposition(S, BB) >= DominatesBlock;
9880 }
9881 
9882 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9883   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
9884 }
9885 
9886 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
9887   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
9888 }
9889 
9890 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9891   ValuesAtScopes.erase(S);
9892   LoopDispositions.erase(S);
9893   BlockDispositions.erase(S);
9894   UnsignedRanges.erase(S);
9895   SignedRanges.erase(S);
9896   ExprValueMap.erase(S);
9897   HasRecMap.erase(S);
9898 
9899   auto RemoveSCEVFromBackedgeMap =
9900       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9901         for (auto I = Map.begin(), E = Map.end(); I != E;) {
9902           BackedgeTakenInfo &BEInfo = I->second;
9903           if (BEInfo.hasOperand(S, this)) {
9904             BEInfo.clear();
9905             Map.erase(I++);
9906           } else
9907             ++I;
9908         }
9909       };
9910 
9911   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9912   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
9913 }
9914 
9915 typedef DenseMap<const Loop *, std::string> VerifyMap;
9916 
9917 /// replaceSubString - Replaces all occurrences of From in Str with To.
9918 static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9919   size_t Pos = 0;
9920   while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9921     Str.replace(Pos, From.size(), To.data(), To.size());
9922     Pos += To.size();
9923   }
9924 }
9925 
9926 /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9927 static void
9928 getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
9929   std::string &S = Map[L];
9930   if (S.empty()) {
9931     raw_string_ostream OS(S);
9932     SE.getBackedgeTakenCount(L)->print(OS);
9933 
9934     // false and 0 are semantically equivalent. This can happen in dead loops.
9935     replaceSubString(OS.str(), "false", "0");
9936     // Remove wrap flags, their use in SCEV is highly fragile.
9937     // FIXME: Remove this when SCEV gets smarter about them.
9938     replaceSubString(OS.str(), "<nw>", "");
9939     replaceSubString(OS.str(), "<nsw>", "");
9940     replaceSubString(OS.str(), "<nuw>", "");
9941   }
9942 
9943   for (auto *R : reverse(*L))
9944     getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
9945 }
9946 
9947 void ScalarEvolution::verify() const {
9948   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9949 
9950   // Gather stringified backedge taken counts for all loops using SCEV's caches.
9951   // FIXME: It would be much better to store actual values instead of strings,
9952   //        but SCEV pointers will change if we drop the caches.
9953   VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
9954   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9955     getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9956 
9957   // Gather stringified backedge taken counts for all loops using a fresh
9958   // ScalarEvolution object.
9959   ScalarEvolution SE2(F, TLI, AC, DT, LI);
9960   for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9961     getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
9962 
9963   // Now compare whether they're the same with and without caches. This allows
9964   // verifying that no pass changed the cache.
9965   assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9966          "New loops suddenly appeared!");
9967 
9968   for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9969                            OldE = BackedgeDumpsOld.end(),
9970                            NewI = BackedgeDumpsNew.begin();
9971        OldI != OldE; ++OldI, ++NewI) {
9972     assert(OldI->first == NewI->first && "Loop order changed!");
9973 
9974     // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9975     // changes.
9976     // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
9977     // means that a pass is buggy or SCEV has to learn a new pattern but is
9978     // usually not harmful.
9979     if (OldI->second != NewI->second &&
9980         OldI->second.find("undef") == std::string::npos &&
9981         NewI->second.find("undef") == std::string::npos &&
9982         OldI->second != "***COULDNOTCOMPUTE***" &&
9983         NewI->second != "***COULDNOTCOMPUTE***") {
9984       dbgs() << "SCEVValidator: SCEV for loop '"
9985              << OldI->first->getHeader()->getName()
9986              << "' changed from '" << OldI->second
9987              << "' to '" << NewI->second << "'!\n";
9988       std::abort();
9989     }
9990   }
9991 
9992   // TODO: Verify more things.
9993 }
9994 
9995 bool ScalarEvolution::invalidate(
9996     Function &F, const PreservedAnalyses &PA,
9997     FunctionAnalysisManager::Invalidator &Inv) {
9998   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
9999   // of its dependencies is invalidated.
10000   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10001   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10002          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10003          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10004          Inv.invalidate<LoopAnalysis>(F, PA);
10005 }
10006 
10007 AnalysisKey ScalarEvolutionAnalysis::Key;
10008 
10009 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10010                                              FunctionAnalysisManager &AM) {
10011   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10012                          AM.getResult<AssumptionAnalysis>(F),
10013                          AM.getResult<DominatorTreeAnalysis>(F),
10014                          AM.getResult<LoopAnalysis>(F));
10015 }
10016 
10017 PreservedAnalyses
10018 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10019   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10020   return PreservedAnalyses::all();
10021 }
10022 
10023 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10024                       "Scalar Evolution Analysis", false, true)
10025 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10026 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10027 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10028 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10029 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10030                     "Scalar Evolution Analysis", false, true)
10031 char ScalarEvolutionWrapperPass::ID = 0;
10032 
10033 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10034   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10035 }
10036 
10037 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10038   SE.reset(new ScalarEvolution(
10039       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10040       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10041       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10042       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10043   return false;
10044 }
10045 
10046 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10047 
10048 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10049   SE->print(OS);
10050 }
10051 
10052 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10053   if (!VerifySCEV)
10054     return;
10055 
10056   SE->verify();
10057 }
10058 
10059 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10060   AU.setPreservesAll();
10061   AU.addRequiredTransitive<AssumptionCacheTracker>();
10062   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10063   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10064   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10065 }
10066 
10067 const SCEVPredicate *
10068 ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10069                                    const SCEVConstant *RHS) {
10070   FoldingSetNodeID ID;
10071   // Unique this node based on the arguments
10072   ID.AddInteger(SCEVPredicate::P_Equal);
10073   ID.AddPointer(LHS);
10074   ID.AddPointer(RHS);
10075   void *IP = nullptr;
10076   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10077     return S;
10078   SCEVEqualPredicate *Eq = new (SCEVAllocator)
10079       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10080   UniquePreds.InsertNode(Eq, IP);
10081   return Eq;
10082 }
10083 
10084 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10085     const SCEVAddRecExpr *AR,
10086     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10087   FoldingSetNodeID ID;
10088   // Unique this node based on the arguments
10089   ID.AddInteger(SCEVPredicate::P_Wrap);
10090   ID.AddPointer(AR);
10091   ID.AddInteger(AddedFlags);
10092   void *IP = nullptr;
10093   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10094     return S;
10095   auto *OF = new (SCEVAllocator)
10096       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10097   UniquePreds.InsertNode(OF, IP);
10098   return OF;
10099 }
10100 
10101 namespace {
10102 
10103 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10104 public:
10105   /// Rewrites \p S in the context of a loop L and the SCEV predication
10106   /// infrastructure.
10107   ///
10108   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
10109   /// equivalences present in \p Pred.
10110   ///
10111   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
10112   /// \p NewPreds such that the result will be an AddRecExpr.
10113   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10114                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10115                              SCEVUnionPredicate *Pred) {
10116     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
10117     return Rewriter.visit(S);
10118   }
10119 
10120   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10121                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
10122                         SCEVUnionPredicate *Pred)
10123       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
10124 
10125   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10126     if (Pred) {
10127       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
10128       for (auto *Pred : ExprPreds)
10129         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
10130           if (IPred->getLHS() == Expr)
10131             return IPred->getRHS();
10132     }
10133 
10134     return Expr;
10135   }
10136 
10137   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10138     const SCEV *Operand = visit(Expr->getOperand());
10139     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10140     if (AR && AR->getLoop() == L && AR->isAffine()) {
10141       // This couldn't be folded because the operand didn't have the nuw
10142       // flag. Add the nusw flag as an assumption that we could make.
10143       const SCEV *Step = AR->getStepRecurrence(SE);
10144       Type *Ty = Expr->getType();
10145       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10146         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10147                                 SE.getSignExtendExpr(Step, Ty), L,
10148                                 AR->getNoWrapFlags());
10149     }
10150     return SE.getZeroExtendExpr(Operand, Expr->getType());
10151   }
10152 
10153   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10154     const SCEV *Operand = visit(Expr->getOperand());
10155     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
10156     if (AR && AR->getLoop() == L && AR->isAffine()) {
10157       // This couldn't be folded because the operand didn't have the nsw
10158       // flag. Add the nssw flag as an assumption that we could make.
10159       const SCEV *Step = AR->getStepRecurrence(SE);
10160       Type *Ty = Expr->getType();
10161       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10162         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10163                                 SE.getSignExtendExpr(Step, Ty), L,
10164                                 AR->getNoWrapFlags());
10165     }
10166     return SE.getSignExtendExpr(Operand, Expr->getType());
10167   }
10168 
10169 private:
10170   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10171                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10172     auto *A = SE.getWrapPredicate(AR, AddedFlags);
10173     if (!NewPreds) {
10174       // Check if we've already made this assumption.
10175       return Pred && Pred->implies(A);
10176     }
10177     NewPreds->insert(A);
10178     return true;
10179   }
10180 
10181   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
10182   SCEVUnionPredicate *Pred;
10183   const Loop *L;
10184 };
10185 } // end anonymous namespace
10186 
10187 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
10188                                                    SCEVUnionPredicate &Preds) {
10189   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
10190 }
10191 
10192 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
10193     const SCEV *S, const Loop *L,
10194     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
10195 
10196   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
10197   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
10198   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10199 
10200   if (!AddRec)
10201     return nullptr;
10202 
10203   // Since the transformation was successful, we can now transfer the SCEV
10204   // predicates.
10205   for (auto *P : TransformPreds)
10206     Preds.insert(P);
10207 
10208   return AddRec;
10209 }
10210 
10211 /// SCEV predicates
10212 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10213                              SCEVPredicateKind Kind)
10214     : FastID(ID), Kind(Kind) {}
10215 
10216 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10217                                        const SCEVUnknown *LHS,
10218                                        const SCEVConstant *RHS)
10219     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10220 
10221 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10222   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
10223 
10224   if (!Op)
10225     return false;
10226 
10227   return Op->LHS == LHS && Op->RHS == RHS;
10228 }
10229 
10230 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10231 
10232 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10233 
10234 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10235   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10236 }
10237 
10238 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10239                                      const SCEVAddRecExpr *AR,
10240                                      IncrementWrapFlags Flags)
10241     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10242 
10243 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10244 
10245 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10246   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10247 
10248   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10249 }
10250 
10251 bool SCEVWrapPredicate::isAlwaysTrue() const {
10252   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10253   IncrementWrapFlags IFlags = Flags;
10254 
10255   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10256     IFlags = clearFlags(IFlags, IncrementNSSW);
10257 
10258   return IFlags == IncrementAnyWrap;
10259 }
10260 
10261 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10262   OS.indent(Depth) << *getExpr() << " Added Flags: ";
10263   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10264     OS << "<nusw>";
10265   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10266     OS << "<nssw>";
10267   OS << "\n";
10268 }
10269 
10270 SCEVWrapPredicate::IncrementWrapFlags
10271 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10272                                    ScalarEvolution &SE) {
10273   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10274   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10275 
10276   // We can safely transfer the NSW flag as NSSW.
10277   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10278     ImpliedFlags = IncrementNSSW;
10279 
10280   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10281     // If the increment is positive, the SCEV NUW flag will also imply the
10282     // WrapPredicate NUSW flag.
10283     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10284       if (Step->getValue()->getValue().isNonNegative())
10285         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10286   }
10287 
10288   return ImpliedFlags;
10289 }
10290 
10291 /// Union predicates don't get cached so create a dummy set ID for it.
10292 SCEVUnionPredicate::SCEVUnionPredicate()
10293     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10294 
10295 bool SCEVUnionPredicate::isAlwaysTrue() const {
10296   return all_of(Preds,
10297                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
10298 }
10299 
10300 ArrayRef<const SCEVPredicate *>
10301 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10302   auto I = SCEVToPreds.find(Expr);
10303   if (I == SCEVToPreds.end())
10304     return ArrayRef<const SCEVPredicate *>();
10305   return I->second;
10306 }
10307 
10308 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10309   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
10310     return all_of(Set->Preds,
10311                   [this](const SCEVPredicate *I) { return this->implies(I); });
10312 
10313   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10314   if (ScevPredsIt == SCEVToPreds.end())
10315     return false;
10316   auto &SCEVPreds = ScevPredsIt->second;
10317 
10318   return any_of(SCEVPreds,
10319                 [N](const SCEVPredicate *I) { return I->implies(N); });
10320 }
10321 
10322 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10323 
10324 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10325   for (auto Pred : Preds)
10326     Pred->print(OS, Depth);
10327 }
10328 
10329 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10330   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
10331     for (auto Pred : Set->Preds)
10332       add(Pred);
10333     return;
10334   }
10335 
10336   if (implies(N))
10337     return;
10338 
10339   const SCEV *Key = N->getExpr();
10340   assert(Key && "Only SCEVUnionPredicate doesn't have an "
10341                 " associated expression!");
10342 
10343   SCEVToPreds[Key].push_back(N);
10344   Preds.push_back(N);
10345 }
10346 
10347 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10348                                                      Loop &L)
10349     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
10350 
10351 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10352   const SCEV *Expr = SE.getSCEV(V);
10353   RewriteEntry &Entry = RewriteMap[Expr];
10354 
10355   // If we already have an entry and the version matches, return it.
10356   if (Entry.second && Generation == Entry.first)
10357     return Entry.second;
10358 
10359   // We found an entry but it's stale. Rewrite the stale entry
10360   // according to the current predicate.
10361   if (Entry.second)
10362     Expr = Entry.second;
10363 
10364   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
10365   Entry = {Generation, NewSCEV};
10366 
10367   return NewSCEV;
10368 }
10369 
10370 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10371   if (!BackedgeCount) {
10372     SCEVUnionPredicate BackedgePred;
10373     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10374     addPredicate(BackedgePred);
10375   }
10376   return BackedgeCount;
10377 }
10378 
10379 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10380   if (Preds.implies(&Pred))
10381     return;
10382   Preds.add(&Pred);
10383   updateGeneration();
10384 }
10385 
10386 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10387   return Preds;
10388 }
10389 
10390 void PredicatedScalarEvolution::updateGeneration() {
10391   // If the generation number wrapped recompute everything.
10392   if (++Generation == 0) {
10393     for (auto &II : RewriteMap) {
10394       const SCEV *Rewritten = II.second.second;
10395       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
10396     }
10397   }
10398 }
10399 
10400 void PredicatedScalarEvolution::setNoOverflow(
10401     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10402   const SCEV *Expr = getSCEV(V);
10403   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10404 
10405   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10406 
10407   // Clear the statically implied flags.
10408   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10409   addPredicate(*SE.getWrapPredicate(AR, Flags));
10410 
10411   auto II = FlagsMap.insert({V, Flags});
10412   if (!II.second)
10413     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10414 }
10415 
10416 bool PredicatedScalarEvolution::hasNoOverflow(
10417     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10418   const SCEV *Expr = getSCEV(V);
10419   const auto *AR = cast<SCEVAddRecExpr>(Expr);
10420 
10421   Flags = SCEVWrapPredicate::clearFlags(
10422       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10423 
10424   auto II = FlagsMap.find(V);
10425 
10426   if (II != FlagsMap.end())
10427     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10428 
10429   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10430 }
10431 
10432 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
10433   const SCEV *Expr = this->getSCEV(V);
10434   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
10435   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
10436 
10437   if (!New)
10438     return nullptr;
10439 
10440   for (auto *P : NewPreds)
10441     Preds.add(P);
10442 
10443   updateGeneration();
10444   RewriteMap[SE.getSCEV(V)] = {Generation, New};
10445   return New;
10446 }
10447 
10448 PredicatedScalarEvolution::PredicatedScalarEvolution(
10449     const PredicatedScalarEvolution &Init)
10450     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10451       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
10452   for (const auto &I : Init.FlagsMap)
10453     FlagsMap.insert(I);
10454 }
10455 
10456 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
10457   // For each block.
10458   for (auto *BB : L.getBlocks())
10459     for (auto &I : *BB) {
10460       if (!SE.isSCEVable(I.getType()))
10461         continue;
10462 
10463       auto *Expr = SE.getSCEV(&I);
10464       auto II = RewriteMap.find(Expr);
10465 
10466       if (II == RewriteMap.end())
10467         continue;
10468 
10469       // Don't print things that are not interesting.
10470       if (II->second.second == Expr)
10471         continue;
10472 
10473       OS.indent(Depth) << "[PSE]" << I << ":\n";
10474       OS.indent(Depth + 2) << *Expr << "\n";
10475       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
10476     }
10477 }
10478