xref: /llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp (revision 4cad61adb32337b27bcc17827d51ccbb160ed492)
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/KnownBits.h"
93 #include "llvm/Support/MathExtras.h"
94 #include "llvm/Support/SaveAndRestore.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include <algorithm>
97 using namespace llvm;
98 
99 #define DEBUG_TYPE "scalar-evolution"
100 
101 STATISTIC(NumArrayLenItCounts,
102           "Number of trip counts computed with array length");
103 STATISTIC(NumTripCountsComputed,
104           "Number of loops with predictable loop counts");
105 STATISTIC(NumTripCountsNotComputed,
106           "Number of loops without predictable loop counts");
107 STATISTIC(NumBruteForceTripCountsComputed,
108           "Number of loops with trip counts computed by force");
109 
110 static cl::opt<unsigned>
111 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
112                         cl::desc("Maximum number of iterations SCEV will "
113                                  "symbolically execute a constant "
114                                  "derived loop"),
115                         cl::init(100));
116 
117 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
118 static cl::opt<bool>
119 VerifySCEV("verify-scev",
120            cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
121 static cl::opt<bool>
122     VerifySCEVMap("verify-scev-maps",
123                   cl::desc("Verify no dangling value in ScalarEvolution's "
124                            "ExprValueMap (slow)"));
125 
126 static cl::opt<unsigned> MulOpsInlineThreshold(
127     "scev-mulops-inline-threshold", cl::Hidden,
128     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
129     cl::init(32));
130 
131 static cl::opt<unsigned> AddOpsInlineThreshold(
132     "scev-addops-inline-threshold", cl::Hidden,
133     cl::desc("Threshold for inlining addition operands into a SCEV"),
134     cl::init(500));
135 
136 static cl::opt<unsigned> MaxSCEVCompareDepth(
137     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
138     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
139     cl::init(32));
140 
141 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
142     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
143     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
144     cl::init(2));
145 
146 static cl::opt<unsigned> MaxValueCompareDepth(
147     "scalar-evolution-max-value-compare-depth", cl::Hidden,
148     cl::desc("Maximum depth of recursive value complexity comparisons"),
149     cl::init(2));
150 
151 static cl::opt<unsigned>
152     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
153                   cl::desc("Maximum depth of recursive arithmetics"),
154                   cl::init(32));
155 
156 static cl::opt<unsigned> MaxConstantEvolvingDepth(
157     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
158     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
159 
160 static cl::opt<unsigned>
161     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
162                 cl::desc("Maximum depth of recursive SExt/ZExt"),
163                 cl::init(8));
164 
165 static cl::opt<unsigned>
166     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
167                   cl::desc("Max coefficients in AddRec during evolving"),
168                   cl::init(16));
169 
170 //===----------------------------------------------------------------------===//
171 //                           SCEV class definitions
172 //===----------------------------------------------------------------------===//
173 
174 //===----------------------------------------------------------------------===//
175 // Implementation of the SCEV class.
176 //
177 
178 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
179 LLVM_DUMP_METHOD void SCEV::dump() const {
180   print(dbgs());
181   dbgs() << '\n';
182 }
183 #endif
184 
185 void SCEV::print(raw_ostream &OS) const {
186   switch (static_cast<SCEVTypes>(getSCEVType())) {
187   case scConstant:
188     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
189     return;
190   case scTruncate: {
191     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
192     const SCEV *Op = Trunc->getOperand();
193     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
194        << *Trunc->getType() << ")";
195     return;
196   }
197   case scZeroExtend: {
198     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
199     const SCEV *Op = ZExt->getOperand();
200     OS << "(zext " << *Op->getType() << " " << *Op << " to "
201        << *ZExt->getType() << ")";
202     return;
203   }
204   case scSignExtend: {
205     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
206     const SCEV *Op = SExt->getOperand();
207     OS << "(sext " << *Op->getType() << " " << *Op << " to "
208        << *SExt->getType() << ")";
209     return;
210   }
211   case scAddRecExpr: {
212     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
213     OS << "{" << *AR->getOperand(0);
214     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
215       OS << ",+," << *AR->getOperand(i);
216     OS << "}<";
217     if (AR->hasNoUnsignedWrap())
218       OS << "nuw><";
219     if (AR->hasNoSignedWrap())
220       OS << "nsw><";
221     if (AR->hasNoSelfWrap() &&
222         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
223       OS << "nw><";
224     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
225     OS << ">";
226     return;
227   }
228   case scAddExpr:
229   case scMulExpr:
230   case scUMaxExpr:
231   case scSMaxExpr: {
232     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
233     const char *OpStr = nullptr;
234     switch (NAry->getSCEVType()) {
235     case scAddExpr: OpStr = " + "; break;
236     case scMulExpr: OpStr = " * "; break;
237     case scUMaxExpr: OpStr = " umax "; break;
238     case scSMaxExpr: OpStr = " smax "; break;
239     }
240     OS << "(";
241     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
242          I != E; ++I) {
243       OS << **I;
244       if (std::next(I) != E)
245         OS << OpStr;
246     }
247     OS << ")";
248     switch (NAry->getSCEVType()) {
249     case scAddExpr:
250     case scMulExpr:
251       if (NAry->hasNoUnsignedWrap())
252         OS << "<nuw>";
253       if (NAry->hasNoSignedWrap())
254         OS << "<nsw>";
255     }
256     return;
257   }
258   case scUDivExpr: {
259     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
260     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
261     return;
262   }
263   case scUnknown: {
264     const SCEVUnknown *U = cast<SCEVUnknown>(this);
265     Type *AllocTy;
266     if (U->isSizeOf(AllocTy)) {
267       OS << "sizeof(" << *AllocTy << ")";
268       return;
269     }
270     if (U->isAlignOf(AllocTy)) {
271       OS << "alignof(" << *AllocTy << ")";
272       return;
273     }
274 
275     Type *CTy;
276     Constant *FieldNo;
277     if (U->isOffsetOf(CTy, FieldNo)) {
278       OS << "offsetof(" << *CTy << ", ";
279       FieldNo->printAsOperand(OS, false);
280       OS << ")";
281       return;
282     }
283 
284     // Otherwise just print it normally.
285     U->getValue()->printAsOperand(OS, false);
286     return;
287   }
288   case scCouldNotCompute:
289     OS << "***COULDNOTCOMPUTE***";
290     return;
291   }
292   llvm_unreachable("Unknown SCEV kind!");
293 }
294 
295 Type *SCEV::getType() const {
296   switch (static_cast<SCEVTypes>(getSCEVType())) {
297   case scConstant:
298     return cast<SCEVConstant>(this)->getType();
299   case scTruncate:
300   case scZeroExtend:
301   case scSignExtend:
302     return cast<SCEVCastExpr>(this)->getType();
303   case scAddRecExpr:
304   case scMulExpr:
305   case scUMaxExpr:
306   case scSMaxExpr:
307     return cast<SCEVNAryExpr>(this)->getType();
308   case scAddExpr:
309     return cast<SCEVAddExpr>(this)->getType();
310   case scUDivExpr:
311     return cast<SCEVUDivExpr>(this)->getType();
312   case scUnknown:
313     return cast<SCEVUnknown>(this)->getType();
314   case scCouldNotCompute:
315     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
316   }
317   llvm_unreachable("Unknown SCEV kind!");
318 }
319 
320 bool SCEV::isZero() const {
321   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
322     return SC->getValue()->isZero();
323   return false;
324 }
325 
326 bool SCEV::isOne() const {
327   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
328     return SC->getValue()->isOne();
329   return false;
330 }
331 
332 bool SCEV::isAllOnesValue() const {
333   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
334     return SC->getValue()->isMinusOne();
335   return false;
336 }
337 
338 bool SCEV::isNonConstantNegative() const {
339   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
340   if (!Mul) return false;
341 
342   // If there is a constant factor, it will be first.
343   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
344   if (!SC) return false;
345 
346   // Return true if the value is negative, this matches things like (-42 * V).
347   return SC->getAPInt().isNegative();
348 }
349 
350 SCEVCouldNotCompute::SCEVCouldNotCompute() :
351   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
352 
353 bool SCEVCouldNotCompute::classof(const SCEV *S) {
354   return S->getSCEVType() == scCouldNotCompute;
355 }
356 
357 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
358   FoldingSetNodeID ID;
359   ID.AddInteger(scConstant);
360   ID.AddPointer(V);
361   void *IP = nullptr;
362   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
363   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
364   UniqueSCEVs.InsertNode(S, IP);
365   return S;
366 }
367 
368 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
369   return getConstant(ConstantInt::get(getContext(), Val));
370 }
371 
372 const SCEV *
373 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
374   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
375   return getConstant(ConstantInt::get(ITy, V, isSigned));
376 }
377 
378 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
379                            unsigned SCEVTy, const SCEV *op, Type *ty)
380   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
381 
382 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
383                                    const SCEV *op, Type *ty)
384   : SCEVCastExpr(ID, scTruncate, op, ty) {
385   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
386          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
387          "Cannot truncate non-integer value!");
388 }
389 
390 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
391                                        const SCEV *op, Type *ty)
392   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
393   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
394          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
395          "Cannot zero extend non-integer value!");
396 }
397 
398 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
399                                        const SCEV *op, Type *ty)
400   : SCEVCastExpr(ID, scSignExtend, op, ty) {
401   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
402          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
403          "Cannot sign extend non-integer value!");
404 }
405 
406 void SCEVUnknown::deleted() {
407   // Clear this SCEVUnknown from various maps.
408   SE->forgetMemoizedResults(this);
409 
410   // Remove this SCEVUnknown from the uniquing map.
411   SE->UniqueSCEVs.RemoveNode(this);
412 
413   // Release the value.
414   setValPtr(nullptr);
415 }
416 
417 void SCEVUnknown::allUsesReplacedWith(Value *New) {
418   // Remove this SCEVUnknown from the uniquing map.
419   SE->UniqueSCEVs.RemoveNode(this);
420 
421   // Update this SCEVUnknown to point to the new value. This is needed
422   // because there may still be outstanding SCEVs which still point to
423   // this SCEVUnknown.
424   setValPtr(New);
425 }
426 
427 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
428   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
429     if (VCE->getOpcode() == Instruction::PtrToInt)
430       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
431         if (CE->getOpcode() == Instruction::GetElementPtr &&
432             CE->getOperand(0)->isNullValue() &&
433             CE->getNumOperands() == 2)
434           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
435             if (CI->isOne()) {
436               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
437                                  ->getElementType();
438               return true;
439             }
440 
441   return false;
442 }
443 
444 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
445   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
446     if (VCE->getOpcode() == Instruction::PtrToInt)
447       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
448         if (CE->getOpcode() == Instruction::GetElementPtr &&
449             CE->getOperand(0)->isNullValue()) {
450           Type *Ty =
451             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
452           if (StructType *STy = dyn_cast<StructType>(Ty))
453             if (!STy->isPacked() &&
454                 CE->getNumOperands() == 3 &&
455                 CE->getOperand(1)->isNullValue()) {
456               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
457                 if (CI->isOne() &&
458                     STy->getNumElements() == 2 &&
459                     STy->getElementType(0)->isIntegerTy(1)) {
460                   AllocTy = STy->getElementType(1);
461                   return true;
462                 }
463             }
464         }
465 
466   return false;
467 }
468 
469 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
470   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
471     if (VCE->getOpcode() == Instruction::PtrToInt)
472       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
473         if (CE->getOpcode() == Instruction::GetElementPtr &&
474             CE->getNumOperands() == 3 &&
475             CE->getOperand(0)->isNullValue() &&
476             CE->getOperand(1)->isNullValue()) {
477           Type *Ty =
478             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
479           // Ignore vector types here so that ScalarEvolutionExpander doesn't
480           // emit getelementptrs that index into vectors.
481           if (Ty->isStructTy() || Ty->isArrayTy()) {
482             CTy = Ty;
483             FieldNo = CE->getOperand(2);
484             return true;
485           }
486         }
487 
488   return false;
489 }
490 
491 //===----------------------------------------------------------------------===//
492 //                               SCEV Utilities
493 //===----------------------------------------------------------------------===//
494 
495 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
496 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
497 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
498 /// have been previously deemed to be "equally complex" by this routine.  It is
499 /// intended to avoid exponential time complexity in cases like:
500 ///
501 ///   %a = f(%x, %y)
502 ///   %b = f(%a, %a)
503 ///   %c = f(%b, %b)
504 ///
505 ///   %d = f(%x, %y)
506 ///   %e = f(%d, %d)
507 ///   %f = f(%e, %e)
508 ///
509 ///   CompareValueComplexity(%f, %c)
510 ///
511 /// Since we do not continue running this routine on expression trees once we
512 /// have seen unequal values, there is no need to track them in the cache.
513 static int
514 CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache,
515                        const LoopInfo *const LI, Value *LV, Value *RV,
516                        unsigned Depth) {
517   if (Depth > MaxValueCompareDepth || EqCache.count({LV, RV}))
518     return 0;
519 
520   // Order pointer values after integer values. This helps SCEVExpander form
521   // GEPs.
522   bool LIsPointer = LV->getType()->isPointerTy(),
523        RIsPointer = RV->getType()->isPointerTy();
524   if (LIsPointer != RIsPointer)
525     return (int)LIsPointer - (int)RIsPointer;
526 
527   // Compare getValueID values.
528   unsigned LID = LV->getValueID(), RID = RV->getValueID();
529   if (LID != RID)
530     return (int)LID - (int)RID;
531 
532   // Sort arguments by their position.
533   if (const auto *LA = dyn_cast<Argument>(LV)) {
534     const auto *RA = cast<Argument>(RV);
535     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
536     return (int)LArgNo - (int)RArgNo;
537   }
538 
539   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
540     const auto *RGV = cast<GlobalValue>(RV);
541 
542     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
543       auto LT = GV->getLinkage();
544       return !(GlobalValue::isPrivateLinkage(LT) ||
545                GlobalValue::isInternalLinkage(LT));
546     };
547 
548     // Use the names to distinguish the two values, but only if the
549     // names are semantically important.
550     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
551       return LGV->getName().compare(RGV->getName());
552   }
553 
554   // For instructions, compare their loop depth, and their operand count.  This
555   // is pretty loose.
556   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
557     const auto *RInst = cast<Instruction>(RV);
558 
559     // Compare loop depths.
560     const BasicBlock *LParent = LInst->getParent(),
561                      *RParent = RInst->getParent();
562     if (LParent != RParent) {
563       unsigned LDepth = LI->getLoopDepth(LParent),
564                RDepth = LI->getLoopDepth(RParent);
565       if (LDepth != RDepth)
566         return (int)LDepth - (int)RDepth;
567     }
568 
569     // Compare the number of operands.
570     unsigned LNumOps = LInst->getNumOperands(),
571              RNumOps = RInst->getNumOperands();
572     if (LNumOps != RNumOps)
573       return (int)LNumOps - (int)RNumOps;
574 
575     for (unsigned Idx : seq(0u, LNumOps)) {
576       int Result =
577           CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx),
578                                  RInst->getOperand(Idx), Depth + 1);
579       if (Result != 0)
580         return Result;
581     }
582   }
583 
584   EqCache.insert({LV, RV});
585   return 0;
586 }
587 
588 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
589 // than RHS, respectively. A three-way result allows recursive comparisons to be
590 // more efficient.
591 static int CompareSCEVComplexity(
592     SmallSet<std::pair<const SCEV *, const SCEV *>, 8> &EqCacheSCEV,
593     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
594     DominatorTree &DT, unsigned Depth = 0) {
595   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
596   if (LHS == RHS)
597     return 0;
598 
599   // Primarily, sort the SCEVs by their getSCEVType().
600   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
601   if (LType != RType)
602     return (int)LType - (int)RType;
603 
604   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.count({LHS, RHS}))
605     return 0;
606   // Aside from the getSCEVType() ordering, the particular ordering
607   // isn't very important except that it's beneficial to be consistent,
608   // so that (a + b) and (b + a) don't end up as different expressions.
609   switch (static_cast<SCEVTypes>(LType)) {
610   case scUnknown: {
611     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
612     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
613 
614     SmallSet<std::pair<Value *, Value *>, 8> EqCache;
615     int X = CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue(),
616                                    Depth + 1);
617     if (X == 0)
618       EqCacheSCEV.insert({LHS, RHS});
619     return X;
620   }
621 
622   case scConstant: {
623     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
624     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
625 
626     // Compare constant values.
627     const APInt &LA = LC->getAPInt();
628     const APInt &RA = RC->getAPInt();
629     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
630     if (LBitWidth != RBitWidth)
631       return (int)LBitWidth - (int)RBitWidth;
632     return LA.ult(RA) ? -1 : 1;
633   }
634 
635   case scAddRecExpr: {
636     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
637     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
638 
639     // There is always a dominance between two recs that are used by one SCEV,
640     // so we can safely sort recs by loop header dominance. We require such
641     // order in getAddExpr.
642     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
643     if (LLoop != RLoop) {
644       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
645       assert(LHead != RHead && "Two loops share the same header?");
646       if (DT.dominates(LHead, RHead))
647         return 1;
648       else
649         assert(DT.dominates(RHead, LHead) &&
650                "No dominance between recurrences used by one SCEV?");
651       return -1;
652     }
653 
654     // Addrec complexity grows with operand count.
655     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
656     if (LNumOps != RNumOps)
657       return (int)LNumOps - (int)RNumOps;
658 
659     // Lexicographically compare.
660     for (unsigned i = 0; i != LNumOps; ++i) {
661       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LA->getOperand(i),
662                                     RA->getOperand(i), DT,  Depth + 1);
663       if (X != 0)
664         return X;
665     }
666     EqCacheSCEV.insert({LHS, RHS});
667     return 0;
668   }
669 
670   case scAddExpr:
671   case scMulExpr:
672   case scSMaxExpr:
673   case scUMaxExpr: {
674     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
675     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
676 
677     // Lexicographically compare n-ary expressions.
678     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
679     if (LNumOps != RNumOps)
680       return (int)LNumOps - (int)RNumOps;
681 
682     for (unsigned i = 0; i != LNumOps; ++i) {
683       if (i >= RNumOps)
684         return 1;
685       int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(i),
686                                     RC->getOperand(i), DT, Depth + 1);
687       if (X != 0)
688         return X;
689     }
690     EqCacheSCEV.insert({LHS, RHS});
691     return 0;
692   }
693 
694   case scUDivExpr: {
695     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
696     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
697 
698     // Lexicographically compare udiv expressions.
699     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getLHS(), RC->getLHS(),
700                                   DT, Depth + 1);
701     if (X != 0)
702       return X;
703     X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getRHS(), RC->getRHS(), DT,
704                               Depth + 1);
705     if (X == 0)
706       EqCacheSCEV.insert({LHS, RHS});
707     return X;
708   }
709 
710   case scTruncate:
711   case scZeroExtend:
712   case scSignExtend: {
713     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
714     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
715 
716     // Compare cast expressions by operand.
717     int X = CompareSCEVComplexity(EqCacheSCEV, LI, LC->getOperand(),
718                                   RC->getOperand(), DT, Depth + 1);
719     if (X == 0)
720       EqCacheSCEV.insert({LHS, RHS});
721     return X;
722   }
723 
724   case scCouldNotCompute:
725     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
726   }
727   llvm_unreachable("Unknown SCEV kind!");
728 }
729 
730 /// Given a list of SCEV objects, order them by their complexity, and group
731 /// objects of the same complexity together by value.  When this routine is
732 /// finished, we know that any duplicates in the vector are consecutive and that
733 /// complexity is monotonically increasing.
734 ///
735 /// Note that we go take special precautions to ensure that we get deterministic
736 /// results from this routine.  In other words, we don't want the results of
737 /// this to depend on where the addresses of various SCEV objects happened to
738 /// land in memory.
739 ///
740 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
741                               LoopInfo *LI, DominatorTree &DT) {
742   if (Ops.size() < 2) return;  // Noop
743 
744   SmallSet<std::pair<const SCEV *, const SCEV *>, 8> EqCache;
745   if (Ops.size() == 2) {
746     // This is the common case, which also happens to be trivially simple.
747     // Special case it.
748     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
749     if (CompareSCEVComplexity(EqCache, LI, RHS, LHS, DT) < 0)
750       std::swap(LHS, RHS);
751     return;
752   }
753 
754   // Do the rough sort by complexity.
755   std::stable_sort(Ops.begin(), Ops.end(),
756                    [&EqCache, LI, &DT](const SCEV *LHS, const SCEV *RHS) {
757                      return
758                          CompareSCEVComplexity(EqCache, LI, LHS, RHS, DT) < 0;
759                    });
760 
761   // Now that we are sorted by complexity, group elements of the same
762   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
763   // be extremely short in practice.  Note that we take this approach because we
764   // do not want to depend on the addresses of the objects we are grouping.
765   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
766     const SCEV *S = Ops[i];
767     unsigned Complexity = S->getSCEVType();
768 
769     // If there are any objects of the same complexity and same value as this
770     // one, group them.
771     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
772       if (Ops[j] == S) { // Found a duplicate.
773         // Move it to immediately after i'th element.
774         std::swap(Ops[i+1], Ops[j]);
775         ++i;   // no need to rescan it.
776         if (i == e-2) return;  // Done!
777       }
778     }
779   }
780 }
781 
782 // Returns the size of the SCEV S.
783 static inline int sizeOfSCEV(const SCEV *S) {
784   struct FindSCEVSize {
785     int Size;
786     FindSCEVSize() : Size(0) {}
787 
788     bool follow(const SCEV *S) {
789       ++Size;
790       // Keep looking at all operands of S.
791       return true;
792     }
793     bool isDone() const {
794       return false;
795     }
796   };
797 
798   FindSCEVSize F;
799   SCEVTraversal<FindSCEVSize> ST(F);
800   ST.visitAll(S);
801   return F.Size;
802 }
803 
804 namespace {
805 
806 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
807 public:
808   // Computes the Quotient and Remainder of the division of Numerator by
809   // Denominator.
810   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
811                      const SCEV *Denominator, const SCEV **Quotient,
812                      const SCEV **Remainder) {
813     assert(Numerator && Denominator && "Uninitialized SCEV");
814 
815     SCEVDivision D(SE, Numerator, Denominator);
816 
817     // Check for the trivial case here to avoid having to check for it in the
818     // rest of the code.
819     if (Numerator == Denominator) {
820       *Quotient = D.One;
821       *Remainder = D.Zero;
822       return;
823     }
824 
825     if (Numerator->isZero()) {
826       *Quotient = D.Zero;
827       *Remainder = D.Zero;
828       return;
829     }
830 
831     // A simple case when N/1. The quotient is N.
832     if (Denominator->isOne()) {
833       *Quotient = Numerator;
834       *Remainder = D.Zero;
835       return;
836     }
837 
838     // Split the Denominator when it is a product.
839     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
840       const SCEV *Q, *R;
841       *Quotient = Numerator;
842       for (const SCEV *Op : T->operands()) {
843         divide(SE, *Quotient, Op, &Q, &R);
844         *Quotient = Q;
845 
846         // Bail out when the Numerator is not divisible by one of the terms of
847         // the Denominator.
848         if (!R->isZero()) {
849           *Quotient = D.Zero;
850           *Remainder = Numerator;
851           return;
852         }
853       }
854       *Remainder = D.Zero;
855       return;
856     }
857 
858     D.visit(Numerator);
859     *Quotient = D.Quotient;
860     *Remainder = D.Remainder;
861   }
862 
863   // Except in the trivial case described above, we do not know how to divide
864   // Expr by Denominator for the following functions with empty implementation.
865   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
866   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
867   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
868   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
869   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
870   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
871   void visitUnknown(const SCEVUnknown *Numerator) {}
872   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
873 
874   void visitConstant(const SCEVConstant *Numerator) {
875     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
876       APInt NumeratorVal = Numerator->getAPInt();
877       APInt DenominatorVal = D->getAPInt();
878       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
879       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
880 
881       if (NumeratorBW > DenominatorBW)
882         DenominatorVal = DenominatorVal.sext(NumeratorBW);
883       else if (NumeratorBW < DenominatorBW)
884         NumeratorVal = NumeratorVal.sext(DenominatorBW);
885 
886       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
887       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
888       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
889       Quotient = SE.getConstant(QuotientVal);
890       Remainder = SE.getConstant(RemainderVal);
891       return;
892     }
893   }
894 
895   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
896     const SCEV *StartQ, *StartR, *StepQ, *StepR;
897     if (!Numerator->isAffine())
898       return cannotDivide(Numerator);
899     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
900     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
901     // Bail out if the types do not match.
902     Type *Ty = Denominator->getType();
903     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
904         Ty != StepQ->getType() || Ty != StepR->getType())
905       return cannotDivide(Numerator);
906     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
907                                 Numerator->getNoWrapFlags());
908     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
909                                  Numerator->getNoWrapFlags());
910   }
911 
912   void visitAddExpr(const SCEVAddExpr *Numerator) {
913     SmallVector<const SCEV *, 2> Qs, Rs;
914     Type *Ty = Denominator->getType();
915 
916     for (const SCEV *Op : Numerator->operands()) {
917       const SCEV *Q, *R;
918       divide(SE, Op, Denominator, &Q, &R);
919 
920       // Bail out if types do not match.
921       if (Ty != Q->getType() || Ty != R->getType())
922         return cannotDivide(Numerator);
923 
924       Qs.push_back(Q);
925       Rs.push_back(R);
926     }
927 
928     if (Qs.size() == 1) {
929       Quotient = Qs[0];
930       Remainder = Rs[0];
931       return;
932     }
933 
934     Quotient = SE.getAddExpr(Qs);
935     Remainder = SE.getAddExpr(Rs);
936   }
937 
938   void visitMulExpr(const SCEVMulExpr *Numerator) {
939     SmallVector<const SCEV *, 2> Qs;
940     Type *Ty = Denominator->getType();
941 
942     bool FoundDenominatorTerm = false;
943     for (const SCEV *Op : Numerator->operands()) {
944       // Bail out if types do not match.
945       if (Ty != Op->getType())
946         return cannotDivide(Numerator);
947 
948       if (FoundDenominatorTerm) {
949         Qs.push_back(Op);
950         continue;
951       }
952 
953       // Check whether Denominator divides one of the product operands.
954       const SCEV *Q, *R;
955       divide(SE, Op, Denominator, &Q, &R);
956       if (!R->isZero()) {
957         Qs.push_back(Op);
958         continue;
959       }
960 
961       // Bail out if types do not match.
962       if (Ty != Q->getType())
963         return cannotDivide(Numerator);
964 
965       FoundDenominatorTerm = true;
966       Qs.push_back(Q);
967     }
968 
969     if (FoundDenominatorTerm) {
970       Remainder = Zero;
971       if (Qs.size() == 1)
972         Quotient = Qs[0];
973       else
974         Quotient = SE.getMulExpr(Qs);
975       return;
976     }
977 
978     if (!isa<SCEVUnknown>(Denominator))
979       return cannotDivide(Numerator);
980 
981     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
982     ValueToValueMap RewriteMap;
983     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
984         cast<SCEVConstant>(Zero)->getValue();
985     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
986 
987     if (Remainder->isZero()) {
988       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
989       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
990           cast<SCEVConstant>(One)->getValue();
991       Quotient =
992           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
993       return;
994     }
995 
996     // Quotient is (Numerator - Remainder) divided by Denominator.
997     const SCEV *Q, *R;
998     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
999     // This SCEV does not seem to simplify: fail the division here.
1000     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1001       return cannotDivide(Numerator);
1002     divide(SE, Diff, Denominator, &Q, &R);
1003     if (R != Zero)
1004       return cannotDivide(Numerator);
1005     Quotient = Q;
1006   }
1007 
1008 private:
1009   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1010                const SCEV *Denominator)
1011       : SE(S), Denominator(Denominator) {
1012     Zero = SE.getZero(Denominator->getType());
1013     One = SE.getOne(Denominator->getType());
1014 
1015     // We generally do not know how to divide Expr by Denominator. We
1016     // initialize the division to a "cannot divide" state to simplify the rest
1017     // of the code.
1018     cannotDivide(Numerator);
1019   }
1020 
1021   // Convenience function for giving up on the division. We set the quotient to
1022   // be equal to zero and the remainder to be equal to the numerator.
1023   void cannotDivide(const SCEV *Numerator) {
1024     Quotient = Zero;
1025     Remainder = Numerator;
1026   }
1027 
1028   ScalarEvolution &SE;
1029   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1030 };
1031 
1032 }
1033 
1034 //===----------------------------------------------------------------------===//
1035 //                      Simple SCEV method implementations
1036 //===----------------------------------------------------------------------===//
1037 
1038 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1039 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1040                                        ScalarEvolution &SE,
1041                                        Type *ResultTy) {
1042   // Handle the simplest case efficiently.
1043   if (K == 1)
1044     return SE.getTruncateOrZeroExtend(It, ResultTy);
1045 
1046   // We are using the following formula for BC(It, K):
1047   //
1048   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1049   //
1050   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1051   // overflow.  Hence, we must assure that the result of our computation is
1052   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1053   // safe in modular arithmetic.
1054   //
1055   // However, this code doesn't use exactly that formula; the formula it uses
1056   // is something like the following, where T is the number of factors of 2 in
1057   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1058   // exponentiation:
1059   //
1060   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1061   //
1062   // This formula is trivially equivalent to the previous formula.  However,
1063   // this formula can be implemented much more efficiently.  The trick is that
1064   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1065   // arithmetic.  To do exact division in modular arithmetic, all we have
1066   // to do is multiply by the inverse.  Therefore, this step can be done at
1067   // width W.
1068   //
1069   // The next issue is how to safely do the division by 2^T.  The way this
1070   // is done is by doing the multiplication step at a width of at least W + T
1071   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1072   // when we perform the division by 2^T (which is equivalent to a right shift
1073   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1074   // truncated out after the division by 2^T.
1075   //
1076   // In comparison to just directly using the first formula, this technique
1077   // is much more efficient; using the first formula requires W * K bits,
1078   // but this formula less than W + K bits. Also, the first formula requires
1079   // a division step, whereas this formula only requires multiplies and shifts.
1080   //
1081   // It doesn't matter whether the subtraction step is done in the calculation
1082   // width or the input iteration count's width; if the subtraction overflows,
1083   // the result must be zero anyway.  We prefer here to do it in the width of
1084   // the induction variable because it helps a lot for certain cases; CodeGen
1085   // isn't smart enough to ignore the overflow, which leads to much less
1086   // efficient code if the width of the subtraction is wider than the native
1087   // register width.
1088   //
1089   // (It's possible to not widen at all by pulling out factors of 2 before
1090   // the multiplication; for example, K=2 can be calculated as
1091   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1092   // extra arithmetic, so it's not an obvious win, and it gets
1093   // much more complicated for K > 3.)
1094 
1095   // Protection from insane SCEVs; this bound is conservative,
1096   // but it probably doesn't matter.
1097   if (K > 1000)
1098     return SE.getCouldNotCompute();
1099 
1100   unsigned W = SE.getTypeSizeInBits(ResultTy);
1101 
1102   // Calculate K! / 2^T and T; we divide out the factors of two before
1103   // multiplying for calculating K! / 2^T to avoid overflow.
1104   // Other overflow doesn't matter because we only care about the bottom
1105   // W bits of the result.
1106   APInt OddFactorial(W, 1);
1107   unsigned T = 1;
1108   for (unsigned i = 3; i <= K; ++i) {
1109     APInt Mult(W, i);
1110     unsigned TwoFactors = Mult.countTrailingZeros();
1111     T += TwoFactors;
1112     Mult.lshrInPlace(TwoFactors);
1113     OddFactorial *= Mult;
1114   }
1115 
1116   // We need at least W + T bits for the multiplication step
1117   unsigned CalculationBits = W + T;
1118 
1119   // Calculate 2^T, at width T+W.
1120   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1121 
1122   // Calculate the multiplicative inverse of K! / 2^T;
1123   // this multiplication factor will perform the exact division by
1124   // K! / 2^T.
1125   APInt Mod = APInt::getSignedMinValue(W+1);
1126   APInt MultiplyFactor = OddFactorial.zext(W+1);
1127   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1128   MultiplyFactor = MultiplyFactor.trunc(W);
1129 
1130   // Calculate the product, at width T+W
1131   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1132                                                       CalculationBits);
1133   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1134   for (unsigned i = 1; i != K; ++i) {
1135     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1136     Dividend = SE.getMulExpr(Dividend,
1137                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1138   }
1139 
1140   // Divide by 2^T
1141   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1142 
1143   // Truncate the result, and divide by K! / 2^T.
1144 
1145   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1146                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1147 }
1148 
1149 /// Return the value of this chain of recurrences at the specified iteration
1150 /// number.  We can evaluate this recurrence by multiplying each element in the
1151 /// chain by the binomial coefficient corresponding to it.  In other words, we
1152 /// can evaluate {A,+,B,+,C,+,D} as:
1153 ///
1154 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1155 ///
1156 /// where BC(It, k) stands for binomial coefficient.
1157 ///
1158 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1159                                                 ScalarEvolution &SE) const {
1160   const SCEV *Result = getStart();
1161   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1162     // The computation is correct in the face of overflow provided that the
1163     // multiplication is performed _after_ the evaluation of the binomial
1164     // coefficient.
1165     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1166     if (isa<SCEVCouldNotCompute>(Coeff))
1167       return Coeff;
1168 
1169     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1170   }
1171   return Result;
1172 }
1173 
1174 //===----------------------------------------------------------------------===//
1175 //                    SCEV Expression folder implementations
1176 //===----------------------------------------------------------------------===//
1177 
1178 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1179                                              Type *Ty) {
1180   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1181          "This is not a truncating conversion!");
1182   assert(isSCEVable(Ty) &&
1183          "This is not a conversion to a SCEVable type!");
1184   Ty = getEffectiveSCEVType(Ty);
1185 
1186   FoldingSetNodeID ID;
1187   ID.AddInteger(scTruncate);
1188   ID.AddPointer(Op);
1189   ID.AddPointer(Ty);
1190   void *IP = nullptr;
1191   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1192 
1193   // Fold if the operand is constant.
1194   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1195     return getConstant(
1196       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1197 
1198   // trunc(trunc(x)) --> trunc(x)
1199   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1200     return getTruncateExpr(ST->getOperand(), Ty);
1201 
1202   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1203   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1204     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1205 
1206   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1207   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1208     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1209 
1210   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1211   // eliminate all the truncates, or we replace other casts with truncates.
1212   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1213     SmallVector<const SCEV *, 4> Operands;
1214     bool hasTrunc = false;
1215     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1216       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1217       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1218         hasTrunc = isa<SCEVTruncateExpr>(S);
1219       Operands.push_back(S);
1220     }
1221     if (!hasTrunc)
1222       return getAddExpr(Operands);
1223     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1224   }
1225 
1226   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1227   // eliminate all the truncates, or we replace other casts with truncates.
1228   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1229     SmallVector<const SCEV *, 4> Operands;
1230     bool hasTrunc = false;
1231     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1232       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1233       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1234         hasTrunc = isa<SCEVTruncateExpr>(S);
1235       Operands.push_back(S);
1236     }
1237     if (!hasTrunc)
1238       return getMulExpr(Operands);
1239     UniqueSCEVs.FindNodeOrInsertPos(ID, IP);  // Mutates IP, returns NULL.
1240   }
1241 
1242   // If the input value is a chrec scev, truncate the chrec's operands.
1243   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1244     SmallVector<const SCEV *, 4> Operands;
1245     for (const SCEV *Op : AddRec->operands())
1246       Operands.push_back(getTruncateExpr(Op, Ty));
1247     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1248   }
1249 
1250   // The cast wasn't folded; create an explicit cast node. We can reuse
1251   // the existing insert position since if we get here, we won't have
1252   // made any changes which would invalidate it.
1253   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1254                                                  Op, Ty);
1255   UniqueSCEVs.InsertNode(S, IP);
1256   return S;
1257 }
1258 
1259 // Get the limit of a recurrence such that incrementing by Step cannot cause
1260 // signed overflow as long as the value of the recurrence within the
1261 // loop does not exceed this limit before incrementing.
1262 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1263                                                  ICmpInst::Predicate *Pred,
1264                                                  ScalarEvolution *SE) {
1265   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1266   if (SE->isKnownPositive(Step)) {
1267     *Pred = ICmpInst::ICMP_SLT;
1268     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1269                            SE->getSignedRangeMax(Step));
1270   }
1271   if (SE->isKnownNegative(Step)) {
1272     *Pred = ICmpInst::ICMP_SGT;
1273     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1274                            SE->getSignedRangeMin(Step));
1275   }
1276   return nullptr;
1277 }
1278 
1279 // Get the limit of a recurrence such that incrementing by Step cannot cause
1280 // unsigned overflow as long as the value of the recurrence within the loop does
1281 // not exceed this limit before incrementing.
1282 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1283                                                    ICmpInst::Predicate *Pred,
1284                                                    ScalarEvolution *SE) {
1285   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1286   *Pred = ICmpInst::ICMP_ULT;
1287 
1288   return SE->getConstant(APInt::getMinValue(BitWidth) -
1289                          SE->getUnsignedRangeMax(Step));
1290 }
1291 
1292 namespace {
1293 
1294 struct ExtendOpTraitsBase {
1295   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1296                                                           unsigned);
1297 };
1298 
1299 // Used to make code generic over signed and unsigned overflow.
1300 template <typename ExtendOp> struct ExtendOpTraits {
1301   // Members present:
1302   //
1303   // static const SCEV::NoWrapFlags WrapType;
1304   //
1305   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1306   //
1307   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1308   //                                           ICmpInst::Predicate *Pred,
1309   //                                           ScalarEvolution *SE);
1310 };
1311 
1312 template <>
1313 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1314   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1315 
1316   static const GetExtendExprTy GetExtendExpr;
1317 
1318   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1319                                              ICmpInst::Predicate *Pred,
1320                                              ScalarEvolution *SE) {
1321     return getSignedOverflowLimitForStep(Step, Pred, SE);
1322   }
1323 };
1324 
1325 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1326     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1327 
1328 template <>
1329 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1330   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1331 
1332   static const GetExtendExprTy GetExtendExpr;
1333 
1334   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1335                                              ICmpInst::Predicate *Pred,
1336                                              ScalarEvolution *SE) {
1337     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1338   }
1339 };
1340 
1341 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1342     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1343 }
1344 
1345 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1346 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1347 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1348 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1349 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1350 // expression "Step + sext/zext(PreIncAR)" is congruent with
1351 // "sext/zext(PostIncAR)"
1352 template <typename ExtendOpTy>
1353 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1354                                         ScalarEvolution *SE, unsigned Depth) {
1355   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1356   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1357 
1358   const Loop *L = AR->getLoop();
1359   const SCEV *Start = AR->getStart();
1360   const SCEV *Step = AR->getStepRecurrence(*SE);
1361 
1362   // Check for a simple looking step prior to loop entry.
1363   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1364   if (!SA)
1365     return nullptr;
1366 
1367   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1368   // subtraction is expensive. For this purpose, perform a quick and dirty
1369   // difference, by checking for Step in the operand list.
1370   SmallVector<const SCEV *, 4> DiffOps;
1371   for (const SCEV *Op : SA->operands())
1372     if (Op != Step)
1373       DiffOps.push_back(Op);
1374 
1375   if (DiffOps.size() == SA->getNumOperands())
1376     return nullptr;
1377 
1378   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1379   // `Step`:
1380 
1381   // 1. NSW/NUW flags on the step increment.
1382   auto PreStartFlags =
1383     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1384   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1385   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1386       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1387 
1388   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1389   // "S+X does not sign/unsign-overflow".
1390   //
1391 
1392   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1393   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1394       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1395     return PreStart;
1396 
1397   // 2. Direct overflow check on the step operation's expression.
1398   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1399   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1400   const SCEV *OperandExtendedStart =
1401       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1402                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1403   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1404     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1405       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1406       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1407       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1408       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1409     }
1410     return PreStart;
1411   }
1412 
1413   // 3. Loop precondition.
1414   ICmpInst::Predicate Pred;
1415   const SCEV *OverflowLimit =
1416       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1417 
1418   if (OverflowLimit &&
1419       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1420     return PreStart;
1421 
1422   return nullptr;
1423 }
1424 
1425 // Get the normalized zero or sign extended expression for this AddRec's Start.
1426 template <typename ExtendOpTy>
1427 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1428                                         ScalarEvolution *SE,
1429                                         unsigned Depth) {
1430   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1431 
1432   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1433   if (!PreStart)
1434     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1435 
1436   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1437                                              Depth),
1438                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1439 }
1440 
1441 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1442 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1443 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1444 //
1445 // Formally:
1446 //
1447 //     {S,+,X} == {S-T,+,X} + T
1448 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1449 //
1450 // If ({S-T,+,X} + T) does not overflow  ... (1)
1451 //
1452 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1453 //
1454 // If {S-T,+,X} does not overflow  ... (2)
1455 //
1456 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1457 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1458 //
1459 // If (S-T)+T does not overflow  ... (3)
1460 //
1461 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1462 //      == {Ext(S),+,Ext(X)} == LHS
1463 //
1464 // Thus, if (1), (2) and (3) are true for some T, then
1465 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1466 //
1467 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1468 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1469 // to check for (1) and (2).
1470 //
1471 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1472 // is `Delta` (defined below).
1473 //
1474 template <typename ExtendOpTy>
1475 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1476                                                 const SCEV *Step,
1477                                                 const Loop *L) {
1478   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1479 
1480   // We restrict `Start` to a constant to prevent SCEV from spending too much
1481   // time here.  It is correct (but more expensive) to continue with a
1482   // non-constant `Start` and do a general SCEV subtraction to compute
1483   // `PreStart` below.
1484   //
1485   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1486   if (!StartC)
1487     return false;
1488 
1489   APInt StartAI = StartC->getAPInt();
1490 
1491   for (unsigned Delta : {-2, -1, 1, 2}) {
1492     const SCEV *PreStart = getConstant(StartAI - Delta);
1493 
1494     FoldingSetNodeID ID;
1495     ID.AddInteger(scAddRecExpr);
1496     ID.AddPointer(PreStart);
1497     ID.AddPointer(Step);
1498     ID.AddPointer(L);
1499     void *IP = nullptr;
1500     const auto *PreAR =
1501       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1502 
1503     // Give up if we don't already have the add recurrence we need because
1504     // actually constructing an add recurrence is relatively expensive.
1505     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1506       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1507       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1508       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1509           DeltaS, &Pred, this);
1510       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1511         return true;
1512     }
1513   }
1514 
1515   return false;
1516 }
1517 
1518 const SCEV *
1519 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1520   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1521          "This is not an extending conversion!");
1522   assert(isSCEVable(Ty) &&
1523          "This is not a conversion to a SCEVable type!");
1524   Ty = getEffectiveSCEVType(Ty);
1525 
1526   // Fold if the operand is constant.
1527   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1528     return getConstant(
1529       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1530 
1531   // zext(zext(x)) --> zext(x)
1532   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1533     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1534 
1535   // Before doing any expensive analysis, check to see if we've already
1536   // computed a SCEV for this Op and Ty.
1537   FoldingSetNodeID ID;
1538   ID.AddInteger(scZeroExtend);
1539   ID.AddPointer(Op);
1540   ID.AddPointer(Ty);
1541   void *IP = nullptr;
1542   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1543   if (Depth > MaxExtDepth) {
1544     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1545                                                      Op, Ty);
1546     UniqueSCEVs.InsertNode(S, IP);
1547     return S;
1548   }
1549 
1550   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1551   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1552     // It's possible the bits taken off by the truncate were all zero bits. If
1553     // so, we should be able to simplify this further.
1554     const SCEV *X = ST->getOperand();
1555     ConstantRange CR = getUnsignedRange(X);
1556     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1557     unsigned NewBits = getTypeSizeInBits(Ty);
1558     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1559             CR.zextOrTrunc(NewBits)))
1560       return getTruncateOrZeroExtend(X, Ty);
1561   }
1562 
1563   // If the input value is a chrec scev, and we can prove that the value
1564   // did not overflow the old, smaller, value, we can zero extend all of the
1565   // operands (often constants).  This allows analysis of something like
1566   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1567   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1568     if (AR->isAffine()) {
1569       const SCEV *Start = AR->getStart();
1570       const SCEV *Step = AR->getStepRecurrence(*this);
1571       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1572       const Loop *L = AR->getLoop();
1573 
1574       if (!AR->hasNoUnsignedWrap()) {
1575         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1576         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1577       }
1578 
1579       // If we have special knowledge that this addrec won't overflow,
1580       // we don't need to do any further analysis.
1581       if (AR->hasNoUnsignedWrap())
1582         return getAddRecExpr(
1583             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1584             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1585 
1586       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1587       // Note that this serves two purposes: It filters out loops that are
1588       // simply not analyzable, and it covers the case where this code is
1589       // being called from within backedge-taken count analysis, such that
1590       // attempting to ask for the backedge-taken count would likely result
1591       // in infinite recursion. In the later case, the analysis code will
1592       // cope with a conservative value, and it will take care to purge
1593       // that value once it has finished.
1594       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1595       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1596         // Manually compute the final value for AR, checking for
1597         // overflow.
1598 
1599         // Check whether the backedge-taken count can be losslessly casted to
1600         // the addrec's type. The count is always unsigned.
1601         const SCEV *CastedMaxBECount =
1602           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1603         const SCEV *RecastedMaxBECount =
1604           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1605         if (MaxBECount == RecastedMaxBECount) {
1606           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1607           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1608           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1609                                         SCEV::FlagAnyWrap, Depth + 1);
1610           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1611                                                           SCEV::FlagAnyWrap,
1612                                                           Depth + 1),
1613                                                WideTy, Depth + 1);
1614           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1615           const SCEV *WideMaxBECount =
1616             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1617           const SCEV *OperandExtendedAdd =
1618             getAddExpr(WideStart,
1619                        getMulExpr(WideMaxBECount,
1620                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1621                                   SCEV::FlagAnyWrap, Depth + 1),
1622                        SCEV::FlagAnyWrap, Depth + 1);
1623           if (ZAdd == OperandExtendedAdd) {
1624             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1625             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1626             // Return the expression with the addrec on the outside.
1627             return getAddRecExpr(
1628                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1629                                                          Depth + 1),
1630                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1631                 AR->getNoWrapFlags());
1632           }
1633           // Similar to above, only this time treat the step value as signed.
1634           // This covers loops that count down.
1635           OperandExtendedAdd =
1636             getAddExpr(WideStart,
1637                        getMulExpr(WideMaxBECount,
1638                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1639                                   SCEV::FlagAnyWrap, Depth + 1),
1640                        SCEV::FlagAnyWrap, Depth + 1);
1641           if (ZAdd == OperandExtendedAdd) {
1642             // Cache knowledge of AR NW, which is propagated to this AddRec.
1643             // Negative step causes unsigned wrap, but it still can't self-wrap.
1644             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1645             // Return the expression with the addrec on the outside.
1646             return getAddRecExpr(
1647                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1648                                                          Depth + 1),
1649                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1650                 AR->getNoWrapFlags());
1651           }
1652         }
1653       }
1654 
1655       // Normally, in the cases we can prove no-overflow via a
1656       // backedge guarding condition, we can also compute a backedge
1657       // taken count for the loop.  The exceptions are assumptions and
1658       // guards present in the loop -- SCEV is not great at exploiting
1659       // these to compute max backedge taken counts, but can still use
1660       // these to prove lack of overflow.  Use this fact to avoid
1661       // doing extra work that may not pay off.
1662       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1663           !AC.assumptions().empty()) {
1664         // If the backedge is guarded by a comparison with the pre-inc
1665         // value the addrec is safe. Also, if the entry is guarded by
1666         // a comparison with the start value and the backedge is
1667         // guarded by a comparison with the post-inc value, the addrec
1668         // is safe.
1669         if (isKnownPositive(Step)) {
1670           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1671                                       getUnsignedRangeMax(Step));
1672           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1673               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
1674                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1675                                            AR->getPostIncExpr(*this), N))) {
1676             // Cache knowledge of AR NUW, which is propagated to this
1677             // AddRec.
1678             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1679             // Return the expression with the addrec on the outside.
1680             return getAddRecExpr(
1681                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1682                                                          Depth + 1),
1683                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1684                 AR->getNoWrapFlags());
1685           }
1686         } else if (isKnownNegative(Step)) {
1687           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1688                                       getSignedRangeMin(Step));
1689           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1690               (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
1691                isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1692                                            AR->getPostIncExpr(*this), N))) {
1693             // Cache knowledge of AR NW, which is propagated to this
1694             // AddRec.  Negative step causes unsigned wrap, but it
1695             // still can't self-wrap.
1696             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1697             // Return the expression with the addrec on the outside.
1698             return getAddRecExpr(
1699                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1700                                                          Depth + 1),
1701                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1702                 AR->getNoWrapFlags());
1703           }
1704         }
1705       }
1706 
1707       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1708         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1709         return getAddRecExpr(
1710             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1711             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1712       }
1713     }
1714 
1715   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1716     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1717     if (SA->hasNoUnsignedWrap()) {
1718       // If the addition does not unsign overflow then we can, by definition,
1719       // commute the zero extension with the addition operation.
1720       SmallVector<const SCEV *, 4> Ops;
1721       for (const auto *Op : SA->operands())
1722         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1723       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1724     }
1725   }
1726 
1727   // The cast wasn't folded; create an explicit cast node.
1728   // Recompute the insert position, as it may have been invalidated.
1729   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1730   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1731                                                    Op, Ty);
1732   UniqueSCEVs.InsertNode(S, IP);
1733   return S;
1734 }
1735 
1736 const SCEV *
1737 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1738   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1739          "This is not an extending conversion!");
1740   assert(isSCEVable(Ty) &&
1741          "This is not a conversion to a SCEVable type!");
1742   Ty = getEffectiveSCEVType(Ty);
1743 
1744   // Fold if the operand is constant.
1745   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1746     return getConstant(
1747       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1748 
1749   // sext(sext(x)) --> sext(x)
1750   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1751     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1752 
1753   // sext(zext(x)) --> zext(x)
1754   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1755     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1756 
1757   // Before doing any expensive analysis, check to see if we've already
1758   // computed a SCEV for this Op and Ty.
1759   FoldingSetNodeID ID;
1760   ID.AddInteger(scSignExtend);
1761   ID.AddPointer(Op);
1762   ID.AddPointer(Ty);
1763   void *IP = nullptr;
1764   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1765   // Limit recursion depth.
1766   if (Depth > MaxExtDepth) {
1767     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1768                                                      Op, Ty);
1769     UniqueSCEVs.InsertNode(S, IP);
1770     return S;
1771   }
1772 
1773   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1774   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1775     // It's possible the bits taken off by the truncate were all sign bits. If
1776     // so, we should be able to simplify this further.
1777     const SCEV *X = ST->getOperand();
1778     ConstantRange CR = getSignedRange(X);
1779     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1780     unsigned NewBits = getTypeSizeInBits(Ty);
1781     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1782             CR.sextOrTrunc(NewBits)))
1783       return getTruncateOrSignExtend(X, Ty);
1784   }
1785 
1786   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1787   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1788     if (SA->getNumOperands() == 2) {
1789       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1790       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1791       if (SMul && SC1) {
1792         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1793           const APInt &C1 = SC1->getAPInt();
1794           const APInt &C2 = SC2->getAPInt();
1795           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1796               C2.ugt(C1) && C2.isPowerOf2())
1797             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1798                               getSignExtendExpr(SMul, Ty, Depth + 1),
1799                               SCEV::FlagAnyWrap, Depth + 1);
1800         }
1801       }
1802     }
1803 
1804     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1805     if (SA->hasNoSignedWrap()) {
1806       // If the addition does not sign overflow then we can, by definition,
1807       // commute the sign extension with the addition operation.
1808       SmallVector<const SCEV *, 4> Ops;
1809       for (const auto *Op : SA->operands())
1810         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1811       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1812     }
1813   }
1814   // If the input value is a chrec scev, and we can prove that the value
1815   // did not overflow the old, smaller, value, we can sign extend all of the
1816   // operands (often constants).  This allows analysis of something like
1817   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1818   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1819     if (AR->isAffine()) {
1820       const SCEV *Start = AR->getStart();
1821       const SCEV *Step = AR->getStepRecurrence(*this);
1822       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1823       const Loop *L = AR->getLoop();
1824 
1825       if (!AR->hasNoSignedWrap()) {
1826         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1827         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1828       }
1829 
1830       // If we have special knowledge that this addrec won't overflow,
1831       // we don't need to do any further analysis.
1832       if (AR->hasNoSignedWrap())
1833         return getAddRecExpr(
1834             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1835             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1836 
1837       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1838       // Note that this serves two purposes: It filters out loops that are
1839       // simply not analyzable, and it covers the case where this code is
1840       // being called from within backedge-taken count analysis, such that
1841       // attempting to ask for the backedge-taken count would likely result
1842       // in infinite recursion. In the later case, the analysis code will
1843       // cope with a conservative value, and it will take care to purge
1844       // that value once it has finished.
1845       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1846       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1847         // Manually compute the final value for AR, checking for
1848         // overflow.
1849 
1850         // Check whether the backedge-taken count can be losslessly casted to
1851         // the addrec's type. The count is always unsigned.
1852         const SCEV *CastedMaxBECount =
1853           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1854         const SCEV *RecastedMaxBECount =
1855           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1856         if (MaxBECount == RecastedMaxBECount) {
1857           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1858           // Check whether Start+Step*MaxBECount has no signed overflow.
1859           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1860                                         SCEV::FlagAnyWrap, Depth + 1);
1861           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1862                                                           SCEV::FlagAnyWrap,
1863                                                           Depth + 1),
1864                                                WideTy, Depth + 1);
1865           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1866           const SCEV *WideMaxBECount =
1867             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1868           const SCEV *OperandExtendedAdd =
1869             getAddExpr(WideStart,
1870                        getMulExpr(WideMaxBECount,
1871                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1872                                   SCEV::FlagAnyWrap, Depth + 1),
1873                        SCEV::FlagAnyWrap, Depth + 1);
1874           if (SAdd == OperandExtendedAdd) {
1875             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1876             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1877             // Return the expression with the addrec on the outside.
1878             return getAddRecExpr(
1879                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1880                                                          Depth + 1),
1881                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1882                 AR->getNoWrapFlags());
1883           }
1884           // Similar to above, only this time treat the step value as unsigned.
1885           // This covers loops that count up with an unsigned step.
1886           OperandExtendedAdd =
1887             getAddExpr(WideStart,
1888                        getMulExpr(WideMaxBECount,
1889                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1890                                   SCEV::FlagAnyWrap, Depth + 1),
1891                        SCEV::FlagAnyWrap, Depth + 1);
1892           if (SAdd == OperandExtendedAdd) {
1893             // If AR wraps around then
1894             //
1895             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1896             // => SAdd != OperandExtendedAdd
1897             //
1898             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1899             // (SAdd == OperandExtendedAdd => AR is NW)
1900 
1901             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1902 
1903             // Return the expression with the addrec on the outside.
1904             return getAddRecExpr(
1905                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1906                                                          Depth + 1),
1907                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1908                 AR->getNoWrapFlags());
1909           }
1910         }
1911       }
1912 
1913       // Normally, in the cases we can prove no-overflow via a
1914       // backedge guarding condition, we can also compute a backedge
1915       // taken count for the loop.  The exceptions are assumptions and
1916       // guards present in the loop -- SCEV is not great at exploiting
1917       // these to compute max backedge taken counts, but can still use
1918       // these to prove lack of overflow.  Use this fact to avoid
1919       // doing extra work that may not pay off.
1920 
1921       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1922           !AC.assumptions().empty()) {
1923         // If the backedge is guarded by a comparison with the pre-inc
1924         // value the addrec is safe. Also, if the entry is guarded by
1925         // a comparison with the start value and the backedge is
1926         // guarded by a comparison with the post-inc value, the addrec
1927         // is safe.
1928         ICmpInst::Predicate Pred;
1929         const SCEV *OverflowLimit =
1930             getSignedOverflowLimitForStep(Step, &Pred, this);
1931         if (OverflowLimit &&
1932             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1933              (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1934               isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1935                                           OverflowLimit)))) {
1936           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1937           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1938           return getAddRecExpr(
1939               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1940               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1941         }
1942       }
1943 
1944       // If Start and Step are constants, check if we can apply this
1945       // transformation:
1946       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1947       auto *SC1 = dyn_cast<SCEVConstant>(Start);
1948       auto *SC2 = dyn_cast<SCEVConstant>(Step);
1949       if (SC1 && SC2) {
1950         const APInt &C1 = SC1->getAPInt();
1951         const APInt &C2 = SC2->getAPInt();
1952         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1953             C2.isPowerOf2()) {
1954           Start = getSignExtendExpr(Start, Ty, Depth + 1);
1955           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1956                                             AR->getNoWrapFlags());
1957           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
1958                             SCEV::FlagAnyWrap, Depth + 1);
1959         }
1960       }
1961 
1962       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1963         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1964         return getAddRecExpr(
1965             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1966             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1967       }
1968     }
1969 
1970   // If the input value is provably positive and we could not simplify
1971   // away the sext build a zext instead.
1972   if (isKnownNonNegative(Op))
1973     return getZeroExtendExpr(Op, Ty, Depth + 1);
1974 
1975   // The cast wasn't folded; create an explicit cast node.
1976   // Recompute the insert position, as it may have been invalidated.
1977   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1978   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1979                                                    Op, Ty);
1980   UniqueSCEVs.InsertNode(S, IP);
1981   return S;
1982 }
1983 
1984 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
1985 /// unspecified bits out to the given type.
1986 ///
1987 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
1988                                               Type *Ty) {
1989   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1990          "This is not an extending conversion!");
1991   assert(isSCEVable(Ty) &&
1992          "This is not a conversion to a SCEVable type!");
1993   Ty = getEffectiveSCEVType(Ty);
1994 
1995   // Sign-extend negative constants.
1996   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1997     if (SC->getAPInt().isNegative())
1998       return getSignExtendExpr(Op, Ty);
1999 
2000   // Peel off a truncate cast.
2001   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2002     const SCEV *NewOp = T->getOperand();
2003     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2004       return getAnyExtendExpr(NewOp, Ty);
2005     return getTruncateOrNoop(NewOp, Ty);
2006   }
2007 
2008   // Next try a zext cast. If the cast is folded, use it.
2009   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2010   if (!isa<SCEVZeroExtendExpr>(ZExt))
2011     return ZExt;
2012 
2013   // Next try a sext cast. If the cast is folded, use it.
2014   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2015   if (!isa<SCEVSignExtendExpr>(SExt))
2016     return SExt;
2017 
2018   // Force the cast to be folded into the operands of an addrec.
2019   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2020     SmallVector<const SCEV *, 4> Ops;
2021     for (const SCEV *Op : AR->operands())
2022       Ops.push_back(getAnyExtendExpr(Op, Ty));
2023     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2024   }
2025 
2026   // If the expression is obviously signed, use the sext cast value.
2027   if (isa<SCEVSMaxExpr>(Op))
2028     return SExt;
2029 
2030   // Absent any other information, use the zext cast value.
2031   return ZExt;
2032 }
2033 
2034 /// Process the given Ops list, which is a list of operands to be added under
2035 /// the given scale, update the given map. This is a helper function for
2036 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2037 /// that would form an add expression like this:
2038 ///
2039 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2040 ///
2041 /// where A and B are constants, update the map with these values:
2042 ///
2043 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2044 ///
2045 /// and add 13 + A*B*29 to AccumulatedConstant.
2046 /// This will allow getAddRecExpr to produce this:
2047 ///
2048 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2049 ///
2050 /// This form often exposes folding opportunities that are hidden in
2051 /// the original operand list.
2052 ///
2053 /// Return true iff it appears that any interesting folding opportunities
2054 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2055 /// the common case where no interesting opportunities are present, and
2056 /// is also used as a check to avoid infinite recursion.
2057 ///
2058 static bool
2059 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2060                              SmallVectorImpl<const SCEV *> &NewOps,
2061                              APInt &AccumulatedConstant,
2062                              const SCEV *const *Ops, size_t NumOperands,
2063                              const APInt &Scale,
2064                              ScalarEvolution &SE) {
2065   bool Interesting = false;
2066 
2067   // Iterate over the add operands. They are sorted, with constants first.
2068   unsigned i = 0;
2069   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2070     ++i;
2071     // Pull a buried constant out to the outside.
2072     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2073       Interesting = true;
2074     AccumulatedConstant += Scale * C->getAPInt();
2075   }
2076 
2077   // Next comes everything else. We're especially interested in multiplies
2078   // here, but they're in the middle, so just visit the rest with one loop.
2079   for (; i != NumOperands; ++i) {
2080     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2081     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2082       APInt NewScale =
2083           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2084       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2085         // A multiplication of a constant with another add; recurse.
2086         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2087         Interesting |=
2088           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2089                                        Add->op_begin(), Add->getNumOperands(),
2090                                        NewScale, SE);
2091       } else {
2092         // A multiplication of a constant with some other value. Update
2093         // the map.
2094         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2095         const SCEV *Key = SE.getMulExpr(MulOps);
2096         auto Pair = M.insert({Key, NewScale});
2097         if (Pair.second) {
2098           NewOps.push_back(Pair.first->first);
2099         } else {
2100           Pair.first->second += NewScale;
2101           // The map already had an entry for this value, which may indicate
2102           // a folding opportunity.
2103           Interesting = true;
2104         }
2105       }
2106     } else {
2107       // An ordinary operand. Update the map.
2108       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2109           M.insert({Ops[i], Scale});
2110       if (Pair.second) {
2111         NewOps.push_back(Pair.first->first);
2112       } else {
2113         Pair.first->second += Scale;
2114         // The map already had an entry for this value, which may indicate
2115         // a folding opportunity.
2116         Interesting = true;
2117       }
2118     }
2119   }
2120 
2121   return Interesting;
2122 }
2123 
2124 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2125 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2126 // can't-overflow flags for the operation if possible.
2127 static SCEV::NoWrapFlags
2128 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2129                       const SmallVectorImpl<const SCEV *> &Ops,
2130                       SCEV::NoWrapFlags Flags) {
2131   using namespace std::placeholders;
2132   typedef OverflowingBinaryOperator OBO;
2133 
2134   bool CanAnalyze =
2135       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2136   (void)CanAnalyze;
2137   assert(CanAnalyze && "don't call from other places!");
2138 
2139   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2140   SCEV::NoWrapFlags SignOrUnsignWrap =
2141       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2142 
2143   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2144   auto IsKnownNonNegative = [&](const SCEV *S) {
2145     return SE->isKnownNonNegative(S);
2146   };
2147 
2148   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2149     Flags =
2150         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2151 
2152   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2153 
2154   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2155       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2156 
2157     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2158     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2159 
2160     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2161     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2162       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2163           Instruction::Add, C, OBO::NoSignedWrap);
2164       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2165         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2166     }
2167     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2168       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2169           Instruction::Add, C, OBO::NoUnsignedWrap);
2170       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2171         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2172     }
2173   }
2174 
2175   return Flags;
2176 }
2177 
2178 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2179   if (!isLoopInvariant(S, L))
2180     return false;
2181   // If a value depends on a SCEVUnknown which is defined after the loop, we
2182   // conservatively assume that we cannot calculate it at the loop's entry.
2183   struct FindDominatedSCEVUnknown {
2184     bool Found = false;
2185     const Loop *L;
2186     DominatorTree &DT;
2187     LoopInfo &LI;
2188 
2189     FindDominatedSCEVUnknown(const Loop *L, DominatorTree &DT, LoopInfo &LI)
2190         : L(L), DT(DT), LI(LI) {}
2191 
2192     bool checkSCEVUnknown(const SCEVUnknown *SU) {
2193       if (auto *I = dyn_cast<Instruction>(SU->getValue())) {
2194         if (DT.dominates(L->getHeader(), I->getParent()))
2195           Found = true;
2196         else
2197           assert(DT.dominates(I->getParent(), L->getHeader()) &&
2198                  "No dominance relationship between SCEV and loop?");
2199       }
2200       return false;
2201     }
2202 
2203     bool follow(const SCEV *S) {
2204       switch (static_cast<SCEVTypes>(S->getSCEVType())) {
2205       case scConstant:
2206         return false;
2207       case scAddRecExpr:
2208       case scTruncate:
2209       case scZeroExtend:
2210       case scSignExtend:
2211       case scAddExpr:
2212       case scMulExpr:
2213       case scUMaxExpr:
2214       case scSMaxExpr:
2215       case scUDivExpr:
2216         return true;
2217       case scUnknown:
2218         return checkSCEVUnknown(cast<SCEVUnknown>(S));
2219       case scCouldNotCompute:
2220         llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2221       }
2222       return false;
2223     }
2224 
2225     bool isDone() { return Found; }
2226   };
2227 
2228   FindDominatedSCEVUnknown FSU(L, DT, LI);
2229   SCEVTraversal<FindDominatedSCEVUnknown> ST(FSU);
2230   ST.visitAll(S);
2231   return !FSU.Found;
2232 }
2233 
2234 /// Get a canonical add expression, or something simpler if possible.
2235 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2236                                         SCEV::NoWrapFlags Flags,
2237                                         unsigned Depth) {
2238   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2239          "only nuw or nsw allowed");
2240   assert(!Ops.empty() && "Cannot get empty add!");
2241   if (Ops.size() == 1) return Ops[0];
2242 #ifndef NDEBUG
2243   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2244   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2245     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2246            "SCEVAddExpr operand types don't match!");
2247 #endif
2248 
2249   // Sort by complexity, this groups all similar expression types together.
2250   GroupByComplexity(Ops, &LI, DT);
2251 
2252   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2253 
2254   // If there are any constants, fold them together.
2255   unsigned Idx = 0;
2256   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2257     ++Idx;
2258     assert(Idx < Ops.size());
2259     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2260       // We found two constants, fold them together!
2261       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2262       if (Ops.size() == 2) return Ops[0];
2263       Ops.erase(Ops.begin()+1);  // Erase the folded element
2264       LHSC = cast<SCEVConstant>(Ops[0]);
2265     }
2266 
2267     // If we are left with a constant zero being added, strip it off.
2268     if (LHSC->getValue()->isZero()) {
2269       Ops.erase(Ops.begin());
2270       --Idx;
2271     }
2272 
2273     if (Ops.size() == 1) return Ops[0];
2274   }
2275 
2276   // Limit recursion calls depth.
2277   if (Depth > MaxArithDepth)
2278     return getOrCreateAddExpr(Ops, Flags);
2279 
2280   // Okay, check to see if the same value occurs in the operand list more than
2281   // once.  If so, merge them together into an multiply expression.  Since we
2282   // sorted the list, these values are required to be adjacent.
2283   Type *Ty = Ops[0]->getType();
2284   bool FoundMatch = false;
2285   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2286     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2287       // Scan ahead to count how many equal operands there are.
2288       unsigned Count = 2;
2289       while (i+Count != e && Ops[i+Count] == Ops[i])
2290         ++Count;
2291       // Merge the values into a multiply.
2292       const SCEV *Scale = getConstant(Ty, Count);
2293       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2294       if (Ops.size() == Count)
2295         return Mul;
2296       Ops[i] = Mul;
2297       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2298       --i; e -= Count - 1;
2299       FoundMatch = true;
2300     }
2301   if (FoundMatch)
2302     return getAddExpr(Ops, Flags);
2303 
2304   // Check for truncates. If all the operands are truncated from the same
2305   // type, see if factoring out the truncate would permit the result to be
2306   // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2307   // if the contents of the resulting outer trunc fold to something simple.
2308   for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2309     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
2310     Type *DstType = Trunc->getType();
2311     Type *SrcType = Trunc->getOperand()->getType();
2312     SmallVector<const SCEV *, 8> LargeOps;
2313     bool Ok = true;
2314     // Check all the operands to see if they can be represented in the
2315     // source type of the truncate.
2316     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2317       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2318         if (T->getOperand()->getType() != SrcType) {
2319           Ok = false;
2320           break;
2321         }
2322         LargeOps.push_back(T->getOperand());
2323       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2324         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2325       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2326         SmallVector<const SCEV *, 8> LargeMulOps;
2327         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2328           if (const SCEVTruncateExpr *T =
2329                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2330             if (T->getOperand()->getType() != SrcType) {
2331               Ok = false;
2332               break;
2333             }
2334             LargeMulOps.push_back(T->getOperand());
2335           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2336             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2337           } else {
2338             Ok = false;
2339             break;
2340           }
2341         }
2342         if (Ok)
2343           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2344       } else {
2345         Ok = false;
2346         break;
2347       }
2348     }
2349     if (Ok) {
2350       // Evaluate the expression in the larger type.
2351       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2352       // If it folds to something simple, use it. Otherwise, don't.
2353       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2354         return getTruncateExpr(Fold, DstType);
2355     }
2356   }
2357 
2358   // Skip past any other cast SCEVs.
2359   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2360     ++Idx;
2361 
2362   // If there are add operands they would be next.
2363   if (Idx < Ops.size()) {
2364     bool DeletedAdd = false;
2365     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2366       if (Ops.size() > AddOpsInlineThreshold ||
2367           Add->getNumOperands() > AddOpsInlineThreshold)
2368         break;
2369       // If we have an add, expand the add operands onto the end of the operands
2370       // list.
2371       Ops.erase(Ops.begin()+Idx);
2372       Ops.append(Add->op_begin(), Add->op_end());
2373       DeletedAdd = true;
2374     }
2375 
2376     // If we deleted at least one add, we added operands to the end of the list,
2377     // and they are not necessarily sorted.  Recurse to resort and resimplify
2378     // any operands we just acquired.
2379     if (DeletedAdd)
2380       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2381   }
2382 
2383   // Skip over the add expression until we get to a multiply.
2384   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2385     ++Idx;
2386 
2387   // Check to see if there are any folding opportunities present with
2388   // operands multiplied by constant values.
2389   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2390     uint64_t BitWidth = getTypeSizeInBits(Ty);
2391     DenseMap<const SCEV *, APInt> M;
2392     SmallVector<const SCEV *, 8> NewOps;
2393     APInt AccumulatedConstant(BitWidth, 0);
2394     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2395                                      Ops.data(), Ops.size(),
2396                                      APInt(BitWidth, 1), *this)) {
2397       struct APIntCompare {
2398         bool operator()(const APInt &LHS, const APInt &RHS) const {
2399           return LHS.ult(RHS);
2400         }
2401       };
2402 
2403       // Some interesting folding opportunity is present, so its worthwhile to
2404       // re-generate the operands list. Group the operands by constant scale,
2405       // to avoid multiplying by the same constant scale multiple times.
2406       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2407       for (const SCEV *NewOp : NewOps)
2408         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2409       // Re-generate the operands list.
2410       Ops.clear();
2411       if (AccumulatedConstant != 0)
2412         Ops.push_back(getConstant(AccumulatedConstant));
2413       for (auto &MulOp : MulOpLists)
2414         if (MulOp.first != 0)
2415           Ops.push_back(getMulExpr(
2416               getConstant(MulOp.first),
2417               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2418               SCEV::FlagAnyWrap, Depth + 1));
2419       if (Ops.empty())
2420         return getZero(Ty);
2421       if (Ops.size() == 1)
2422         return Ops[0];
2423       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2424     }
2425   }
2426 
2427   // If we are adding something to a multiply expression, make sure the
2428   // something is not already an operand of the multiply.  If so, merge it into
2429   // the multiply.
2430   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2431     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2432     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2433       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2434       if (isa<SCEVConstant>(MulOpSCEV))
2435         continue;
2436       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2437         if (MulOpSCEV == Ops[AddOp]) {
2438           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2439           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2440           if (Mul->getNumOperands() != 2) {
2441             // If the multiply has more than two operands, we must get the
2442             // Y*Z term.
2443             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2444                                                 Mul->op_begin()+MulOp);
2445             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2446             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2447           }
2448           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2449           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2450           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2451                                             SCEV::FlagAnyWrap, Depth + 1);
2452           if (Ops.size() == 2) return OuterMul;
2453           if (AddOp < Idx) {
2454             Ops.erase(Ops.begin()+AddOp);
2455             Ops.erase(Ops.begin()+Idx-1);
2456           } else {
2457             Ops.erase(Ops.begin()+Idx);
2458             Ops.erase(Ops.begin()+AddOp-1);
2459           }
2460           Ops.push_back(OuterMul);
2461           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2462         }
2463 
2464       // Check this multiply against other multiplies being added together.
2465       for (unsigned OtherMulIdx = Idx+1;
2466            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2467            ++OtherMulIdx) {
2468         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2469         // If MulOp occurs in OtherMul, we can fold the two multiplies
2470         // together.
2471         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2472              OMulOp != e; ++OMulOp)
2473           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2474             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2475             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2476             if (Mul->getNumOperands() != 2) {
2477               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2478                                                   Mul->op_begin()+MulOp);
2479               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2480               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2481             }
2482             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2483             if (OtherMul->getNumOperands() != 2) {
2484               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2485                                                   OtherMul->op_begin()+OMulOp);
2486               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2487               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2488             }
2489             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2490             const SCEV *InnerMulSum =
2491                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2492             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2493                                               SCEV::FlagAnyWrap, Depth + 1);
2494             if (Ops.size() == 2) return OuterMul;
2495             Ops.erase(Ops.begin()+Idx);
2496             Ops.erase(Ops.begin()+OtherMulIdx-1);
2497             Ops.push_back(OuterMul);
2498             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2499           }
2500       }
2501     }
2502   }
2503 
2504   // If there are any add recurrences in the operands list, see if any other
2505   // added values are loop invariant.  If so, we can fold them into the
2506   // recurrence.
2507   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2508     ++Idx;
2509 
2510   // Scan over all recurrences, trying to fold loop invariants into them.
2511   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2512     // Scan all of the other operands to this add and add them to the vector if
2513     // they are loop invariant w.r.t. the recurrence.
2514     SmallVector<const SCEV *, 8> LIOps;
2515     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2516     const Loop *AddRecLoop = AddRec->getLoop();
2517     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2518       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2519         LIOps.push_back(Ops[i]);
2520         Ops.erase(Ops.begin()+i);
2521         --i; --e;
2522       }
2523 
2524     // If we found some loop invariants, fold them into the recurrence.
2525     if (!LIOps.empty()) {
2526       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2527       LIOps.push_back(AddRec->getStart());
2528 
2529       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2530                                              AddRec->op_end());
2531       // This follows from the fact that the no-wrap flags on the outer add
2532       // expression are applicable on the 0th iteration, when the add recurrence
2533       // will be equal to its start value.
2534       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2535 
2536       // Build the new addrec. Propagate the NUW and NSW flags if both the
2537       // outer add and the inner addrec are guaranteed to have no overflow.
2538       // Always propagate NW.
2539       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2540       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2541 
2542       // If all of the other operands were loop invariant, we are done.
2543       if (Ops.size() == 1) return NewRec;
2544 
2545       // Otherwise, add the folded AddRec by the non-invariant parts.
2546       for (unsigned i = 0;; ++i)
2547         if (Ops[i] == AddRec) {
2548           Ops[i] = NewRec;
2549           break;
2550         }
2551       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2552     }
2553 
2554     // Okay, if there weren't any loop invariants to be folded, check to see if
2555     // there are multiple AddRec's with the same loop induction variable being
2556     // added together.  If so, we can fold them.
2557     for (unsigned OtherIdx = Idx+1;
2558          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2559          ++OtherIdx) {
2560       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2561       // so that the 1st found AddRecExpr is dominated by all others.
2562       assert(DT.dominates(
2563            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2564            AddRec->getLoop()->getHeader()) &&
2565         "AddRecExprs are not sorted in reverse dominance order?");
2566       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2567         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2568         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2569                                                AddRec->op_end());
2570         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2571              ++OtherIdx) {
2572           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2573           if (OtherAddRec->getLoop() == AddRecLoop) {
2574             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2575                  i != e; ++i) {
2576               if (i >= AddRecOps.size()) {
2577                 AddRecOps.append(OtherAddRec->op_begin()+i,
2578                                  OtherAddRec->op_end());
2579                 break;
2580               }
2581               SmallVector<const SCEV *, 2> TwoOps = {
2582                   AddRecOps[i], OtherAddRec->getOperand(i)};
2583               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2584             }
2585             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2586           }
2587         }
2588         // Step size has changed, so we cannot guarantee no self-wraparound.
2589         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2590         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2591       }
2592     }
2593 
2594     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2595     // next one.
2596   }
2597 
2598   // Okay, it looks like we really DO need an add expr.  Check to see if we
2599   // already have one, otherwise create a new one.
2600   return getOrCreateAddExpr(Ops, Flags);
2601 }
2602 
2603 const SCEV *
2604 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2605                                     SCEV::NoWrapFlags Flags) {
2606   FoldingSetNodeID ID;
2607   ID.AddInteger(scAddExpr);
2608   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2609     ID.AddPointer(Ops[i]);
2610   void *IP = nullptr;
2611   SCEVAddExpr *S =
2612       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2613   if (!S) {
2614     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2615     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2616     S = new (SCEVAllocator)
2617         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2618     UniqueSCEVs.InsertNode(S, IP);
2619   }
2620   S->setNoWrapFlags(Flags);
2621   return S;
2622 }
2623 
2624 const SCEV *
2625 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2626                                     SCEV::NoWrapFlags Flags) {
2627   FoldingSetNodeID ID;
2628   ID.AddInteger(scMulExpr);
2629   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2630     ID.AddPointer(Ops[i]);
2631   void *IP = nullptr;
2632   SCEVMulExpr *S =
2633     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2634   if (!S) {
2635     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2636     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2637     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2638                                         O, Ops.size());
2639     UniqueSCEVs.InsertNode(S, IP);
2640   }
2641   S->setNoWrapFlags(Flags);
2642   return S;
2643 }
2644 
2645 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2646   uint64_t k = i*j;
2647   if (j > 1 && k / j != i) Overflow = true;
2648   return k;
2649 }
2650 
2651 /// Compute the result of "n choose k", the binomial coefficient.  If an
2652 /// intermediate computation overflows, Overflow will be set and the return will
2653 /// be garbage. Overflow is not cleared on absence of overflow.
2654 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2655   // We use the multiplicative formula:
2656   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2657   // At each iteration, we take the n-th term of the numeral and divide by the
2658   // (k-n)th term of the denominator.  This division will always produce an
2659   // integral result, and helps reduce the chance of overflow in the
2660   // intermediate computations. However, we can still overflow even when the
2661   // final result would fit.
2662 
2663   if (n == 0 || n == k) return 1;
2664   if (k > n) return 0;
2665 
2666   if (k > n/2)
2667     k = n-k;
2668 
2669   uint64_t r = 1;
2670   for (uint64_t i = 1; i <= k; ++i) {
2671     r = umul_ov(r, n-(i-1), Overflow);
2672     r /= i;
2673   }
2674   return r;
2675 }
2676 
2677 /// Determine if any of the operands in this SCEV are a constant or if
2678 /// any of the add or multiply expressions in this SCEV contain a constant.
2679 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2680   struct FindConstantInAddMulChain {
2681     bool FoundConstant = false;
2682 
2683     bool follow(const SCEV *S) {
2684       FoundConstant |= isa<SCEVConstant>(S);
2685       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2686     }
2687     bool isDone() const {
2688       return FoundConstant;
2689     }
2690   };
2691 
2692   FindConstantInAddMulChain F;
2693   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2694   ST.visitAll(StartExpr);
2695   return F.FoundConstant;
2696 }
2697 
2698 /// Get a canonical multiply expression, or something simpler if possible.
2699 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2700                                         SCEV::NoWrapFlags Flags,
2701                                         unsigned Depth) {
2702   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2703          "only nuw or nsw allowed");
2704   assert(!Ops.empty() && "Cannot get empty mul!");
2705   if (Ops.size() == 1) return Ops[0];
2706 #ifndef NDEBUG
2707   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2708   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2709     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2710            "SCEVMulExpr operand types don't match!");
2711 #endif
2712 
2713   // Sort by complexity, this groups all similar expression types together.
2714   GroupByComplexity(Ops, &LI, DT);
2715 
2716   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2717 
2718   // Limit recursion calls depth.
2719   if (Depth > MaxArithDepth)
2720     return getOrCreateMulExpr(Ops, Flags);
2721 
2722   // If there are any constants, fold them together.
2723   unsigned Idx = 0;
2724   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2725 
2726     // C1*(C2+V) -> C1*C2 + C1*V
2727     if (Ops.size() == 2)
2728         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2729           // If any of Add's ops are Adds or Muls with a constant,
2730           // apply this transformation as well.
2731           if (Add->getNumOperands() == 2)
2732             // TODO: There are some cases where this transformation is not
2733             // profitable, for example:
2734             // Add = (C0 + X) * Y + Z.
2735             // Maybe the scope of this transformation should be narrowed down.
2736             if (containsConstantInAddMulChain(Add))
2737               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2738                                            SCEV::FlagAnyWrap, Depth + 1),
2739                                 getMulExpr(LHSC, Add->getOperand(1),
2740                                            SCEV::FlagAnyWrap, Depth + 1),
2741                                 SCEV::FlagAnyWrap, Depth + 1);
2742 
2743     ++Idx;
2744     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2745       // We found two constants, fold them together!
2746       ConstantInt *Fold =
2747           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2748       Ops[0] = getConstant(Fold);
2749       Ops.erase(Ops.begin()+1);  // Erase the folded element
2750       if (Ops.size() == 1) return Ops[0];
2751       LHSC = cast<SCEVConstant>(Ops[0]);
2752     }
2753 
2754     // If we are left with a constant one being multiplied, strip it off.
2755     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2756       Ops.erase(Ops.begin());
2757       --Idx;
2758     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2759       // If we have a multiply of zero, it will always be zero.
2760       return Ops[0];
2761     } else if (Ops[0]->isAllOnesValue()) {
2762       // If we have a mul by -1 of an add, try distributing the -1 among the
2763       // add operands.
2764       if (Ops.size() == 2) {
2765         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2766           SmallVector<const SCEV *, 4> NewOps;
2767           bool AnyFolded = false;
2768           for (const SCEV *AddOp : Add->operands()) {
2769             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2770                                          Depth + 1);
2771             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2772             NewOps.push_back(Mul);
2773           }
2774           if (AnyFolded)
2775             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2776         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2777           // Negation preserves a recurrence's no self-wrap property.
2778           SmallVector<const SCEV *, 4> Operands;
2779           for (const SCEV *AddRecOp : AddRec->operands())
2780             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2781                                           Depth + 1));
2782 
2783           return getAddRecExpr(Operands, AddRec->getLoop(),
2784                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2785         }
2786       }
2787     }
2788 
2789     if (Ops.size() == 1)
2790       return Ops[0];
2791   }
2792 
2793   // Skip over the add expression until we get to a multiply.
2794   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2795     ++Idx;
2796 
2797   // If there are mul operands inline them all into this expression.
2798   if (Idx < Ops.size()) {
2799     bool DeletedMul = false;
2800     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2801       if (Ops.size() > MulOpsInlineThreshold)
2802         break;
2803       // If we have an mul, expand the mul operands onto the end of the
2804       // operands list.
2805       Ops.erase(Ops.begin()+Idx);
2806       Ops.append(Mul->op_begin(), Mul->op_end());
2807       DeletedMul = true;
2808     }
2809 
2810     // If we deleted at least one mul, we added operands to the end of the
2811     // list, and they are not necessarily sorted.  Recurse to resort and
2812     // resimplify any operands we just acquired.
2813     if (DeletedMul)
2814       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2815   }
2816 
2817   // If there are any add recurrences in the operands list, see if any other
2818   // added values are loop invariant.  If so, we can fold them into the
2819   // recurrence.
2820   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2821     ++Idx;
2822 
2823   // Scan over all recurrences, trying to fold loop invariants into them.
2824   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2825     // Scan all of the other operands to this mul and add them to the vector
2826     // if they are loop invariant w.r.t. the recurrence.
2827     SmallVector<const SCEV *, 8> LIOps;
2828     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2829     const Loop *AddRecLoop = AddRec->getLoop();
2830     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2831       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2832         LIOps.push_back(Ops[i]);
2833         Ops.erase(Ops.begin()+i);
2834         --i; --e;
2835       }
2836 
2837     // If we found some loop invariants, fold them into the recurrence.
2838     if (!LIOps.empty()) {
2839       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2840       SmallVector<const SCEV *, 4> NewOps;
2841       NewOps.reserve(AddRec->getNumOperands());
2842       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2843       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2844         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2845                                     SCEV::FlagAnyWrap, Depth + 1));
2846 
2847       // Build the new addrec. Propagate the NUW and NSW flags if both the
2848       // outer mul and the inner addrec are guaranteed to have no overflow.
2849       //
2850       // No self-wrap cannot be guaranteed after changing the step size, but
2851       // will be inferred if either NUW or NSW is true.
2852       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2853       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2854 
2855       // If all of the other operands were loop invariant, we are done.
2856       if (Ops.size() == 1) return NewRec;
2857 
2858       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2859       for (unsigned i = 0;; ++i)
2860         if (Ops[i] == AddRec) {
2861           Ops[i] = NewRec;
2862           break;
2863         }
2864       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2865     }
2866 
2867     // Okay, if there weren't any loop invariants to be folded, check to see
2868     // if there are multiple AddRec's with the same loop induction variable
2869     // being multiplied together.  If so, we can fold them.
2870 
2871     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2872     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2873     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2874     //   ]]],+,...up to x=2n}.
2875     // Note that the arguments to choose() are always integers with values
2876     // known at compile time, never SCEV objects.
2877     //
2878     // The implementation avoids pointless extra computations when the two
2879     // addrec's are of different length (mathematically, it's equivalent to
2880     // an infinite stream of zeros on the right).
2881     bool OpsModified = false;
2882     for (unsigned OtherIdx = Idx+1;
2883          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2884          ++OtherIdx) {
2885       const SCEVAddRecExpr *OtherAddRec =
2886         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2887       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2888         continue;
2889 
2890       // Limit max number of arguments to avoid creation of unreasonably big
2891       // SCEVAddRecs with very complex operands.
2892       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2893           MaxAddRecSize)
2894         continue;
2895 
2896       bool Overflow = false;
2897       Type *Ty = AddRec->getType();
2898       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2899       SmallVector<const SCEV*, 7> AddRecOps;
2900       for (int x = 0, xe = AddRec->getNumOperands() +
2901              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2902         const SCEV *Term = getZero(Ty);
2903         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2904           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2905           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2906                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2907                z < ze && !Overflow; ++z) {
2908             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2909             uint64_t Coeff;
2910             if (LargerThan64Bits)
2911               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2912             else
2913               Coeff = Coeff1*Coeff2;
2914             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2915             const SCEV *Term1 = AddRec->getOperand(y-z);
2916             const SCEV *Term2 = OtherAddRec->getOperand(z);
2917             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2918                                                SCEV::FlagAnyWrap, Depth + 1),
2919                               SCEV::FlagAnyWrap, Depth + 1);
2920           }
2921         }
2922         AddRecOps.push_back(Term);
2923       }
2924       if (!Overflow) {
2925         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2926                                               SCEV::FlagAnyWrap);
2927         if (Ops.size() == 2) return NewAddRec;
2928         Ops[Idx] = NewAddRec;
2929         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2930         OpsModified = true;
2931         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2932         if (!AddRec)
2933           break;
2934       }
2935     }
2936     if (OpsModified)
2937       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2938 
2939     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2940     // next one.
2941   }
2942 
2943   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2944   // already have one, otherwise create a new one.
2945   return getOrCreateMulExpr(Ops, Flags);
2946 }
2947 
2948 /// Get a canonical unsigned division expression, or something simpler if
2949 /// possible.
2950 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2951                                          const SCEV *RHS) {
2952   assert(getEffectiveSCEVType(LHS->getType()) ==
2953          getEffectiveSCEVType(RHS->getType()) &&
2954          "SCEVUDivExpr operand types don't match!");
2955 
2956   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2957     if (RHSC->getValue()->isOne())
2958       return LHS;                               // X udiv 1 --> x
2959     // If the denominator is zero, the result of the udiv is undefined. Don't
2960     // try to analyze it, because the resolution chosen here may differ from
2961     // the resolution chosen in other parts of the compiler.
2962     if (!RHSC->getValue()->isZero()) {
2963       // Determine if the division can be folded into the operands of
2964       // its operands.
2965       // TODO: Generalize this to non-constants by using known-bits information.
2966       Type *Ty = LHS->getType();
2967       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
2968       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
2969       // For non-power-of-two values, effectively round the value up to the
2970       // nearest power of two.
2971       if (!RHSC->getAPInt().isPowerOf2())
2972         ++MaxShiftAmt;
2973       IntegerType *ExtTy =
2974         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
2975       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2976         if (const SCEVConstant *Step =
2977             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2978           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2979           const APInt &StepInt = Step->getAPInt();
2980           const APInt &DivInt = RHSC->getAPInt();
2981           if (!StepInt.urem(DivInt) &&
2982               getZeroExtendExpr(AR, ExtTy) ==
2983               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2984                             getZeroExtendExpr(Step, ExtTy),
2985                             AR->getLoop(), SCEV::FlagAnyWrap)) {
2986             SmallVector<const SCEV *, 4> Operands;
2987             for (const SCEV *Op : AR->operands())
2988               Operands.push_back(getUDivExpr(Op, RHS));
2989             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
2990           }
2991           /// Get a canonical UDivExpr for a recurrence.
2992           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2993           // We can currently only fold X%N if X is constant.
2994           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2995           if (StartC && !DivInt.urem(StepInt) &&
2996               getZeroExtendExpr(AR, ExtTy) ==
2997               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2998                             getZeroExtendExpr(Step, ExtTy),
2999                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3000             const APInt &StartInt = StartC->getAPInt();
3001             const APInt &StartRem = StartInt.urem(StepInt);
3002             if (StartRem != 0)
3003               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3004                                   AR->getLoop(), SCEV::FlagNW);
3005           }
3006         }
3007       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3008       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3009         SmallVector<const SCEV *, 4> Operands;
3010         for (const SCEV *Op : M->operands())
3011           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3012         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3013           // Find an operand that's safely divisible.
3014           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3015             const SCEV *Op = M->getOperand(i);
3016             const SCEV *Div = getUDivExpr(Op, RHSC);
3017             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3018               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3019                                                       M->op_end());
3020               Operands[i] = Div;
3021               return getMulExpr(Operands);
3022             }
3023           }
3024       }
3025       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3026       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3027         SmallVector<const SCEV *, 4> Operands;
3028         for (const SCEV *Op : A->operands())
3029           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3030         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3031           Operands.clear();
3032           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3033             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3034             if (isa<SCEVUDivExpr>(Op) ||
3035                 getMulExpr(Op, RHS) != A->getOperand(i))
3036               break;
3037             Operands.push_back(Op);
3038           }
3039           if (Operands.size() == A->getNumOperands())
3040             return getAddExpr(Operands);
3041         }
3042       }
3043 
3044       // Fold if both operands are constant.
3045       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3046         Constant *LHSCV = LHSC->getValue();
3047         Constant *RHSCV = RHSC->getValue();
3048         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3049                                                                    RHSCV)));
3050       }
3051     }
3052   }
3053 
3054   FoldingSetNodeID ID;
3055   ID.AddInteger(scUDivExpr);
3056   ID.AddPointer(LHS);
3057   ID.AddPointer(RHS);
3058   void *IP = nullptr;
3059   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3060   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3061                                              LHS, RHS);
3062   UniqueSCEVs.InsertNode(S, IP);
3063   return S;
3064 }
3065 
3066 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3067   APInt A = C1->getAPInt().abs();
3068   APInt B = C2->getAPInt().abs();
3069   uint32_t ABW = A.getBitWidth();
3070   uint32_t BBW = B.getBitWidth();
3071 
3072   if (ABW > BBW)
3073     B = B.zext(ABW);
3074   else if (ABW < BBW)
3075     A = A.zext(BBW);
3076 
3077   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3078 }
3079 
3080 /// Get a canonical unsigned division expression, or something simpler if
3081 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3082 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3083 /// it's not exact because the udiv may be clearing bits.
3084 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3085                                               const SCEV *RHS) {
3086   // TODO: we could try to find factors in all sorts of things, but for now we
3087   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3088   // end of this file for inspiration.
3089 
3090   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3091   if (!Mul || !Mul->hasNoUnsignedWrap())
3092     return getUDivExpr(LHS, RHS);
3093 
3094   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3095     // If the mulexpr multiplies by a constant, then that constant must be the
3096     // first element of the mulexpr.
3097     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3098       if (LHSCst == RHSCst) {
3099         SmallVector<const SCEV *, 2> Operands;
3100         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3101         return getMulExpr(Operands);
3102       }
3103 
3104       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3105       // that there's a factor provided by one of the other terms. We need to
3106       // check.
3107       APInt Factor = gcd(LHSCst, RHSCst);
3108       if (!Factor.isIntN(1)) {
3109         LHSCst =
3110             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3111         RHSCst =
3112             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3113         SmallVector<const SCEV *, 2> Operands;
3114         Operands.push_back(LHSCst);
3115         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3116         LHS = getMulExpr(Operands);
3117         RHS = RHSCst;
3118         Mul = dyn_cast<SCEVMulExpr>(LHS);
3119         if (!Mul)
3120           return getUDivExactExpr(LHS, RHS);
3121       }
3122     }
3123   }
3124 
3125   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3126     if (Mul->getOperand(i) == RHS) {
3127       SmallVector<const SCEV *, 2> Operands;
3128       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3129       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3130       return getMulExpr(Operands);
3131     }
3132   }
3133 
3134   return getUDivExpr(LHS, RHS);
3135 }
3136 
3137 /// Get an add recurrence expression for the specified loop.  Simplify the
3138 /// expression as much as possible.
3139 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3140                                            const Loop *L,
3141                                            SCEV::NoWrapFlags Flags) {
3142   SmallVector<const SCEV *, 4> Operands;
3143   Operands.push_back(Start);
3144   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3145     if (StepChrec->getLoop() == L) {
3146       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3147       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3148     }
3149 
3150   Operands.push_back(Step);
3151   return getAddRecExpr(Operands, L, Flags);
3152 }
3153 
3154 /// Get an add recurrence expression for the specified loop.  Simplify the
3155 /// expression as much as possible.
3156 const SCEV *
3157 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3158                                const Loop *L, SCEV::NoWrapFlags Flags) {
3159   if (Operands.size() == 1) return Operands[0];
3160 #ifndef NDEBUG
3161   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3162   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3163     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3164            "SCEVAddRecExpr operand types don't match!");
3165   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3166     assert(isLoopInvariant(Operands[i], L) &&
3167            "SCEVAddRecExpr operand is not loop-invariant!");
3168 #endif
3169 
3170   if (Operands.back()->isZero()) {
3171     Operands.pop_back();
3172     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3173   }
3174 
3175   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3176   // use that information to infer NUW and NSW flags. However, computing a
3177   // BE count requires calling getAddRecExpr, so we may not yet have a
3178   // meaningful BE count at this point (and if we don't, we'd be stuck
3179   // with a SCEVCouldNotCompute as the cached BE count).
3180 
3181   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3182 
3183   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3184   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3185     const Loop *NestedLoop = NestedAR->getLoop();
3186     if (L->contains(NestedLoop)
3187             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3188             : (!NestedLoop->contains(L) &&
3189                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3190       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3191                                                   NestedAR->op_end());
3192       Operands[0] = NestedAR->getStart();
3193       // AddRecs require their operands be loop-invariant with respect to their
3194       // loops. Don't perform this transformation if it would break this
3195       // requirement.
3196       bool AllInvariant = all_of(
3197           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3198 
3199       if (AllInvariant) {
3200         // Create a recurrence for the outer loop with the same step size.
3201         //
3202         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3203         // inner recurrence has the same property.
3204         SCEV::NoWrapFlags OuterFlags =
3205           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3206 
3207         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3208         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3209           return isLoopInvariant(Op, NestedLoop);
3210         });
3211 
3212         if (AllInvariant) {
3213           // Ok, both add recurrences are valid after the transformation.
3214           //
3215           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3216           // the outer recurrence has the same property.
3217           SCEV::NoWrapFlags InnerFlags =
3218             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3219           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3220         }
3221       }
3222       // Reset Operands to its original state.
3223       Operands[0] = NestedAR;
3224     }
3225   }
3226 
3227   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3228   // already have one, otherwise create a new one.
3229   FoldingSetNodeID ID;
3230   ID.AddInteger(scAddRecExpr);
3231   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3232     ID.AddPointer(Operands[i]);
3233   ID.AddPointer(L);
3234   void *IP = nullptr;
3235   SCEVAddRecExpr *S =
3236     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3237   if (!S) {
3238     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3239     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3240     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3241                                            O, Operands.size(), L);
3242     UniqueSCEVs.InsertNode(S, IP);
3243   }
3244   S->setNoWrapFlags(Flags);
3245   return S;
3246 }
3247 
3248 const SCEV *
3249 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3250                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3251   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3252   // getSCEV(Base)->getType() has the same address space as Base->getType()
3253   // because SCEV::getType() preserves the address space.
3254   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3255   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3256   // instruction to its SCEV, because the Instruction may be guarded by control
3257   // flow and the no-overflow bits may not be valid for the expression in any
3258   // context. This can be fixed similarly to how these flags are handled for
3259   // adds.
3260   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3261                                              : SCEV::FlagAnyWrap;
3262 
3263   const SCEV *TotalOffset = getZero(IntPtrTy);
3264   // The array size is unimportant. The first thing we do on CurTy is getting
3265   // its element type.
3266   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3267   for (const SCEV *IndexExpr : IndexExprs) {
3268     // Compute the (potentially symbolic) offset in bytes for this index.
3269     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3270       // For a struct, add the member offset.
3271       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3272       unsigned FieldNo = Index->getZExtValue();
3273       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3274 
3275       // Add the field offset to the running total offset.
3276       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3277 
3278       // Update CurTy to the type of the field at Index.
3279       CurTy = STy->getTypeAtIndex(Index);
3280     } else {
3281       // Update CurTy to its element type.
3282       CurTy = cast<SequentialType>(CurTy)->getElementType();
3283       // For an array, add the element offset, explicitly scaled.
3284       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3285       // Getelementptr indices are signed.
3286       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3287 
3288       // Multiply the index by the element size to compute the element offset.
3289       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3290 
3291       // Add the element offset to the running total offset.
3292       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3293     }
3294   }
3295 
3296   // Add the total offset from all the GEP indices to the base.
3297   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3298 }
3299 
3300 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3301                                          const SCEV *RHS) {
3302   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3303   return getSMaxExpr(Ops);
3304 }
3305 
3306 const SCEV *
3307 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3308   assert(!Ops.empty() && "Cannot get empty smax!");
3309   if (Ops.size() == 1) return Ops[0];
3310 #ifndef NDEBUG
3311   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3312   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3313     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3314            "SCEVSMaxExpr operand types don't match!");
3315 #endif
3316 
3317   // Sort by complexity, this groups all similar expression types together.
3318   GroupByComplexity(Ops, &LI, DT);
3319 
3320   // If there are any constants, fold them together.
3321   unsigned Idx = 0;
3322   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3323     ++Idx;
3324     assert(Idx < Ops.size());
3325     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3326       // We found two constants, fold them together!
3327       ConstantInt *Fold = ConstantInt::get(
3328           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3329       Ops[0] = getConstant(Fold);
3330       Ops.erase(Ops.begin()+1);  // Erase the folded element
3331       if (Ops.size() == 1) return Ops[0];
3332       LHSC = cast<SCEVConstant>(Ops[0]);
3333     }
3334 
3335     // If we are left with a constant minimum-int, strip it off.
3336     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3337       Ops.erase(Ops.begin());
3338       --Idx;
3339     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3340       // If we have an smax with a constant maximum-int, it will always be
3341       // maximum-int.
3342       return Ops[0];
3343     }
3344 
3345     if (Ops.size() == 1) return Ops[0];
3346   }
3347 
3348   // Find the first SMax
3349   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3350     ++Idx;
3351 
3352   // Check to see if one of the operands is an SMax. If so, expand its operands
3353   // onto our operand list, and recurse to simplify.
3354   if (Idx < Ops.size()) {
3355     bool DeletedSMax = false;
3356     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3357       Ops.erase(Ops.begin()+Idx);
3358       Ops.append(SMax->op_begin(), SMax->op_end());
3359       DeletedSMax = true;
3360     }
3361 
3362     if (DeletedSMax)
3363       return getSMaxExpr(Ops);
3364   }
3365 
3366   // Okay, check to see if the same value occurs in the operand list twice.  If
3367   // so, delete one.  Since we sorted the list, these values are required to
3368   // be adjacent.
3369   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3370     //  X smax Y smax Y  -->  X smax Y
3371     //  X smax Y         -->  X, if X is always greater than Y
3372     if (Ops[i] == Ops[i+1] ||
3373         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3374       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3375       --i; --e;
3376     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3377       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3378       --i; --e;
3379     }
3380 
3381   if (Ops.size() == 1) return Ops[0];
3382 
3383   assert(!Ops.empty() && "Reduced smax down to nothing!");
3384 
3385   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3386   // already have one, otherwise create a new one.
3387   FoldingSetNodeID ID;
3388   ID.AddInteger(scSMaxExpr);
3389   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3390     ID.AddPointer(Ops[i]);
3391   void *IP = nullptr;
3392   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3393   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3394   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3395   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3396                                              O, Ops.size());
3397   UniqueSCEVs.InsertNode(S, IP);
3398   return S;
3399 }
3400 
3401 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3402                                          const SCEV *RHS) {
3403   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3404   return getUMaxExpr(Ops);
3405 }
3406 
3407 const SCEV *
3408 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3409   assert(!Ops.empty() && "Cannot get empty umax!");
3410   if (Ops.size() == 1) return Ops[0];
3411 #ifndef NDEBUG
3412   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3413   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3414     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3415            "SCEVUMaxExpr operand types don't match!");
3416 #endif
3417 
3418   // Sort by complexity, this groups all similar expression types together.
3419   GroupByComplexity(Ops, &LI, DT);
3420 
3421   // If there are any constants, fold them together.
3422   unsigned Idx = 0;
3423   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3424     ++Idx;
3425     assert(Idx < Ops.size());
3426     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3427       // We found two constants, fold them together!
3428       ConstantInt *Fold = ConstantInt::get(
3429           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3430       Ops[0] = getConstant(Fold);
3431       Ops.erase(Ops.begin()+1);  // Erase the folded element
3432       if (Ops.size() == 1) return Ops[0];
3433       LHSC = cast<SCEVConstant>(Ops[0]);
3434     }
3435 
3436     // If we are left with a constant minimum-int, strip it off.
3437     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3438       Ops.erase(Ops.begin());
3439       --Idx;
3440     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3441       // If we have an umax with a constant maximum-int, it will always be
3442       // maximum-int.
3443       return Ops[0];
3444     }
3445 
3446     if (Ops.size() == 1) return Ops[0];
3447   }
3448 
3449   // Find the first UMax
3450   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3451     ++Idx;
3452 
3453   // Check to see if one of the operands is a UMax. If so, expand its operands
3454   // onto our operand list, and recurse to simplify.
3455   if (Idx < Ops.size()) {
3456     bool DeletedUMax = false;
3457     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3458       Ops.erase(Ops.begin()+Idx);
3459       Ops.append(UMax->op_begin(), UMax->op_end());
3460       DeletedUMax = true;
3461     }
3462 
3463     if (DeletedUMax)
3464       return getUMaxExpr(Ops);
3465   }
3466 
3467   // Okay, check to see if the same value occurs in the operand list twice.  If
3468   // so, delete one.  Since we sorted the list, these values are required to
3469   // be adjacent.
3470   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3471     //  X umax Y umax Y  -->  X umax Y
3472     //  X umax Y         -->  X, if X is always greater than Y
3473     if (Ops[i] == Ops[i+1] ||
3474         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3475       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3476       --i; --e;
3477     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3478       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3479       --i; --e;
3480     }
3481 
3482   if (Ops.size() == 1) return Ops[0];
3483 
3484   assert(!Ops.empty() && "Reduced umax down to nothing!");
3485 
3486   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3487   // already have one, otherwise create a new one.
3488   FoldingSetNodeID ID;
3489   ID.AddInteger(scUMaxExpr);
3490   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3491     ID.AddPointer(Ops[i]);
3492   void *IP = nullptr;
3493   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3494   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3495   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3496   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3497                                              O, Ops.size());
3498   UniqueSCEVs.InsertNode(S, IP);
3499   return S;
3500 }
3501 
3502 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3503                                          const SCEV *RHS) {
3504   // ~smax(~x, ~y) == smin(x, y).
3505   return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3506 }
3507 
3508 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3509                                          const SCEV *RHS) {
3510   // ~umax(~x, ~y) == umin(x, y)
3511   return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3512 }
3513 
3514 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3515   // We can bypass creating a target-independent
3516   // constant expression and then folding it back into a ConstantInt.
3517   // This is just a compile-time optimization.
3518   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3519 }
3520 
3521 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3522                                              StructType *STy,
3523                                              unsigned FieldNo) {
3524   // We can bypass creating a target-independent
3525   // constant expression and then folding it back into a ConstantInt.
3526   // This is just a compile-time optimization.
3527   return getConstant(
3528       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3529 }
3530 
3531 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3532   // Don't attempt to do anything other than create a SCEVUnknown object
3533   // here.  createSCEV only calls getUnknown after checking for all other
3534   // interesting possibilities, and any other code that calls getUnknown
3535   // is doing so in order to hide a value from SCEV canonicalization.
3536 
3537   FoldingSetNodeID ID;
3538   ID.AddInteger(scUnknown);
3539   ID.AddPointer(V);
3540   void *IP = nullptr;
3541   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3542     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3543            "Stale SCEVUnknown in uniquing map!");
3544     return S;
3545   }
3546   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3547                                             FirstUnknown);
3548   FirstUnknown = cast<SCEVUnknown>(S);
3549   UniqueSCEVs.InsertNode(S, IP);
3550   return S;
3551 }
3552 
3553 //===----------------------------------------------------------------------===//
3554 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3555 //
3556 
3557 /// Test if values of the given type are analyzable within the SCEV
3558 /// framework. This primarily includes integer types, and it can optionally
3559 /// include pointer types if the ScalarEvolution class has access to
3560 /// target-specific information.
3561 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3562   // Integers and pointers are always SCEVable.
3563   return Ty->isIntegerTy() || Ty->isPointerTy();
3564 }
3565 
3566 /// Return the size in bits of the specified type, for which isSCEVable must
3567 /// return true.
3568 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3569   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3570   return getDataLayout().getTypeSizeInBits(Ty);
3571 }
3572 
3573 /// Return a type with the same bitwidth as the given type and which represents
3574 /// how SCEV will treat the given type, for which isSCEVable must return
3575 /// true. For pointer types, this is the pointer-sized integer type.
3576 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3577   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3578 
3579   if (Ty->isIntegerTy())
3580     return Ty;
3581 
3582   // The only other support type is pointer.
3583   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3584   return getDataLayout().getIntPtrType(Ty);
3585 }
3586 
3587 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3588   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3589 }
3590 
3591 const SCEV *ScalarEvolution::getCouldNotCompute() {
3592   return CouldNotCompute.get();
3593 }
3594 
3595 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3596   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3597     auto *SU = dyn_cast<SCEVUnknown>(S);
3598     return SU && SU->getValue() == nullptr;
3599   });
3600 
3601   return !ContainsNulls;
3602 }
3603 
3604 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3605   HasRecMapType::iterator I = HasRecMap.find(S);
3606   if (I != HasRecMap.end())
3607     return I->second;
3608 
3609   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3610   HasRecMap.insert({S, FoundAddRec});
3611   return FoundAddRec;
3612 }
3613 
3614 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3615 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3616 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3617 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3618   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3619   if (!Add)
3620     return {S, nullptr};
3621 
3622   if (Add->getNumOperands() != 2)
3623     return {S, nullptr};
3624 
3625   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3626   if (!ConstOp)
3627     return {S, nullptr};
3628 
3629   return {Add->getOperand(1), ConstOp->getValue()};
3630 }
3631 
3632 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3633 /// by the value and offset from any ValueOffsetPair in the set.
3634 SetVector<ScalarEvolution::ValueOffsetPair> *
3635 ScalarEvolution::getSCEVValues(const SCEV *S) {
3636   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3637   if (SI == ExprValueMap.end())
3638     return nullptr;
3639 #ifndef NDEBUG
3640   if (VerifySCEVMap) {
3641     // Check there is no dangling Value in the set returned.
3642     for (const auto &VE : SI->second)
3643       assert(ValueExprMap.count(VE.first));
3644   }
3645 #endif
3646   return &SI->second;
3647 }
3648 
3649 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3650 /// cannot be used separately. eraseValueFromMap should be used to remove
3651 /// V from ValueExprMap and ExprValueMap at the same time.
3652 void ScalarEvolution::eraseValueFromMap(Value *V) {
3653   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3654   if (I != ValueExprMap.end()) {
3655     const SCEV *S = I->second;
3656     // Remove {V, 0} from the set of ExprValueMap[S]
3657     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3658       SV->remove({V, nullptr});
3659 
3660     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3661     const SCEV *Stripped;
3662     ConstantInt *Offset;
3663     std::tie(Stripped, Offset) = splitAddExpr(S);
3664     if (Offset != nullptr) {
3665       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3666         SV->remove({V, Offset});
3667     }
3668     ValueExprMap.erase(V);
3669   }
3670 }
3671 
3672 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3673 /// create a new one.
3674 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3675   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3676 
3677   const SCEV *S = getExistingSCEV(V);
3678   if (S == nullptr) {
3679     S = createSCEV(V);
3680     // During PHI resolution, it is possible to create two SCEVs for the same
3681     // V, so it is needed to double check whether V->S is inserted into
3682     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3683     std::pair<ValueExprMapType::iterator, bool> Pair =
3684         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3685     if (Pair.second) {
3686       ExprValueMap[S].insert({V, nullptr});
3687 
3688       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3689       // ExprValueMap.
3690       const SCEV *Stripped = S;
3691       ConstantInt *Offset = nullptr;
3692       std::tie(Stripped, Offset) = splitAddExpr(S);
3693       // If stripped is SCEVUnknown, don't bother to save
3694       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3695       // increase the complexity of the expansion code.
3696       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3697       // because it may generate add/sub instead of GEP in SCEV expansion.
3698       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3699           !isa<GetElementPtrInst>(V))
3700         ExprValueMap[Stripped].insert({V, Offset});
3701     }
3702   }
3703   return S;
3704 }
3705 
3706 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3707   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3708 
3709   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3710   if (I != ValueExprMap.end()) {
3711     const SCEV *S = I->second;
3712     if (checkValidity(S))
3713       return S;
3714     eraseValueFromMap(V);
3715     forgetMemoizedResults(S);
3716   }
3717   return nullptr;
3718 }
3719 
3720 /// Return a SCEV corresponding to -V = -1*V
3721 ///
3722 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3723                                              SCEV::NoWrapFlags Flags) {
3724   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3725     return getConstant(
3726                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3727 
3728   Type *Ty = V->getType();
3729   Ty = getEffectiveSCEVType(Ty);
3730   return getMulExpr(
3731       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3732 }
3733 
3734 /// Return a SCEV corresponding to ~V = -1-V
3735 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3736   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3737     return getConstant(
3738                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3739 
3740   Type *Ty = V->getType();
3741   Ty = getEffectiveSCEVType(Ty);
3742   const SCEV *AllOnes =
3743                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3744   return getMinusSCEV(AllOnes, V);
3745 }
3746 
3747 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3748                                           SCEV::NoWrapFlags Flags,
3749                                           unsigned Depth) {
3750   // Fast path: X - X --> 0.
3751   if (LHS == RHS)
3752     return getZero(LHS->getType());
3753 
3754   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3755   // makes it so that we cannot make much use of NUW.
3756   auto AddFlags = SCEV::FlagAnyWrap;
3757   const bool RHSIsNotMinSigned =
3758       !getSignedRangeMin(RHS).isMinSignedValue();
3759   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3760     // Let M be the minimum representable signed value. Then (-1)*RHS
3761     // signed-wraps if and only if RHS is M. That can happen even for
3762     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3763     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3764     // (-1)*RHS, we need to prove that RHS != M.
3765     //
3766     // If LHS is non-negative and we know that LHS - RHS does not
3767     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3768     // either by proving that RHS > M or that LHS >= 0.
3769     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3770       AddFlags = SCEV::FlagNSW;
3771     }
3772   }
3773 
3774   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3775   // RHS is NSW and LHS >= 0.
3776   //
3777   // The difficulty here is that the NSW flag may have been proven
3778   // relative to a loop that is to be found in a recurrence in LHS and
3779   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3780   // larger scope than intended.
3781   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3782 
3783   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3784 }
3785 
3786 const SCEV *
3787 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3788   Type *SrcTy = V->getType();
3789   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3790          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3791          "Cannot truncate or zero extend with non-integer arguments!");
3792   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3793     return V;  // No conversion
3794   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3795     return getTruncateExpr(V, Ty);
3796   return getZeroExtendExpr(V, Ty);
3797 }
3798 
3799 const SCEV *
3800 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3801                                          Type *Ty) {
3802   Type *SrcTy = V->getType();
3803   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3804          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3805          "Cannot truncate or zero extend with non-integer arguments!");
3806   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3807     return V;  // No conversion
3808   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3809     return getTruncateExpr(V, Ty);
3810   return getSignExtendExpr(V, Ty);
3811 }
3812 
3813 const SCEV *
3814 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3815   Type *SrcTy = V->getType();
3816   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3817          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3818          "Cannot noop or zero extend with non-integer arguments!");
3819   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3820          "getNoopOrZeroExtend cannot truncate!");
3821   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3822     return V;  // No conversion
3823   return getZeroExtendExpr(V, Ty);
3824 }
3825 
3826 const SCEV *
3827 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3828   Type *SrcTy = V->getType();
3829   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3830          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3831          "Cannot noop or sign extend with non-integer arguments!");
3832   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3833          "getNoopOrSignExtend cannot truncate!");
3834   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3835     return V;  // No conversion
3836   return getSignExtendExpr(V, Ty);
3837 }
3838 
3839 const SCEV *
3840 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3841   Type *SrcTy = V->getType();
3842   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3843          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3844          "Cannot noop or any extend with non-integer arguments!");
3845   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3846          "getNoopOrAnyExtend cannot truncate!");
3847   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3848     return V;  // No conversion
3849   return getAnyExtendExpr(V, Ty);
3850 }
3851 
3852 const SCEV *
3853 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3854   Type *SrcTy = V->getType();
3855   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3856          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3857          "Cannot truncate or noop with non-integer arguments!");
3858   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3859          "getTruncateOrNoop cannot extend!");
3860   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3861     return V;  // No conversion
3862   return getTruncateExpr(V, Ty);
3863 }
3864 
3865 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3866                                                         const SCEV *RHS) {
3867   const SCEV *PromotedLHS = LHS;
3868   const SCEV *PromotedRHS = RHS;
3869 
3870   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3871     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3872   else
3873     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3874 
3875   return getUMaxExpr(PromotedLHS, PromotedRHS);
3876 }
3877 
3878 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3879                                                         const SCEV *RHS) {
3880   const SCEV *PromotedLHS = LHS;
3881   const SCEV *PromotedRHS = RHS;
3882 
3883   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3884     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3885   else
3886     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3887 
3888   return getUMinExpr(PromotedLHS, PromotedRHS);
3889 }
3890 
3891 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3892   // A pointer operand may evaluate to a nonpointer expression, such as null.
3893   if (!V->getType()->isPointerTy())
3894     return V;
3895 
3896   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3897     return getPointerBase(Cast->getOperand());
3898   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
3899     const SCEV *PtrOp = nullptr;
3900     for (const SCEV *NAryOp : NAry->operands()) {
3901       if (NAryOp->getType()->isPointerTy()) {
3902         // Cannot find the base of an expression with multiple pointer operands.
3903         if (PtrOp)
3904           return V;
3905         PtrOp = NAryOp;
3906       }
3907     }
3908     if (!PtrOp)
3909       return V;
3910     return getPointerBase(PtrOp);
3911   }
3912   return V;
3913 }
3914 
3915 /// Push users of the given Instruction onto the given Worklist.
3916 static void
3917 PushDefUseChildren(Instruction *I,
3918                    SmallVectorImpl<Instruction *> &Worklist) {
3919   // Push the def-use children onto the Worklist stack.
3920   for (User *U : I->users())
3921     Worklist.push_back(cast<Instruction>(U));
3922 }
3923 
3924 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
3925   SmallVector<Instruction *, 16> Worklist;
3926   PushDefUseChildren(PN, Worklist);
3927 
3928   SmallPtrSet<Instruction *, 8> Visited;
3929   Visited.insert(PN);
3930   while (!Worklist.empty()) {
3931     Instruction *I = Worklist.pop_back_val();
3932     if (!Visited.insert(I).second)
3933       continue;
3934 
3935     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
3936     if (It != ValueExprMap.end()) {
3937       const SCEV *Old = It->second;
3938 
3939       // Short-circuit the def-use traversal if the symbolic name
3940       // ceases to appear in expressions.
3941       if (Old != SymName && !hasOperand(Old, SymName))
3942         continue;
3943 
3944       // SCEVUnknown for a PHI either means that it has an unrecognized
3945       // structure, it's a PHI that's in the progress of being computed
3946       // by createNodeForPHI, or it's a single-value PHI. In the first case,
3947       // additional loop trip count information isn't going to change anything.
3948       // In the second case, createNodeForPHI will perform the necessary
3949       // updates on its own when it gets to that point. In the third, we do
3950       // want to forget the SCEVUnknown.
3951       if (!isa<PHINode>(I) ||
3952           !isa<SCEVUnknown>(Old) ||
3953           (I != PN && Old == SymName)) {
3954         eraseValueFromMap(It->first);
3955         forgetMemoizedResults(Old);
3956       }
3957     }
3958 
3959     PushDefUseChildren(I, Worklist);
3960   }
3961 }
3962 
3963 namespace {
3964 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3965 public:
3966   static const SCEV *rewrite(const SCEV *S, const Loop *L,
3967                              ScalarEvolution &SE) {
3968     SCEVInitRewriter Rewriter(L, SE);
3969     const SCEV *Result = Rewriter.visit(S);
3970     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3971   }
3972 
3973   SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3974       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3975 
3976   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3977     if (!SE.isLoopInvariant(Expr, L))
3978       Valid = false;
3979     return Expr;
3980   }
3981 
3982   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3983     // Only allow AddRecExprs for this loop.
3984     if (Expr->getLoop() == L)
3985       return Expr->getStart();
3986     Valid = false;
3987     return Expr;
3988   }
3989 
3990   bool isValid() { return Valid; }
3991 
3992 private:
3993   const Loop *L;
3994   bool Valid;
3995 };
3996 
3997 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3998 public:
3999   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4000                              ScalarEvolution &SE) {
4001     SCEVShiftRewriter Rewriter(L, SE);
4002     const SCEV *Result = Rewriter.visit(S);
4003     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4004   }
4005 
4006   SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4007       : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
4008 
4009   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4010     // Only allow AddRecExprs for this loop.
4011     if (!SE.isLoopInvariant(Expr, L))
4012       Valid = false;
4013     return Expr;
4014   }
4015 
4016   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4017     if (Expr->getLoop() == L && Expr->isAffine())
4018       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4019     Valid = false;
4020     return Expr;
4021   }
4022   bool isValid() { return Valid; }
4023 
4024 private:
4025   const Loop *L;
4026   bool Valid;
4027 };
4028 } // end anonymous namespace
4029 
4030 SCEV::NoWrapFlags
4031 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4032   if (!AR->isAffine())
4033     return SCEV::FlagAnyWrap;
4034 
4035   typedef OverflowingBinaryOperator OBO;
4036   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4037 
4038   if (!AR->hasNoSignedWrap()) {
4039     ConstantRange AddRecRange = getSignedRange(AR);
4040     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4041 
4042     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4043         Instruction::Add, IncRange, OBO::NoSignedWrap);
4044     if (NSWRegion.contains(AddRecRange))
4045       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4046   }
4047 
4048   if (!AR->hasNoUnsignedWrap()) {
4049     ConstantRange AddRecRange = getUnsignedRange(AR);
4050     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4051 
4052     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4053         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4054     if (NUWRegion.contains(AddRecRange))
4055       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4056   }
4057 
4058   return Result;
4059 }
4060 
4061 namespace {
4062 /// Represents an abstract binary operation.  This may exist as a
4063 /// normal instruction or constant expression, or may have been
4064 /// derived from an expression tree.
4065 struct BinaryOp {
4066   unsigned Opcode;
4067   Value *LHS;
4068   Value *RHS;
4069   bool IsNSW;
4070   bool IsNUW;
4071 
4072   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4073   /// constant expression.
4074   Operator *Op;
4075 
4076   explicit BinaryOp(Operator *Op)
4077       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4078         IsNSW(false), IsNUW(false), Op(Op) {
4079     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4080       IsNSW = OBO->hasNoSignedWrap();
4081       IsNUW = OBO->hasNoUnsignedWrap();
4082     }
4083   }
4084 
4085   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4086                     bool IsNUW = false)
4087       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4088         Op(nullptr) {}
4089 };
4090 }
4091 
4092 
4093 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4094 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4095   auto *Op = dyn_cast<Operator>(V);
4096   if (!Op)
4097     return None;
4098 
4099   // Implementation detail: all the cleverness here should happen without
4100   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4101   // SCEV expressions when possible, and we should not break that.
4102 
4103   switch (Op->getOpcode()) {
4104   case Instruction::Add:
4105   case Instruction::Sub:
4106   case Instruction::Mul:
4107   case Instruction::UDiv:
4108   case Instruction::And:
4109   case Instruction::Or:
4110   case Instruction::AShr:
4111   case Instruction::Shl:
4112     return BinaryOp(Op);
4113 
4114   case Instruction::Xor:
4115     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4116       // If the RHS of the xor is a signmask, then this is just an add.
4117       // Instcombine turns add of signmask into xor as a strength reduction step.
4118       if (RHSC->getValue().isSignMask())
4119         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4120     return BinaryOp(Op);
4121 
4122   case Instruction::LShr:
4123     // Turn logical shift right of a constant into a unsigned divide.
4124     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4125       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4126 
4127       // If the shift count is not less than the bitwidth, the result of
4128       // the shift is undefined. Don't try to analyze it, because the
4129       // resolution chosen here may differ from the resolution chosen in
4130       // other parts of the compiler.
4131       if (SA->getValue().ult(BitWidth)) {
4132         Constant *X =
4133             ConstantInt::get(SA->getContext(),
4134                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4135         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4136       }
4137     }
4138     return BinaryOp(Op);
4139 
4140   case Instruction::ExtractValue: {
4141     auto *EVI = cast<ExtractValueInst>(Op);
4142     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4143       break;
4144 
4145     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4146     if (!CI)
4147       break;
4148 
4149     if (auto *F = CI->getCalledFunction())
4150       switch (F->getIntrinsicID()) {
4151       case Intrinsic::sadd_with_overflow:
4152       case Intrinsic::uadd_with_overflow: {
4153         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4154           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4155                           CI->getArgOperand(1));
4156 
4157         // Now that we know that all uses of the arithmetic-result component of
4158         // CI are guarded by the overflow check, we can go ahead and pretend
4159         // that the arithmetic is non-overflowing.
4160         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4161           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4162                           CI->getArgOperand(1), /* IsNSW = */ true,
4163                           /* IsNUW = */ false);
4164         else
4165           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4166                           CI->getArgOperand(1), /* IsNSW = */ false,
4167                           /* IsNUW*/ true);
4168       }
4169 
4170       case Intrinsic::ssub_with_overflow:
4171       case Intrinsic::usub_with_overflow:
4172         return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4173                         CI->getArgOperand(1));
4174 
4175       case Intrinsic::smul_with_overflow:
4176       case Intrinsic::umul_with_overflow:
4177         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4178                         CI->getArgOperand(1));
4179       default:
4180         break;
4181       }
4182   }
4183 
4184   default:
4185     break;
4186   }
4187 
4188   return None;
4189 }
4190 
4191 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4192 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4193 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4194 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4195 /// follows one of the following patterns:
4196 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4197 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4198 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4199 /// we return the type of the truncation operation, and indicate whether the
4200 /// truncated type should be treated as signed/unsigned by setting
4201 /// \p Signed to true/false, respectively.
4202 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4203                                bool &Signed, ScalarEvolution &SE) {
4204 
4205   // The case where Op == SymbolicPHI (that is, with no type conversions on
4206   // the way) is handled by the regular add recurrence creating logic and
4207   // would have already been triggered in createAddRecForPHI. Reaching it here
4208   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4209   // because one of the other operands of the SCEVAddExpr updating this PHI is
4210   // not invariant).
4211   //
4212   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4213   // this case predicates that allow us to prove that Op == SymbolicPHI will
4214   // be added.
4215   if (Op == SymbolicPHI)
4216     return nullptr;
4217 
4218   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4219   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4220   if (SourceBits != NewBits)
4221     return nullptr;
4222 
4223   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4224   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4225   if (!SExt && !ZExt)
4226     return nullptr;
4227   const SCEVTruncateExpr *Trunc =
4228       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4229            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4230   if (!Trunc)
4231     return nullptr;
4232   const SCEV *X = Trunc->getOperand();
4233   if (X != SymbolicPHI)
4234     return nullptr;
4235   Signed = SExt ? true : false;
4236   return Trunc->getType();
4237 }
4238 
4239 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4240   if (!PN->getType()->isIntegerTy())
4241     return nullptr;
4242   const Loop *L = LI.getLoopFor(PN->getParent());
4243   if (!L || L->getHeader() != PN->getParent())
4244     return nullptr;
4245   return L;
4246 }
4247 
4248 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4249 // computation that updates the phi follows the following pattern:
4250 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4251 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4252 // If so, try to see if it can be rewritten as an AddRecExpr under some
4253 // Predicates. If successful, return them as a pair. Also cache the results
4254 // of the analysis.
4255 //
4256 // Example usage scenario:
4257 //    Say the Rewriter is called for the following SCEV:
4258 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4259 //    where:
4260 //         %X = phi i64 (%Start, %BEValue)
4261 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4262 //    and call this function with %SymbolicPHI = %X.
4263 //
4264 //    The analysis will find that the value coming around the backedge has
4265 //    the following SCEV:
4266 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4267 //    Upon concluding that this matches the desired pattern, the function
4268 //    will return the pair {NewAddRec, SmallPredsVec} where:
4269 //         NewAddRec = {%Start,+,%Step}
4270 //         SmallPredsVec = {P1, P2, P3} as follows:
4271 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4272 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4273 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4274 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4275 //    under the predicates {P1,P2,P3}.
4276 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4277 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4278 //
4279 // TODO's:
4280 //
4281 // 1) Extend the Induction descriptor to also support inductions that involve
4282 //    casts: When needed (namely, when we are called in the context of the
4283 //    vectorizer induction analysis), a Set of cast instructions will be
4284 //    populated by this method, and provided back to isInductionPHI. This is
4285 //    needed to allow the vectorizer to properly record them to be ignored by
4286 //    the cost model and to avoid vectorizing them (otherwise these casts,
4287 //    which are redundant under the runtime overflow checks, will be
4288 //    vectorized, which can be costly).
4289 //
4290 // 2) Support additional induction/PHISCEV patterns: We also want to support
4291 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4292 //    after the induction update operation (the induction increment):
4293 //
4294 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4295 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4296 //
4297 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4298 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4299 //
4300 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4301 //
4302 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4303 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4304   SmallVector<const SCEVPredicate *, 3> Predicates;
4305 
4306   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4307   // return an AddRec expression under some predicate.
4308 
4309   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4310   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4311   assert (L && "Expecting an integer loop header phi");
4312 
4313   // The loop may have multiple entrances or multiple exits; we can analyze
4314   // this phi as an addrec if it has a unique entry value and a unique
4315   // backedge value.
4316   Value *BEValueV = nullptr, *StartValueV = nullptr;
4317   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4318     Value *V = PN->getIncomingValue(i);
4319     if (L->contains(PN->getIncomingBlock(i))) {
4320       if (!BEValueV) {
4321         BEValueV = V;
4322       } else if (BEValueV != V) {
4323         BEValueV = nullptr;
4324         break;
4325       }
4326     } else if (!StartValueV) {
4327       StartValueV = V;
4328     } else if (StartValueV != V) {
4329       StartValueV = nullptr;
4330       break;
4331     }
4332   }
4333   if (!BEValueV || !StartValueV)
4334     return None;
4335 
4336   const SCEV *BEValue = getSCEV(BEValueV);
4337 
4338   // If the value coming around the backedge is an add with the symbolic
4339   // value we just inserted, possibly with casts that we can ignore under
4340   // an appropriate runtime guard, then we found a simple induction variable!
4341   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4342   if (!Add)
4343     return None;
4344 
4345   // If there is a single occurrence of the symbolic value, possibly
4346   // casted, replace it with a recurrence.
4347   unsigned FoundIndex = Add->getNumOperands();
4348   Type *TruncTy = nullptr;
4349   bool Signed;
4350   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4351     if ((TruncTy =
4352              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4353       if (FoundIndex == e) {
4354         FoundIndex = i;
4355         break;
4356       }
4357 
4358   if (FoundIndex == Add->getNumOperands())
4359     return None;
4360 
4361   // Create an add with everything but the specified operand.
4362   SmallVector<const SCEV *, 8> Ops;
4363   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4364     if (i != FoundIndex)
4365       Ops.push_back(Add->getOperand(i));
4366   const SCEV *Accum = getAddExpr(Ops);
4367 
4368   // The runtime checks will not be valid if the step amount is
4369   // varying inside the loop.
4370   if (!isLoopInvariant(Accum, L))
4371     return None;
4372 
4373 
4374   // *** Part2: Create the predicates
4375 
4376   // Analysis was successful: we have a phi-with-cast pattern for which we
4377   // can return an AddRec expression under the following predicates:
4378   //
4379   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4380   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4381   // P2: An Equal predicate that guarantees that
4382   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4383   // P3: An Equal predicate that guarantees that
4384   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4385   //
4386   // As we next prove, the above predicates guarantee that:
4387   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4388   //
4389   //
4390   // More formally, we want to prove that:
4391   //     Expr(i+1) = Start + (i+1) * Accum
4392   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4393   //
4394   // Given that:
4395   // 1) Expr(0) = Start
4396   // 2) Expr(1) = Start + Accum
4397   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4398   // 3) Induction hypothesis (step i):
4399   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4400   //
4401   // Proof:
4402   //  Expr(i+1) =
4403   //   = Start + (i+1)*Accum
4404   //   = (Start + i*Accum) + Accum
4405   //   = Expr(i) + Accum
4406   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4407   //                                                             :: from step i
4408   //
4409   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4410   //
4411   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4412   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4413   //     + Accum                                                     :: from P3
4414   //
4415   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4416   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4417   //
4418   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4419   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4420   //
4421   // By induction, the same applies to all iterations 1<=i<n:
4422   //
4423 
4424   // Create a truncated addrec for which we will add a no overflow check (P1).
4425   const SCEV *StartVal = getSCEV(StartValueV);
4426   const SCEV *PHISCEV =
4427       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4428                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4429   const auto *AR = cast<SCEVAddRecExpr>(PHISCEV);
4430 
4431   SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4432       Signed ? SCEVWrapPredicate::IncrementNSSW
4433              : SCEVWrapPredicate::IncrementNUSW;
4434   const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4435   Predicates.push_back(AddRecPred);
4436 
4437   // Create the Equal Predicates P2,P3:
4438   auto AppendPredicate = [&](const SCEV *Expr) -> void {
4439     assert (isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4440     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4441     const SCEV *ExtendedExpr =
4442         Signed ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4443                : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4444     if (Expr != ExtendedExpr &&
4445         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4446       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4447       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4448       Predicates.push_back(Pred);
4449     }
4450   };
4451 
4452   AppendPredicate(StartVal);
4453   AppendPredicate(Accum);
4454 
4455   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4456   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4457   // into NewAR if it will also add the runtime overflow checks specified in
4458   // Predicates.
4459   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4460 
4461   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4462       std::make_pair(NewAR, Predicates);
4463   // Remember the result of the analysis for this SCEV at this locayyytion.
4464   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4465   return PredRewrite;
4466 }
4467 
4468 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4469 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4470 
4471   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4472   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4473   if (!L)
4474     return None;
4475 
4476   // Check to see if we already analyzed this PHI.
4477   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4478   if (I != PredicatedSCEVRewrites.end()) {
4479     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4480         I->second;
4481     // Analysis was done before and failed to create an AddRec:
4482     if (Rewrite.first == SymbolicPHI)
4483       return None;
4484     // Analysis was done before and succeeded to create an AddRec under
4485     // a predicate:
4486     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4487     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4488     return Rewrite;
4489   }
4490 
4491   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4492     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4493 
4494   // Record in the cache that the analysis failed
4495   if (!Rewrite) {
4496     SmallVector<const SCEVPredicate *, 3> Predicates;
4497     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4498     return None;
4499   }
4500 
4501   return Rewrite;
4502 }
4503 
4504 /// A helper function for createAddRecFromPHI to handle simple cases.
4505 ///
4506 /// This function tries to find an AddRec expression for the simplest (yet most
4507 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4508 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4509 /// technique for finding the AddRec expression.
4510 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4511                                                       Value *BEValueV,
4512                                                       Value *StartValueV) {
4513   const Loop *L = LI.getLoopFor(PN->getParent());
4514   assert(L && L->getHeader() == PN->getParent());
4515   assert(BEValueV && StartValueV);
4516 
4517   auto BO = MatchBinaryOp(BEValueV, DT);
4518   if (!BO)
4519     return nullptr;
4520 
4521   if (BO->Opcode != Instruction::Add)
4522     return nullptr;
4523 
4524   const SCEV *Accum = nullptr;
4525   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4526     Accum = getSCEV(BO->RHS);
4527   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4528     Accum = getSCEV(BO->LHS);
4529 
4530   if (!Accum)
4531     return nullptr;
4532 
4533   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4534   if (BO->IsNUW)
4535     Flags = setFlags(Flags, SCEV::FlagNUW);
4536   if (BO->IsNSW)
4537     Flags = setFlags(Flags, SCEV::FlagNSW);
4538 
4539   const SCEV *StartVal = getSCEV(StartValueV);
4540   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4541 
4542   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4543 
4544   // We can add Flags to the post-inc expression only if we
4545   // know that it is *undefined behavior* for BEValueV to
4546   // overflow.
4547   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4548     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4549       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4550 
4551   return PHISCEV;
4552 }
4553 
4554 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4555   const Loop *L = LI.getLoopFor(PN->getParent());
4556   if (!L || L->getHeader() != PN->getParent())
4557     return nullptr;
4558 
4559   // The loop may have multiple entrances or multiple exits; we can analyze
4560   // this phi as an addrec if it has a unique entry value and a unique
4561   // backedge value.
4562   Value *BEValueV = nullptr, *StartValueV = nullptr;
4563   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4564     Value *V = PN->getIncomingValue(i);
4565     if (L->contains(PN->getIncomingBlock(i))) {
4566       if (!BEValueV) {
4567         BEValueV = V;
4568       } else if (BEValueV != V) {
4569         BEValueV = nullptr;
4570         break;
4571       }
4572     } else if (!StartValueV) {
4573       StartValueV = V;
4574     } else if (StartValueV != V) {
4575       StartValueV = nullptr;
4576       break;
4577     }
4578   }
4579   if (!BEValueV || !StartValueV)
4580     return nullptr;
4581 
4582   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4583          "PHI node already processed?");
4584 
4585   // First, try to find AddRec expression without creating a fictituos symbolic
4586   // value for PN.
4587   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4588     return S;
4589 
4590   // Handle PHI node value symbolically.
4591   const SCEV *SymbolicName = getUnknown(PN);
4592   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4593 
4594   // Using this symbolic name for the PHI, analyze the value coming around
4595   // the back-edge.
4596   const SCEV *BEValue = getSCEV(BEValueV);
4597 
4598   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4599   // has a special value for the first iteration of the loop.
4600 
4601   // If the value coming around the backedge is an add with the symbolic
4602   // value we just inserted, then we found a simple induction variable!
4603   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4604     // If there is a single occurrence of the symbolic value, replace it
4605     // with a recurrence.
4606     unsigned FoundIndex = Add->getNumOperands();
4607     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4608       if (Add->getOperand(i) == SymbolicName)
4609         if (FoundIndex == e) {
4610           FoundIndex = i;
4611           break;
4612         }
4613 
4614     if (FoundIndex != Add->getNumOperands()) {
4615       // Create an add with everything but the specified operand.
4616       SmallVector<const SCEV *, 8> Ops;
4617       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4618         if (i != FoundIndex)
4619           Ops.push_back(Add->getOperand(i));
4620       const SCEV *Accum = getAddExpr(Ops);
4621 
4622       // This is not a valid addrec if the step amount is varying each
4623       // loop iteration, but is not itself an addrec in this loop.
4624       if (isLoopInvariant(Accum, L) ||
4625           (isa<SCEVAddRecExpr>(Accum) &&
4626            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4627         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4628 
4629         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4630           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4631             if (BO->IsNUW)
4632               Flags = setFlags(Flags, SCEV::FlagNUW);
4633             if (BO->IsNSW)
4634               Flags = setFlags(Flags, SCEV::FlagNSW);
4635           }
4636         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4637           // If the increment is an inbounds GEP, then we know the address
4638           // space cannot be wrapped around. We cannot make any guarantee
4639           // about signed or unsigned overflow because pointers are
4640           // unsigned but we may have a negative index from the base
4641           // pointer. We can guarantee that no unsigned wrap occurs if the
4642           // indices form a positive value.
4643           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4644             Flags = setFlags(Flags, SCEV::FlagNW);
4645 
4646             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4647             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4648               Flags = setFlags(Flags, SCEV::FlagNUW);
4649           }
4650 
4651           // We cannot transfer nuw and nsw flags from subtraction
4652           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4653           // for instance.
4654         }
4655 
4656         const SCEV *StartVal = getSCEV(StartValueV);
4657         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4658 
4659         // Okay, for the entire analysis of this edge we assumed the PHI
4660         // to be symbolic.  We now need to go back and purge all of the
4661         // entries for the scalars that use the symbolic expression.
4662         forgetSymbolicName(PN, SymbolicName);
4663         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4664 
4665         // We can add Flags to the post-inc expression only if we
4666         // know that it is *undefined behavior* for BEValueV to
4667         // overflow.
4668         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4669           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4670             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4671 
4672         return PHISCEV;
4673       }
4674     }
4675   } else {
4676     // Otherwise, this could be a loop like this:
4677     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4678     // In this case, j = {1,+,1}  and BEValue is j.
4679     // Because the other in-value of i (0) fits the evolution of BEValue
4680     // i really is an addrec evolution.
4681     //
4682     // We can generalize this saying that i is the shifted value of BEValue
4683     // by one iteration:
4684     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
4685     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4686     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4687     if (Shifted != getCouldNotCompute() &&
4688         Start != getCouldNotCompute()) {
4689       const SCEV *StartVal = getSCEV(StartValueV);
4690       if (Start == StartVal) {
4691         // Okay, for the entire analysis of this edge we assumed the PHI
4692         // to be symbolic.  We now need to go back and purge all of the
4693         // entries for the scalars that use the symbolic expression.
4694         forgetSymbolicName(PN, SymbolicName);
4695         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4696         return Shifted;
4697       }
4698     }
4699   }
4700 
4701   // Remove the temporary PHI node SCEV that has been inserted while intending
4702   // to create an AddRecExpr for this PHI node. We can not keep this temporary
4703   // as it will prevent later (possibly simpler) SCEV expressions to be added
4704   // to the ValueExprMap.
4705   eraseValueFromMap(PN);
4706 
4707   return nullptr;
4708 }
4709 
4710 // Checks if the SCEV S is available at BB.  S is considered available at BB
4711 // if S can be materialized at BB without introducing a fault.
4712 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4713                                BasicBlock *BB) {
4714   struct CheckAvailable {
4715     bool TraversalDone = false;
4716     bool Available = true;
4717 
4718     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
4719     BasicBlock *BB = nullptr;
4720     DominatorTree &DT;
4721 
4722     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4723       : L(L), BB(BB), DT(DT) {}
4724 
4725     bool setUnavailable() {
4726       TraversalDone = true;
4727       Available = false;
4728       return false;
4729     }
4730 
4731     bool follow(const SCEV *S) {
4732       switch (S->getSCEVType()) {
4733       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4734       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
4735         // These expressions are available if their operand(s) is/are.
4736         return true;
4737 
4738       case scAddRecExpr: {
4739         // We allow add recurrences that are on the loop BB is in, or some
4740         // outer loop.  This guarantees availability because the value of the
4741         // add recurrence at BB is simply the "current" value of the induction
4742         // variable.  We can relax this in the future; for instance an add
4743         // recurrence on a sibling dominating loop is also available at BB.
4744         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4745         if (L && (ARLoop == L || ARLoop->contains(L)))
4746           return true;
4747 
4748         return setUnavailable();
4749       }
4750 
4751       case scUnknown: {
4752         // For SCEVUnknown, we check for simple dominance.
4753         const auto *SU = cast<SCEVUnknown>(S);
4754         Value *V = SU->getValue();
4755 
4756         if (isa<Argument>(V))
4757           return false;
4758 
4759         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4760           return false;
4761 
4762         return setUnavailable();
4763       }
4764 
4765       case scUDivExpr:
4766       case scCouldNotCompute:
4767         // We do not try to smart about these at all.
4768         return setUnavailable();
4769       }
4770       llvm_unreachable("switch should be fully covered!");
4771     }
4772 
4773     bool isDone() { return TraversalDone; }
4774   };
4775 
4776   CheckAvailable CA(L, BB, DT);
4777   SCEVTraversal<CheckAvailable> ST(CA);
4778 
4779   ST.visitAll(S);
4780   return CA.Available;
4781 }
4782 
4783 // Try to match a control flow sequence that branches out at BI and merges back
4784 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
4785 // match.
4786 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4787                           Value *&C, Value *&LHS, Value *&RHS) {
4788   C = BI->getCondition();
4789 
4790   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4791   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4792 
4793   if (!LeftEdge.isSingleEdge())
4794     return false;
4795 
4796   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4797 
4798   Use &LeftUse = Merge->getOperandUse(0);
4799   Use &RightUse = Merge->getOperandUse(1);
4800 
4801   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4802     LHS = LeftUse;
4803     RHS = RightUse;
4804     return true;
4805   }
4806 
4807   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4808     LHS = RightUse;
4809     RHS = LeftUse;
4810     return true;
4811   }
4812 
4813   return false;
4814 }
4815 
4816 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
4817   auto IsReachable =
4818       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
4819   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
4820     const Loop *L = LI.getLoopFor(PN->getParent());
4821 
4822     // We don't want to break LCSSA, even in a SCEV expression tree.
4823     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4824       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4825         return nullptr;
4826 
4827     // Try to match
4828     //
4829     //  br %cond, label %left, label %right
4830     // left:
4831     //  br label %merge
4832     // right:
4833     //  br label %merge
4834     // merge:
4835     //  V = phi [ %x, %left ], [ %y, %right ]
4836     //
4837     // as "select %cond, %x, %y"
4838 
4839     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4840     assert(IDom && "At least the entry block should dominate PN");
4841 
4842     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4843     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4844 
4845     if (BI && BI->isConditional() &&
4846         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4847         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4848         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
4849       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4850   }
4851 
4852   return nullptr;
4853 }
4854 
4855 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4856   if (const SCEV *S = createAddRecFromPHI(PN))
4857     return S;
4858 
4859   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4860     return S;
4861 
4862   // If the PHI has a single incoming value, follow that value, unless the
4863   // PHI's incoming blocks are in a different loop, in which case doing so
4864   // risks breaking LCSSA form. Instcombine would normally zap these, but
4865   // it doesn't have DominatorTree information, so it may miss cases.
4866   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
4867     if (LI.replacementPreservesLCSSAForm(PN, V))
4868       return getSCEV(V);
4869 
4870   // If it's not a loop phi, we can't handle it yet.
4871   return getUnknown(PN);
4872 }
4873 
4874 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4875                                                       Value *Cond,
4876                                                       Value *TrueVal,
4877                                                       Value *FalseVal) {
4878   // Handle "constant" branch or select. This can occur for instance when a
4879   // loop pass transforms an inner loop and moves on to process the outer loop.
4880   if (auto *CI = dyn_cast<ConstantInt>(Cond))
4881     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4882 
4883   // Try to match some simple smax or umax patterns.
4884   auto *ICI = dyn_cast<ICmpInst>(Cond);
4885   if (!ICI)
4886     return getUnknown(I);
4887 
4888   Value *LHS = ICI->getOperand(0);
4889   Value *RHS = ICI->getOperand(1);
4890 
4891   switch (ICI->getPredicate()) {
4892   case ICmpInst::ICMP_SLT:
4893   case ICmpInst::ICMP_SLE:
4894     std::swap(LHS, RHS);
4895     LLVM_FALLTHROUGH;
4896   case ICmpInst::ICMP_SGT:
4897   case ICmpInst::ICMP_SGE:
4898     // a >s b ? a+x : b+x  ->  smax(a, b)+x
4899     // a >s b ? b+x : a+x  ->  smin(a, b)+x
4900     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4901       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4902       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4903       const SCEV *LA = getSCEV(TrueVal);
4904       const SCEV *RA = getSCEV(FalseVal);
4905       const SCEV *LDiff = getMinusSCEV(LA, LS);
4906       const SCEV *RDiff = getMinusSCEV(RA, RS);
4907       if (LDiff == RDiff)
4908         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4909       LDiff = getMinusSCEV(LA, RS);
4910       RDiff = getMinusSCEV(RA, LS);
4911       if (LDiff == RDiff)
4912         return getAddExpr(getSMinExpr(LS, RS), LDiff);
4913     }
4914     break;
4915   case ICmpInst::ICMP_ULT:
4916   case ICmpInst::ICMP_ULE:
4917     std::swap(LHS, RHS);
4918     LLVM_FALLTHROUGH;
4919   case ICmpInst::ICMP_UGT:
4920   case ICmpInst::ICMP_UGE:
4921     // a >u b ? a+x : b+x  ->  umax(a, b)+x
4922     // a >u b ? b+x : a+x  ->  umin(a, b)+x
4923     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4924       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4925       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4926       const SCEV *LA = getSCEV(TrueVal);
4927       const SCEV *RA = getSCEV(FalseVal);
4928       const SCEV *LDiff = getMinusSCEV(LA, LS);
4929       const SCEV *RDiff = getMinusSCEV(RA, RS);
4930       if (LDiff == RDiff)
4931         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4932       LDiff = getMinusSCEV(LA, RS);
4933       RDiff = getMinusSCEV(RA, LS);
4934       if (LDiff == RDiff)
4935         return getAddExpr(getUMinExpr(LS, RS), LDiff);
4936     }
4937     break;
4938   case ICmpInst::ICMP_NE:
4939     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
4940     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4941         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4942       const SCEV *One = getOne(I->getType());
4943       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4944       const SCEV *LA = getSCEV(TrueVal);
4945       const SCEV *RA = getSCEV(FalseVal);
4946       const SCEV *LDiff = getMinusSCEV(LA, LS);
4947       const SCEV *RDiff = getMinusSCEV(RA, One);
4948       if (LDiff == RDiff)
4949         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4950     }
4951     break;
4952   case ICmpInst::ICMP_EQ:
4953     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
4954     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4955         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4956       const SCEV *One = getOne(I->getType());
4957       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4958       const SCEV *LA = getSCEV(TrueVal);
4959       const SCEV *RA = getSCEV(FalseVal);
4960       const SCEV *LDiff = getMinusSCEV(LA, One);
4961       const SCEV *RDiff = getMinusSCEV(RA, LS);
4962       if (LDiff == RDiff)
4963         return getAddExpr(getUMaxExpr(One, LS), LDiff);
4964     }
4965     break;
4966   default:
4967     break;
4968   }
4969 
4970   return getUnknown(I);
4971 }
4972 
4973 /// Expand GEP instructions into add and multiply operations. This allows them
4974 /// to be analyzed by regular SCEV code.
4975 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
4976   // Don't attempt to analyze GEPs over unsized objects.
4977   if (!GEP->getSourceElementType()->isSized())
4978     return getUnknown(GEP);
4979 
4980   SmallVector<const SCEV *, 4> IndexExprs;
4981   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4982     IndexExprs.push_back(getSCEV(*Index));
4983   return getGEPExpr(GEP, IndexExprs);
4984 }
4985 
4986 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
4987   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
4988     return C->getAPInt().countTrailingZeros();
4989 
4990   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
4991     return std::min(GetMinTrailingZeros(T->getOperand()),
4992                     (uint32_t)getTypeSizeInBits(T->getType()));
4993 
4994   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
4995     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4996     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
4997                ? getTypeSizeInBits(E->getType())
4998                : OpRes;
4999   }
5000 
5001   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5002     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5003     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5004                ? getTypeSizeInBits(E->getType())
5005                : OpRes;
5006   }
5007 
5008   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5009     // The result is the min of all operands results.
5010     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5011     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5012       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5013     return MinOpRes;
5014   }
5015 
5016   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5017     // The result is the sum of all operands results.
5018     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5019     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5020     for (unsigned i = 1, e = M->getNumOperands();
5021          SumOpRes != BitWidth && i != e; ++i)
5022       SumOpRes =
5023           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5024     return SumOpRes;
5025   }
5026 
5027   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5028     // The result is the min of all operands results.
5029     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5030     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5031       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5032     return MinOpRes;
5033   }
5034 
5035   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5036     // The result is the min of all operands results.
5037     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5038     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5039       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5040     return MinOpRes;
5041   }
5042 
5043   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5044     // The result is the min of all operands results.
5045     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5046     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5047       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5048     return MinOpRes;
5049   }
5050 
5051   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5052     // For a SCEVUnknown, ask ValueTracking.
5053     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5054     return Known.countMinTrailingZeros();
5055   }
5056 
5057   // SCEVUDivExpr
5058   return 0;
5059 }
5060 
5061 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5062   auto I = MinTrailingZerosCache.find(S);
5063   if (I != MinTrailingZerosCache.end())
5064     return I->second;
5065 
5066   uint32_t Result = GetMinTrailingZerosImpl(S);
5067   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5068   assert(InsertPair.second && "Should insert a new key");
5069   return InsertPair.first->second;
5070 }
5071 
5072 /// Helper method to assign a range to V from metadata present in the IR.
5073 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5074   if (Instruction *I = dyn_cast<Instruction>(V))
5075     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5076       return getConstantRangeFromMetadata(*MD);
5077 
5078   return None;
5079 }
5080 
5081 /// Determine the range for a particular SCEV.  If SignHint is
5082 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5083 /// with a "cleaner" unsigned (resp. signed) representation.
5084 const ConstantRange &
5085 ScalarEvolution::getRangeRef(const SCEV *S,
5086                              ScalarEvolution::RangeSignHint SignHint) {
5087   DenseMap<const SCEV *, ConstantRange> &Cache =
5088       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5089                                                        : SignedRanges;
5090 
5091   // See if we've computed this range already.
5092   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5093   if (I != Cache.end())
5094     return I->second;
5095 
5096   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5097     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5098 
5099   unsigned BitWidth = getTypeSizeInBits(S->getType());
5100   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5101 
5102   // If the value has known zeros, the maximum value will have those known zeros
5103   // as well.
5104   uint32_t TZ = GetMinTrailingZeros(S);
5105   if (TZ != 0) {
5106     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5107       ConservativeResult =
5108           ConstantRange(APInt::getMinValue(BitWidth),
5109                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5110     else
5111       ConservativeResult = ConstantRange(
5112           APInt::getSignedMinValue(BitWidth),
5113           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5114   }
5115 
5116   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5117     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5118     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5119       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5120     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5121   }
5122 
5123   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5124     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5125     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5126       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5127     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5128   }
5129 
5130   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5131     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5132     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5133       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5134     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5135   }
5136 
5137   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5138     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5139     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5140       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5141     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5142   }
5143 
5144   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5145     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5146     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5147     return setRange(UDiv, SignHint,
5148                     ConservativeResult.intersectWith(X.udiv(Y)));
5149   }
5150 
5151   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5152     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5153     return setRange(ZExt, SignHint,
5154                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5155   }
5156 
5157   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5158     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5159     return setRange(SExt, SignHint,
5160                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5161   }
5162 
5163   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5164     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5165     return setRange(Trunc, SignHint,
5166                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5167   }
5168 
5169   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5170     // If there's no unsigned wrap, the value will never be less than its
5171     // initial value.
5172     if (AddRec->hasNoUnsignedWrap())
5173       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5174         if (!C->getValue()->isZero())
5175           ConservativeResult = ConservativeResult.intersectWith(
5176               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5177 
5178     // If there's no signed wrap, and all the operands have the same sign or
5179     // zero, the value won't ever change sign.
5180     if (AddRec->hasNoSignedWrap()) {
5181       bool AllNonNeg = true;
5182       bool AllNonPos = true;
5183       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5184         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5185         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5186       }
5187       if (AllNonNeg)
5188         ConservativeResult = ConservativeResult.intersectWith(
5189           ConstantRange(APInt(BitWidth, 0),
5190                         APInt::getSignedMinValue(BitWidth)));
5191       else if (AllNonPos)
5192         ConservativeResult = ConservativeResult.intersectWith(
5193           ConstantRange(APInt::getSignedMinValue(BitWidth),
5194                         APInt(BitWidth, 1)));
5195     }
5196 
5197     // TODO: non-affine addrec
5198     if (AddRec->isAffine()) {
5199       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5200       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5201           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5202         auto RangeFromAffine = getRangeForAffineAR(
5203             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5204             BitWidth);
5205         if (!RangeFromAffine.isFullSet())
5206           ConservativeResult =
5207               ConservativeResult.intersectWith(RangeFromAffine);
5208 
5209         auto RangeFromFactoring = getRangeViaFactoring(
5210             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5211             BitWidth);
5212         if (!RangeFromFactoring.isFullSet())
5213           ConservativeResult =
5214               ConservativeResult.intersectWith(RangeFromFactoring);
5215       }
5216     }
5217 
5218     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5219   }
5220 
5221   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5222     // Check if the IR explicitly contains !range metadata.
5223     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5224     if (MDRange.hasValue())
5225       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5226 
5227     // Split here to avoid paying the compile-time cost of calling both
5228     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5229     // if needed.
5230     const DataLayout &DL = getDataLayout();
5231     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5232       // For a SCEVUnknown, ask ValueTracking.
5233       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5234       if (Known.One != ~Known.Zero + 1)
5235         ConservativeResult =
5236             ConservativeResult.intersectWith(ConstantRange(Known.One,
5237                                                            ~Known.Zero + 1));
5238     } else {
5239       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5240              "generalize as needed!");
5241       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5242       if (NS > 1)
5243         ConservativeResult = ConservativeResult.intersectWith(
5244             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5245                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5246     }
5247 
5248     return setRange(U, SignHint, std::move(ConservativeResult));
5249   }
5250 
5251   return setRange(S, SignHint, std::move(ConservativeResult));
5252 }
5253 
5254 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5255 // values that the expression can take. Initially, the expression has a value
5256 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5257 // argument defines if we treat Step as signed or unsigned.
5258 static ConstantRange getRangeForAffineARHelper(APInt Step,
5259                                                const ConstantRange &StartRange,
5260                                                const APInt &MaxBECount,
5261                                                unsigned BitWidth, bool Signed) {
5262   // If either Step or MaxBECount is 0, then the expression won't change, and we
5263   // just need to return the initial range.
5264   if (Step == 0 || MaxBECount == 0)
5265     return StartRange;
5266 
5267   // If we don't know anything about the initial value (i.e. StartRange is
5268   // FullRange), then we don't know anything about the final range either.
5269   // Return FullRange.
5270   if (StartRange.isFullSet())
5271     return ConstantRange(BitWidth, /* isFullSet = */ true);
5272 
5273   // If Step is signed and negative, then we use its absolute value, but we also
5274   // note that we're moving in the opposite direction.
5275   bool Descending = Signed && Step.isNegative();
5276 
5277   if (Signed)
5278     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5279     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5280     // This equations hold true due to the well-defined wrap-around behavior of
5281     // APInt.
5282     Step = Step.abs();
5283 
5284   // Check if Offset is more than full span of BitWidth. If it is, the
5285   // expression is guaranteed to overflow.
5286   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5287     return ConstantRange(BitWidth, /* isFullSet = */ true);
5288 
5289   // Offset is by how much the expression can change. Checks above guarantee no
5290   // overflow here.
5291   APInt Offset = Step * MaxBECount;
5292 
5293   // Minimum value of the final range will match the minimal value of StartRange
5294   // if the expression is increasing and will be decreased by Offset otherwise.
5295   // Maximum value of the final range will match the maximal value of StartRange
5296   // if the expression is decreasing and will be increased by Offset otherwise.
5297   APInt StartLower = StartRange.getLower();
5298   APInt StartUpper = StartRange.getUpper() - 1;
5299   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5300                                    : (StartUpper + std::move(Offset));
5301 
5302   // It's possible that the new minimum/maximum value will fall into the initial
5303   // range (due to wrap around). This means that the expression can take any
5304   // value in this bitwidth, and we have to return full range.
5305   if (StartRange.contains(MovedBoundary))
5306     return ConstantRange(BitWidth, /* isFullSet = */ true);
5307 
5308   APInt NewLower =
5309       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5310   APInt NewUpper =
5311       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5312   NewUpper += 1;
5313 
5314   // If we end up with full range, return a proper full range.
5315   if (NewLower == NewUpper)
5316     return ConstantRange(BitWidth, /* isFullSet = */ true);
5317 
5318   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5319   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5320 }
5321 
5322 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5323                                                    const SCEV *Step,
5324                                                    const SCEV *MaxBECount,
5325                                                    unsigned BitWidth) {
5326   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5327          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5328          "Precondition!");
5329 
5330   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5331   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5332 
5333   // First, consider step signed.
5334   ConstantRange StartSRange = getSignedRange(Start);
5335   ConstantRange StepSRange = getSignedRange(Step);
5336 
5337   // If Step can be both positive and negative, we need to find ranges for the
5338   // maximum absolute step values in both directions and union them.
5339   ConstantRange SR =
5340       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5341                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5342   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5343                                               StartSRange, MaxBECountValue,
5344                                               BitWidth, /* Signed = */ true));
5345 
5346   // Next, consider step unsigned.
5347   ConstantRange UR = getRangeForAffineARHelper(
5348       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5349       MaxBECountValue, BitWidth, /* Signed = */ false);
5350 
5351   // Finally, intersect signed and unsigned ranges.
5352   return SR.intersectWith(UR);
5353 }
5354 
5355 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5356                                                     const SCEV *Step,
5357                                                     const SCEV *MaxBECount,
5358                                                     unsigned BitWidth) {
5359   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5360   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5361 
5362   struct SelectPattern {
5363     Value *Condition = nullptr;
5364     APInt TrueValue;
5365     APInt FalseValue;
5366 
5367     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5368                            const SCEV *S) {
5369       Optional<unsigned> CastOp;
5370       APInt Offset(BitWidth, 0);
5371 
5372       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5373              "Should be!");
5374 
5375       // Peel off a constant offset:
5376       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5377         // In the future we could consider being smarter here and handle
5378         // {Start+Step,+,Step} too.
5379         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5380           return;
5381 
5382         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5383         S = SA->getOperand(1);
5384       }
5385 
5386       // Peel off a cast operation
5387       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5388         CastOp = SCast->getSCEVType();
5389         S = SCast->getOperand();
5390       }
5391 
5392       using namespace llvm::PatternMatch;
5393 
5394       auto *SU = dyn_cast<SCEVUnknown>(S);
5395       const APInt *TrueVal, *FalseVal;
5396       if (!SU ||
5397           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5398                                           m_APInt(FalseVal)))) {
5399         Condition = nullptr;
5400         return;
5401       }
5402 
5403       TrueValue = *TrueVal;
5404       FalseValue = *FalseVal;
5405 
5406       // Re-apply the cast we peeled off earlier
5407       if (CastOp.hasValue())
5408         switch (*CastOp) {
5409         default:
5410           llvm_unreachable("Unknown SCEV cast type!");
5411 
5412         case scTruncate:
5413           TrueValue = TrueValue.trunc(BitWidth);
5414           FalseValue = FalseValue.trunc(BitWidth);
5415           break;
5416         case scZeroExtend:
5417           TrueValue = TrueValue.zext(BitWidth);
5418           FalseValue = FalseValue.zext(BitWidth);
5419           break;
5420         case scSignExtend:
5421           TrueValue = TrueValue.sext(BitWidth);
5422           FalseValue = FalseValue.sext(BitWidth);
5423           break;
5424         }
5425 
5426       // Re-apply the constant offset we peeled off earlier
5427       TrueValue += Offset;
5428       FalseValue += Offset;
5429     }
5430 
5431     bool isRecognized() { return Condition != nullptr; }
5432   };
5433 
5434   SelectPattern StartPattern(*this, BitWidth, Start);
5435   if (!StartPattern.isRecognized())
5436     return ConstantRange(BitWidth, /* isFullSet = */ true);
5437 
5438   SelectPattern StepPattern(*this, BitWidth, Step);
5439   if (!StepPattern.isRecognized())
5440     return ConstantRange(BitWidth, /* isFullSet = */ true);
5441 
5442   if (StartPattern.Condition != StepPattern.Condition) {
5443     // We don't handle this case today; but we could, by considering four
5444     // possibilities below instead of two. I'm not sure if there are cases where
5445     // that will help over what getRange already does, though.
5446     return ConstantRange(BitWidth, /* isFullSet = */ true);
5447   }
5448 
5449   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5450   // construct arbitrary general SCEV expressions here.  This function is called
5451   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5452   // say) can end up caching a suboptimal value.
5453 
5454   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5455   // C2352 and C2512 (otherwise it isn't needed).
5456 
5457   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5458   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5459   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5460   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5461 
5462   ConstantRange TrueRange =
5463       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5464   ConstantRange FalseRange =
5465       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5466 
5467   return TrueRange.unionWith(FalseRange);
5468 }
5469 
5470 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5471   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5472   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5473 
5474   // Return early if there are no flags to propagate to the SCEV.
5475   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5476   if (BinOp->hasNoUnsignedWrap())
5477     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5478   if (BinOp->hasNoSignedWrap())
5479     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5480   if (Flags == SCEV::FlagAnyWrap)
5481     return SCEV::FlagAnyWrap;
5482 
5483   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5484 }
5485 
5486 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5487   // Here we check that I is in the header of the innermost loop containing I,
5488   // since we only deal with instructions in the loop header. The actual loop we
5489   // need to check later will come from an add recurrence, but getting that
5490   // requires computing the SCEV of the operands, which can be expensive. This
5491   // check we can do cheaply to rule out some cases early.
5492   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5493   if (InnermostContainingLoop == nullptr ||
5494       InnermostContainingLoop->getHeader() != I->getParent())
5495     return false;
5496 
5497   // Only proceed if we can prove that I does not yield poison.
5498   if (!programUndefinedIfFullPoison(I))
5499     return false;
5500 
5501   // At this point we know that if I is executed, then it does not wrap
5502   // according to at least one of NSW or NUW. If I is not executed, then we do
5503   // not know if the calculation that I represents would wrap. Multiple
5504   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5505   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5506   // derived from other instructions that map to the same SCEV. We cannot make
5507   // that guarantee for cases where I is not executed. So we need to find the
5508   // loop that I is considered in relation to and prove that I is executed for
5509   // every iteration of that loop. That implies that the value that I
5510   // calculates does not wrap anywhere in the loop, so then we can apply the
5511   // flags to the SCEV.
5512   //
5513   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5514   // from different loops, so that we know which loop to prove that I is
5515   // executed in.
5516   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5517     // I could be an extractvalue from a call to an overflow intrinsic.
5518     // TODO: We can do better here in some cases.
5519     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5520       return false;
5521     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5522     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5523       bool AllOtherOpsLoopInvariant = true;
5524       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5525            ++OtherOpIndex) {
5526         if (OtherOpIndex != OpIndex) {
5527           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5528           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5529             AllOtherOpsLoopInvariant = false;
5530             break;
5531           }
5532         }
5533       }
5534       if (AllOtherOpsLoopInvariant &&
5535           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5536         return true;
5537     }
5538   }
5539   return false;
5540 }
5541 
5542 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5543   // If we know that \c I can never be poison period, then that's enough.
5544   if (isSCEVExprNeverPoison(I))
5545     return true;
5546 
5547   // For an add recurrence specifically, we assume that infinite loops without
5548   // side effects are undefined behavior, and then reason as follows:
5549   //
5550   // If the add recurrence is poison in any iteration, it is poison on all
5551   // future iterations (since incrementing poison yields poison). If the result
5552   // of the add recurrence is fed into the loop latch condition and the loop
5553   // does not contain any throws or exiting blocks other than the latch, we now
5554   // have the ability to "choose" whether the backedge is taken or not (by
5555   // choosing a sufficiently evil value for the poison feeding into the branch)
5556   // for every iteration including and after the one in which \p I first became
5557   // poison.  There are two possibilities (let's call the iteration in which \p
5558   // I first became poison as K):
5559   //
5560   //  1. In the set of iterations including and after K, the loop body executes
5561   //     no side effects.  In this case executing the backege an infinte number
5562   //     of times will yield undefined behavior.
5563   //
5564   //  2. In the set of iterations including and after K, the loop body executes
5565   //     at least one side effect.  In this case, that specific instance of side
5566   //     effect is control dependent on poison, which also yields undefined
5567   //     behavior.
5568 
5569   auto *ExitingBB = L->getExitingBlock();
5570   auto *LatchBB = L->getLoopLatch();
5571   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5572     return false;
5573 
5574   SmallPtrSet<const Instruction *, 16> Pushed;
5575   SmallVector<const Instruction *, 8> PoisonStack;
5576 
5577   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5578   // things that are known to be fully poison under that assumption go on the
5579   // PoisonStack.
5580   Pushed.insert(I);
5581   PoisonStack.push_back(I);
5582 
5583   bool LatchControlDependentOnPoison = false;
5584   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5585     const Instruction *Poison = PoisonStack.pop_back_val();
5586 
5587     for (auto *PoisonUser : Poison->users()) {
5588       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5589         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5590           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5591       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5592         assert(BI->isConditional() && "Only possibility!");
5593         if (BI->getParent() == LatchBB) {
5594           LatchControlDependentOnPoison = true;
5595           break;
5596         }
5597       }
5598     }
5599   }
5600 
5601   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5602 }
5603 
5604 ScalarEvolution::LoopProperties
5605 ScalarEvolution::getLoopProperties(const Loop *L) {
5606   typedef ScalarEvolution::LoopProperties LoopProperties;
5607 
5608   auto Itr = LoopPropertiesCache.find(L);
5609   if (Itr == LoopPropertiesCache.end()) {
5610     auto HasSideEffects = [](Instruction *I) {
5611       if (auto *SI = dyn_cast<StoreInst>(I))
5612         return !SI->isSimple();
5613 
5614       return I->mayHaveSideEffects();
5615     };
5616 
5617     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5618                          /*HasNoSideEffects*/ true};
5619 
5620     for (auto *BB : L->getBlocks())
5621       for (auto &I : *BB) {
5622         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5623           LP.HasNoAbnormalExits = false;
5624         if (HasSideEffects(&I))
5625           LP.HasNoSideEffects = false;
5626         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5627           break; // We're already as pessimistic as we can get.
5628       }
5629 
5630     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5631     assert(InsertPair.second && "We just checked!");
5632     Itr = InsertPair.first;
5633   }
5634 
5635   return Itr->second;
5636 }
5637 
5638 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5639   if (!isSCEVable(V->getType()))
5640     return getUnknown(V);
5641 
5642   if (Instruction *I = dyn_cast<Instruction>(V)) {
5643     // Don't attempt to analyze instructions in blocks that aren't
5644     // reachable. Such instructions don't matter, and they aren't required
5645     // to obey basic rules for definitions dominating uses which this
5646     // analysis depends on.
5647     if (!DT.isReachableFromEntry(I->getParent()))
5648       return getUnknown(V);
5649   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5650     return getConstant(CI);
5651   else if (isa<ConstantPointerNull>(V))
5652     return getZero(V->getType());
5653   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5654     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5655   else if (!isa<ConstantExpr>(V))
5656     return getUnknown(V);
5657 
5658   Operator *U = cast<Operator>(V);
5659   if (auto BO = MatchBinaryOp(U, DT)) {
5660     switch (BO->Opcode) {
5661     case Instruction::Add: {
5662       // The simple thing to do would be to just call getSCEV on both operands
5663       // and call getAddExpr with the result. However if we're looking at a
5664       // bunch of things all added together, this can be quite inefficient,
5665       // because it leads to N-1 getAddExpr calls for N ultimate operands.
5666       // Instead, gather up all the operands and make a single getAddExpr call.
5667       // LLVM IR canonical form means we need only traverse the left operands.
5668       SmallVector<const SCEV *, 4> AddOps;
5669       do {
5670         if (BO->Op) {
5671           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5672             AddOps.push_back(OpSCEV);
5673             break;
5674           }
5675 
5676           // If a NUW or NSW flag can be applied to the SCEV for this
5677           // addition, then compute the SCEV for this addition by itself
5678           // with a separate call to getAddExpr. We need to do that
5679           // instead of pushing the operands of the addition onto AddOps,
5680           // since the flags are only known to apply to this particular
5681           // addition - they may not apply to other additions that can be
5682           // formed with operands from AddOps.
5683           const SCEV *RHS = getSCEV(BO->RHS);
5684           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5685           if (Flags != SCEV::FlagAnyWrap) {
5686             const SCEV *LHS = getSCEV(BO->LHS);
5687             if (BO->Opcode == Instruction::Sub)
5688               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
5689             else
5690               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
5691             break;
5692           }
5693         }
5694 
5695         if (BO->Opcode == Instruction::Sub)
5696           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
5697         else
5698           AddOps.push_back(getSCEV(BO->RHS));
5699 
5700         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5701         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
5702                        NewBO->Opcode != Instruction::Sub)) {
5703           AddOps.push_back(getSCEV(BO->LHS));
5704           break;
5705         }
5706         BO = NewBO;
5707       } while (true);
5708 
5709       return getAddExpr(AddOps);
5710     }
5711 
5712     case Instruction::Mul: {
5713       SmallVector<const SCEV *, 4> MulOps;
5714       do {
5715         if (BO->Op) {
5716           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
5717             MulOps.push_back(OpSCEV);
5718             break;
5719           }
5720 
5721           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
5722           if (Flags != SCEV::FlagAnyWrap) {
5723             MulOps.push_back(
5724                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
5725             break;
5726           }
5727         }
5728 
5729         MulOps.push_back(getSCEV(BO->RHS));
5730         auto NewBO = MatchBinaryOp(BO->LHS, DT);
5731         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
5732           MulOps.push_back(getSCEV(BO->LHS));
5733           break;
5734         }
5735         BO = NewBO;
5736       } while (true);
5737 
5738       return getMulExpr(MulOps);
5739     }
5740     case Instruction::UDiv:
5741       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
5742     case Instruction::Sub: {
5743       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5744       if (BO->Op)
5745         Flags = getNoWrapFlagsFromUB(BO->Op);
5746       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
5747     }
5748     case Instruction::And:
5749       // For an expression like x&255 that merely masks off the high bits,
5750       // use zext(trunc(x)) as the SCEV expression.
5751       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5752         if (CI->isZero())
5753           return getSCEV(BO->RHS);
5754         if (CI->isMinusOne())
5755           return getSCEV(BO->LHS);
5756         const APInt &A = CI->getValue();
5757 
5758         // Instcombine's ShrinkDemandedConstant may strip bits out of
5759         // constants, obscuring what would otherwise be a low-bits mask.
5760         // Use computeKnownBits to compute what ShrinkDemandedConstant
5761         // knew about to reconstruct a low-bits mask value.
5762         unsigned LZ = A.countLeadingZeros();
5763         unsigned TZ = A.countTrailingZeros();
5764         unsigned BitWidth = A.getBitWidth();
5765         KnownBits Known(BitWidth);
5766         computeKnownBits(BO->LHS, Known, getDataLayout(),
5767                          0, &AC, nullptr, &DT);
5768 
5769         APInt EffectiveMask =
5770             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
5771         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
5772           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
5773           const SCEV *LHS = getSCEV(BO->LHS);
5774           const SCEV *ShiftedLHS = nullptr;
5775           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
5776             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
5777               // For an expression like (x * 8) & 8, simplify the multiply.
5778               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
5779               unsigned GCD = std::min(MulZeros, TZ);
5780               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
5781               SmallVector<const SCEV*, 4> MulOps;
5782               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
5783               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
5784               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
5785               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
5786             }
5787           }
5788           if (!ShiftedLHS)
5789             ShiftedLHS = getUDivExpr(LHS, MulCount);
5790           return getMulExpr(
5791               getZeroExtendExpr(
5792                   getTruncateExpr(ShiftedLHS,
5793                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5794                   BO->LHS->getType()),
5795               MulCount);
5796         }
5797       }
5798       break;
5799 
5800     case Instruction::Or:
5801       // If the RHS of the Or is a constant, we may have something like:
5802       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
5803       // optimizations will transparently handle this case.
5804       //
5805       // In order for this transformation to be safe, the LHS must be of the
5806       // form X*(2^n) and the Or constant must be less than 2^n.
5807       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5808         const SCEV *LHS = getSCEV(BO->LHS);
5809         const APInt &CIVal = CI->getValue();
5810         if (GetMinTrailingZeros(LHS) >=
5811             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5812           // Build a plain add SCEV.
5813           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5814           // If the LHS of the add was an addrec and it has no-wrap flags,
5815           // transfer the no-wrap flags, since an or won't introduce a wrap.
5816           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5817             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5818             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5819                 OldAR->getNoWrapFlags());
5820           }
5821           return S;
5822         }
5823       }
5824       break;
5825 
5826     case Instruction::Xor:
5827       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5828         // If the RHS of xor is -1, then this is a not operation.
5829         if (CI->isMinusOne())
5830           return getNotSCEV(getSCEV(BO->LHS));
5831 
5832         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5833         // This is a variant of the check for xor with -1, and it handles
5834         // the case where instcombine has trimmed non-demanded bits out
5835         // of an xor with -1.
5836         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5837           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5838             if (LBO->getOpcode() == Instruction::And &&
5839                 LCI->getValue() == CI->getValue())
5840               if (const SCEVZeroExtendExpr *Z =
5841                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5842                 Type *UTy = BO->LHS->getType();
5843                 const SCEV *Z0 = Z->getOperand();
5844                 Type *Z0Ty = Z0->getType();
5845                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
5846 
5847                 // If C is a low-bits mask, the zero extend is serving to
5848                 // mask off the high bits. Complement the operand and
5849                 // re-apply the zext.
5850                 if (CI->getValue().isMask(Z0TySize))
5851                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5852 
5853                 // If C is a single bit, it may be in the sign-bit position
5854                 // before the zero-extend. In this case, represent the xor
5855                 // using an add, which is equivalent, and re-apply the zext.
5856                 APInt Trunc = CI->getValue().trunc(Z0TySize);
5857                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5858                     Trunc.isSignMask())
5859                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5860                                            UTy);
5861               }
5862       }
5863       break;
5864 
5865   case Instruction::Shl:
5866     // Turn shift left of a constant amount into a multiply.
5867     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5868       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
5869 
5870       // If the shift count is not less than the bitwidth, the result of
5871       // the shift is undefined. Don't try to analyze it, because the
5872       // resolution chosen here may differ from the resolution chosen in
5873       // other parts of the compiler.
5874       if (SA->getValue().uge(BitWidth))
5875         break;
5876 
5877       // It is currently not resolved how to interpret NSW for left
5878       // shift by BitWidth - 1, so we avoid applying flags in that
5879       // case. Remove this check (or this comment) once the situation
5880       // is resolved. See
5881       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5882       // and http://reviews.llvm.org/D8890 .
5883       auto Flags = SCEV::FlagAnyWrap;
5884       if (BO->Op && SA->getValue().ult(BitWidth - 1))
5885         Flags = getNoWrapFlagsFromUB(BO->Op);
5886 
5887       Constant *X = ConstantInt::get(getContext(),
5888         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5889       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
5890     }
5891     break;
5892 
5893     case Instruction::AShr:
5894       // AShr X, C, where C is a constant.
5895       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
5896       if (!CI)
5897         break;
5898 
5899       Type *OuterTy = BO->LHS->getType();
5900       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
5901       // If the shift count is not less than the bitwidth, the result of
5902       // the shift is undefined. Don't try to analyze it, because the
5903       // resolution chosen here may differ from the resolution chosen in
5904       // other parts of the compiler.
5905       if (CI->getValue().uge(BitWidth))
5906         break;
5907 
5908       if (CI->isZero())
5909         return getSCEV(BO->LHS); // shift by zero --> noop
5910 
5911       uint64_t AShrAmt = CI->getZExtValue();
5912       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
5913 
5914       Operator *L = dyn_cast<Operator>(BO->LHS);
5915       if (L && L->getOpcode() == Instruction::Shl) {
5916         // X = Shl A, n
5917         // Y = AShr X, m
5918         // Both n and m are constant.
5919 
5920         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
5921         if (L->getOperand(1) == BO->RHS)
5922           // For a two-shift sext-inreg, i.e. n = m,
5923           // use sext(trunc(x)) as the SCEV expression.
5924           return getSignExtendExpr(
5925               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
5926 
5927         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
5928         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
5929           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
5930           if (ShlAmt > AShrAmt) {
5931             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
5932             // expression. We already checked that ShlAmt < BitWidth, so
5933             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
5934             // ShlAmt - AShrAmt < Amt.
5935             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
5936                                             ShlAmt - AShrAmt);
5937             return getSignExtendExpr(
5938                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
5939                 getConstant(Mul)), OuterTy);
5940           }
5941         }
5942       }
5943       break;
5944     }
5945   }
5946 
5947   switch (U->getOpcode()) {
5948   case Instruction::Trunc:
5949     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
5950 
5951   case Instruction::ZExt:
5952     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5953 
5954   case Instruction::SExt:
5955     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
5956 
5957   case Instruction::BitCast:
5958     // BitCasts are no-op casts so we just eliminate the cast.
5959     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
5960       return getSCEV(U->getOperand(0));
5961     break;
5962 
5963   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5964   // lead to pointer expressions which cannot safely be expanded to GEPs,
5965   // because ScalarEvolution doesn't respect the GEP aliasing rules when
5966   // simplifying integer expressions.
5967 
5968   case Instruction::GetElementPtr:
5969     return createNodeForGEP(cast<GEPOperator>(U));
5970 
5971   case Instruction::PHI:
5972     return createNodeForPHI(cast<PHINode>(U));
5973 
5974   case Instruction::Select:
5975     // U can also be a select constant expr, which let fall through.  Since
5976     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5977     // constant expressions cannot have instructions as operands, we'd have
5978     // returned getUnknown for a select constant expressions anyway.
5979     if (isa<Instruction>(U))
5980       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5981                                       U->getOperand(1), U->getOperand(2));
5982     break;
5983 
5984   case Instruction::Call:
5985   case Instruction::Invoke:
5986     if (Value *RV = CallSite(U).getReturnedArgOperand())
5987       return getSCEV(RV);
5988     break;
5989   }
5990 
5991   return getUnknown(V);
5992 }
5993 
5994 
5995 
5996 //===----------------------------------------------------------------------===//
5997 //                   Iteration Count Computation Code
5998 //
5999 
6000 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6001   if (!ExitCount)
6002     return 0;
6003 
6004   ConstantInt *ExitConst = ExitCount->getValue();
6005 
6006   // Guard against huge trip counts.
6007   if (ExitConst->getValue().getActiveBits() > 32)
6008     return 0;
6009 
6010   // In case of integer overflow, this returns 0, which is correct.
6011   return ((unsigned)ExitConst->getZExtValue()) + 1;
6012 }
6013 
6014 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6015   if (BasicBlock *ExitingBB = L->getExitingBlock())
6016     return getSmallConstantTripCount(L, ExitingBB);
6017 
6018   // No trip count information for multiple exits.
6019   return 0;
6020 }
6021 
6022 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6023                                                     BasicBlock *ExitingBlock) {
6024   assert(ExitingBlock && "Must pass a non-null exiting block!");
6025   assert(L->isLoopExiting(ExitingBlock) &&
6026          "Exiting block must actually branch out of the loop!");
6027   const SCEVConstant *ExitCount =
6028       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6029   return getConstantTripCount(ExitCount);
6030 }
6031 
6032 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6033   const auto *MaxExitCount =
6034       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6035   return getConstantTripCount(MaxExitCount);
6036 }
6037 
6038 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6039   if (BasicBlock *ExitingBB = L->getExitingBlock())
6040     return getSmallConstantTripMultiple(L, ExitingBB);
6041 
6042   // No trip multiple information for multiple exits.
6043   return 0;
6044 }
6045 
6046 /// Returns the largest constant divisor of the trip count of this loop as a
6047 /// normal unsigned value, if possible. This means that the actual trip count is
6048 /// always a multiple of the returned value (don't forget the trip count could
6049 /// very well be zero as well!).
6050 ///
6051 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6052 /// multiple of a constant (which is also the case if the trip count is simply
6053 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6054 /// if the trip count is very large (>= 2^32).
6055 ///
6056 /// As explained in the comments for getSmallConstantTripCount, this assumes
6057 /// that control exits the loop via ExitingBlock.
6058 unsigned
6059 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6060                                               BasicBlock *ExitingBlock) {
6061   assert(ExitingBlock && "Must pass a non-null exiting block!");
6062   assert(L->isLoopExiting(ExitingBlock) &&
6063          "Exiting block must actually branch out of the loop!");
6064   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6065   if (ExitCount == getCouldNotCompute())
6066     return 1;
6067 
6068   // Get the trip count from the BE count by adding 1.
6069   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6070 
6071   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6072   if (!TC)
6073     // Attempt to factor more general cases. Returns the greatest power of
6074     // two divisor. If overflow happens, the trip count expression is still
6075     // divisible by the greatest power of 2 divisor returned.
6076     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6077 
6078   ConstantInt *Result = TC->getValue();
6079 
6080   // Guard against huge trip counts (this requires checking
6081   // for zero to handle the case where the trip count == -1 and the
6082   // addition wraps).
6083   if (!Result || Result->getValue().getActiveBits() > 32 ||
6084       Result->getValue().getActiveBits() == 0)
6085     return 1;
6086 
6087   return (unsigned)Result->getZExtValue();
6088 }
6089 
6090 /// Get the expression for the number of loop iterations for which this loop is
6091 /// guaranteed not to exit via ExitingBlock. Otherwise return
6092 /// SCEVCouldNotCompute.
6093 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6094                                           BasicBlock *ExitingBlock) {
6095   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6096 }
6097 
6098 const SCEV *
6099 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6100                                                  SCEVUnionPredicate &Preds) {
6101   return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
6102 }
6103 
6104 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6105   return getBackedgeTakenInfo(L).getExact(this);
6106 }
6107 
6108 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6109 /// known never to be less than the actual backedge taken count.
6110 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6111   return getBackedgeTakenInfo(L).getMax(this);
6112 }
6113 
6114 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6115   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6116 }
6117 
6118 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6119 static void
6120 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6121   BasicBlock *Header = L->getHeader();
6122 
6123   // Push all Loop-header PHIs onto the Worklist stack.
6124   for (BasicBlock::iterator I = Header->begin();
6125        PHINode *PN = dyn_cast<PHINode>(I); ++I)
6126     Worklist.push_back(PN);
6127 }
6128 
6129 const ScalarEvolution::BackedgeTakenInfo &
6130 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6131   auto &BTI = getBackedgeTakenInfo(L);
6132   if (BTI.hasFullInfo())
6133     return BTI;
6134 
6135   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6136 
6137   if (!Pair.second)
6138     return Pair.first->second;
6139 
6140   BackedgeTakenInfo Result =
6141       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6142 
6143   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6144 }
6145 
6146 const ScalarEvolution::BackedgeTakenInfo &
6147 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6148   // Initially insert an invalid entry for this loop. If the insertion
6149   // succeeds, proceed to actually compute a backedge-taken count and
6150   // update the value. The temporary CouldNotCompute value tells SCEV
6151   // code elsewhere that it shouldn't attempt to request a new
6152   // backedge-taken count, which could result in infinite recursion.
6153   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6154       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6155   if (!Pair.second)
6156     return Pair.first->second;
6157 
6158   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6159   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6160   // must be cleared in this scope.
6161   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6162 
6163   if (Result.getExact(this) != getCouldNotCompute()) {
6164     assert(isLoopInvariant(Result.getExact(this), L) &&
6165            isLoopInvariant(Result.getMax(this), L) &&
6166            "Computed backedge-taken count isn't loop invariant for loop!");
6167     ++NumTripCountsComputed;
6168   }
6169   else if (Result.getMax(this) == getCouldNotCompute() &&
6170            isa<PHINode>(L->getHeader()->begin())) {
6171     // Only count loops that have phi nodes as not being computable.
6172     ++NumTripCountsNotComputed;
6173   }
6174 
6175   // Now that we know more about the trip count for this loop, forget any
6176   // existing SCEV values for PHI nodes in this loop since they are only
6177   // conservative estimates made without the benefit of trip count
6178   // information. This is similar to the code in forgetLoop, except that
6179   // it handles SCEVUnknown PHI nodes specially.
6180   if (Result.hasAnyInfo()) {
6181     SmallVector<Instruction *, 16> Worklist;
6182     PushLoopPHIs(L, Worklist);
6183 
6184     SmallPtrSet<Instruction *, 8> Visited;
6185     while (!Worklist.empty()) {
6186       Instruction *I = Worklist.pop_back_val();
6187       if (!Visited.insert(I).second)
6188         continue;
6189 
6190       ValueExprMapType::iterator It =
6191         ValueExprMap.find_as(static_cast<Value *>(I));
6192       if (It != ValueExprMap.end()) {
6193         const SCEV *Old = It->second;
6194 
6195         // SCEVUnknown for a PHI either means that it has an unrecognized
6196         // structure, or it's a PHI that's in the progress of being computed
6197         // by createNodeForPHI.  In the former case, additional loop trip
6198         // count information isn't going to change anything. In the later
6199         // case, createNodeForPHI will perform the necessary updates on its
6200         // own when it gets to that point.
6201         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6202           eraseValueFromMap(It->first);
6203           forgetMemoizedResults(Old);
6204         }
6205         if (PHINode *PN = dyn_cast<PHINode>(I))
6206           ConstantEvolutionLoopExitValue.erase(PN);
6207       }
6208 
6209       PushDefUseChildren(I, Worklist);
6210     }
6211   }
6212 
6213   // Re-lookup the insert position, since the call to
6214   // computeBackedgeTakenCount above could result in a
6215   // recusive call to getBackedgeTakenInfo (on a different
6216   // loop), which would invalidate the iterator computed
6217   // earlier.
6218   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6219 }
6220 
6221 void ScalarEvolution::forgetLoop(const Loop *L) {
6222   // Drop any stored trip count value.
6223   auto RemoveLoopFromBackedgeMap =
6224       [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
6225         auto BTCPos = Map.find(L);
6226         if (BTCPos != Map.end()) {
6227           BTCPos->second.clear();
6228           Map.erase(BTCPos);
6229         }
6230       };
6231 
6232   RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
6233   RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
6234 
6235   // Drop information about predicated SCEV rewrites for this loop.
6236   for (auto I = PredicatedSCEVRewrites.begin();
6237        I != PredicatedSCEVRewrites.end();) {
6238     std::pair<const SCEV *, const Loop *> Entry = I->first;
6239     if (Entry.second == L)
6240       PredicatedSCEVRewrites.erase(I++);
6241     else
6242       ++I;
6243   }
6244 
6245   // Drop information about expressions based on loop-header PHIs.
6246   SmallVector<Instruction *, 16> Worklist;
6247   PushLoopPHIs(L, Worklist);
6248 
6249   SmallPtrSet<Instruction *, 8> Visited;
6250   while (!Worklist.empty()) {
6251     Instruction *I = Worklist.pop_back_val();
6252     if (!Visited.insert(I).second)
6253       continue;
6254 
6255     ValueExprMapType::iterator It =
6256       ValueExprMap.find_as(static_cast<Value *>(I));
6257     if (It != ValueExprMap.end()) {
6258       eraseValueFromMap(It->first);
6259       forgetMemoizedResults(It->second);
6260       if (PHINode *PN = dyn_cast<PHINode>(I))
6261         ConstantEvolutionLoopExitValue.erase(PN);
6262     }
6263 
6264     PushDefUseChildren(I, Worklist);
6265   }
6266 
6267   // Forget all contained loops too, to avoid dangling entries in the
6268   // ValuesAtScopes map.
6269   for (Loop *I : *L)
6270     forgetLoop(I);
6271 
6272   LoopPropertiesCache.erase(L);
6273 }
6274 
6275 void ScalarEvolution::forgetValue(Value *V) {
6276   Instruction *I = dyn_cast<Instruction>(V);
6277   if (!I) return;
6278 
6279   // Drop information about expressions based on loop-header PHIs.
6280   SmallVector<Instruction *, 16> Worklist;
6281   Worklist.push_back(I);
6282 
6283   SmallPtrSet<Instruction *, 8> Visited;
6284   while (!Worklist.empty()) {
6285     I = Worklist.pop_back_val();
6286     if (!Visited.insert(I).second)
6287       continue;
6288 
6289     ValueExprMapType::iterator It =
6290       ValueExprMap.find_as(static_cast<Value *>(I));
6291     if (It != ValueExprMap.end()) {
6292       eraseValueFromMap(It->first);
6293       forgetMemoizedResults(It->second);
6294       if (PHINode *PN = dyn_cast<PHINode>(I))
6295         ConstantEvolutionLoopExitValue.erase(PN);
6296     }
6297 
6298     PushDefUseChildren(I, Worklist);
6299   }
6300 }
6301 
6302 /// Get the exact loop backedge taken count considering all loop exits. A
6303 /// computable result can only be returned for loops with a single exit.
6304 /// Returning the minimum taken count among all exits is incorrect because one
6305 /// of the loop's exit limit's may have been skipped. howFarToZero assumes that
6306 /// the limit of each loop test is never skipped. This is a valid assumption as
6307 /// long as the loop exits via that test. For precise results, it is the
6308 /// caller's responsibility to specify the relevant loop exit using
6309 /// getExact(ExitingBlock, SE).
6310 const SCEV *
6311 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE,
6312                                              SCEVUnionPredicate *Preds) const {
6313   // If any exits were not computable, the loop is not computable.
6314   if (!isComplete() || ExitNotTaken.empty())
6315     return SE->getCouldNotCompute();
6316 
6317   const SCEV *BECount = nullptr;
6318   for (auto &ENT : ExitNotTaken) {
6319     assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
6320 
6321     if (!BECount)
6322       BECount = ENT.ExactNotTaken;
6323     else if (BECount != ENT.ExactNotTaken)
6324       return SE->getCouldNotCompute();
6325     if (Preds && !ENT.hasAlwaysTruePredicate())
6326       Preds->add(ENT.Predicate.get());
6327 
6328     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6329            "Predicate should be always true!");
6330   }
6331 
6332   assert(BECount && "Invalid not taken count for loop exit");
6333   return BECount;
6334 }
6335 
6336 /// Get the exact not taken count for this loop exit.
6337 const SCEV *
6338 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6339                                              ScalarEvolution *SE) const {
6340   for (auto &ENT : ExitNotTaken)
6341     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6342       return ENT.ExactNotTaken;
6343 
6344   return SE->getCouldNotCompute();
6345 }
6346 
6347 /// getMax - Get the max backedge taken count for the loop.
6348 const SCEV *
6349 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6350   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6351     return !ENT.hasAlwaysTruePredicate();
6352   };
6353 
6354   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6355     return SE->getCouldNotCompute();
6356 
6357   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6358          "No point in having a non-constant max backedge taken count!");
6359   return getMax();
6360 }
6361 
6362 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6363   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6364     return !ENT.hasAlwaysTruePredicate();
6365   };
6366   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6367 }
6368 
6369 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6370                                                     ScalarEvolution *SE) const {
6371   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6372       SE->hasOperand(getMax(), S))
6373     return true;
6374 
6375   for (auto &ENT : ExitNotTaken)
6376     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6377         SE->hasOperand(ENT.ExactNotTaken, S))
6378       return true;
6379 
6380   return false;
6381 }
6382 
6383 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6384     : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {
6385   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6386           isa<SCEVConstant>(MaxNotTaken)) &&
6387          "No point in having a non-constant max backedge taken count!");
6388 }
6389 
6390 ScalarEvolution::ExitLimit::ExitLimit(
6391     const SCEV *E, const SCEV *M, bool MaxOrZero,
6392     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6393     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6394   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6395           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6396          "Exact is not allowed to be less precise than Max");
6397   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6398           isa<SCEVConstant>(MaxNotTaken)) &&
6399          "No point in having a non-constant max backedge taken count!");
6400   for (auto *PredSet : PredSetList)
6401     for (auto *P : *PredSet)
6402       addPredicate(P);
6403 }
6404 
6405 ScalarEvolution::ExitLimit::ExitLimit(
6406     const SCEV *E, const SCEV *M, bool MaxOrZero,
6407     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6408     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6409   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6410           isa<SCEVConstant>(MaxNotTaken)) &&
6411          "No point in having a non-constant max backedge taken count!");
6412 }
6413 
6414 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6415                                       bool MaxOrZero)
6416     : ExitLimit(E, M, MaxOrZero, None) {
6417   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6418           isa<SCEVConstant>(MaxNotTaken)) &&
6419          "No point in having a non-constant max backedge taken count!");
6420 }
6421 
6422 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6423 /// computable exit into a persistent ExitNotTakenInfo array.
6424 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6425     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6426         &&ExitCounts,
6427     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6428     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6429   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6430   ExitNotTaken.reserve(ExitCounts.size());
6431   std::transform(
6432       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6433       [&](const EdgeExitInfo &EEI) {
6434         BasicBlock *ExitBB = EEI.first;
6435         const ExitLimit &EL = EEI.second;
6436         if (EL.Predicates.empty())
6437           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6438 
6439         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6440         for (auto *Pred : EL.Predicates)
6441           Predicate->add(Pred);
6442 
6443         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6444       });
6445   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6446          "No point in having a non-constant max backedge taken count!");
6447 }
6448 
6449 /// Invalidate this result and free the ExitNotTakenInfo array.
6450 void ScalarEvolution::BackedgeTakenInfo::clear() {
6451   ExitNotTaken.clear();
6452 }
6453 
6454 /// Compute the number of times the backedge of the specified loop will execute.
6455 ScalarEvolution::BackedgeTakenInfo
6456 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6457                                            bool AllowPredicates) {
6458   SmallVector<BasicBlock *, 8> ExitingBlocks;
6459   L->getExitingBlocks(ExitingBlocks);
6460 
6461   typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo;
6462 
6463   SmallVector<EdgeExitInfo, 4> ExitCounts;
6464   bool CouldComputeBECount = true;
6465   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6466   const SCEV *MustExitMaxBECount = nullptr;
6467   const SCEV *MayExitMaxBECount = nullptr;
6468   bool MustExitMaxOrZero = false;
6469 
6470   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6471   // and compute maxBECount.
6472   // Do a union of all the predicates here.
6473   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6474     BasicBlock *ExitBB = ExitingBlocks[i];
6475     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6476 
6477     assert((AllowPredicates || EL.Predicates.empty()) &&
6478            "Predicated exit limit when predicates are not allowed!");
6479 
6480     // 1. For each exit that can be computed, add an entry to ExitCounts.
6481     // CouldComputeBECount is true only if all exits can be computed.
6482     if (EL.ExactNotTaken == getCouldNotCompute())
6483       // We couldn't compute an exact value for this exit, so
6484       // we won't be able to compute an exact value for the loop.
6485       CouldComputeBECount = false;
6486     else
6487       ExitCounts.emplace_back(ExitBB, EL);
6488 
6489     // 2. Derive the loop's MaxBECount from each exit's max number of
6490     // non-exiting iterations. Partition the loop exits into two kinds:
6491     // LoopMustExits and LoopMayExits.
6492     //
6493     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6494     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6495     // MaxBECount is the minimum EL.MaxNotTaken of computable
6496     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6497     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6498     // computable EL.MaxNotTaken.
6499     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6500         DT.dominates(ExitBB, Latch)) {
6501       if (!MustExitMaxBECount) {
6502         MustExitMaxBECount = EL.MaxNotTaken;
6503         MustExitMaxOrZero = EL.MaxOrZero;
6504       } else {
6505         MustExitMaxBECount =
6506             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6507       }
6508     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6509       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6510         MayExitMaxBECount = EL.MaxNotTaken;
6511       else {
6512         MayExitMaxBECount =
6513             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6514       }
6515     }
6516   }
6517   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6518     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6519   // The loop backedge will be taken the maximum or zero times if there's
6520   // a single exit that must be taken the maximum or zero times.
6521   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6522   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6523                            MaxBECount, MaxOrZero);
6524 }
6525 
6526 ScalarEvolution::ExitLimit
6527 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6528                                   bool AllowPredicates) {
6529 
6530   // Okay, we've chosen an exiting block.  See what condition causes us to exit
6531   // at this block and remember the exit block and whether all other targets
6532   // lead to the loop header.
6533   bool MustExecuteLoopHeader = true;
6534   BasicBlock *Exit = nullptr;
6535   for (auto *SBB : successors(ExitingBlock))
6536     if (!L->contains(SBB)) {
6537       if (Exit) // Multiple exit successors.
6538         return getCouldNotCompute();
6539       Exit = SBB;
6540     } else if (SBB != L->getHeader()) {
6541       MustExecuteLoopHeader = false;
6542     }
6543 
6544   // At this point, we know we have a conditional branch that determines whether
6545   // the loop is exited.  However, we don't know if the branch is executed each
6546   // time through the loop.  If not, then the execution count of the branch will
6547   // not be equal to the trip count of the loop.
6548   //
6549   // Currently we check for this by checking to see if the Exit branch goes to
6550   // the loop header.  If so, we know it will always execute the same number of
6551   // times as the loop.  We also handle the case where the exit block *is* the
6552   // loop header.  This is common for un-rotated loops.
6553   //
6554   // If both of those tests fail, walk up the unique predecessor chain to the
6555   // header, stopping if there is an edge that doesn't exit the loop. If the
6556   // header is reached, the execution count of the branch will be equal to the
6557   // trip count of the loop.
6558   //
6559   //  More extensive analysis could be done to handle more cases here.
6560   //
6561   if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
6562     // The simple checks failed, try climbing the unique predecessor chain
6563     // up to the header.
6564     bool Ok = false;
6565     for (BasicBlock *BB = ExitingBlock; BB; ) {
6566       BasicBlock *Pred = BB->getUniquePredecessor();
6567       if (!Pred)
6568         return getCouldNotCompute();
6569       TerminatorInst *PredTerm = Pred->getTerminator();
6570       for (const BasicBlock *PredSucc : PredTerm->successors()) {
6571         if (PredSucc == BB)
6572           continue;
6573         // If the predecessor has a successor that isn't BB and isn't
6574         // outside the loop, assume the worst.
6575         if (L->contains(PredSucc))
6576           return getCouldNotCompute();
6577       }
6578       if (Pred == L->getHeader()) {
6579         Ok = true;
6580         break;
6581       }
6582       BB = Pred;
6583     }
6584     if (!Ok)
6585       return getCouldNotCompute();
6586   }
6587 
6588   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6589   TerminatorInst *Term = ExitingBlock->getTerminator();
6590   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6591     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6592     // Proceed to the next level to examine the exit condition expression.
6593     return computeExitLimitFromCond(
6594         L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
6595         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6596   }
6597 
6598   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
6599     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6600                                                 /*ControlsExit=*/IsOnlyExit);
6601 
6602   return getCouldNotCompute();
6603 }
6604 
6605 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6606     const Loop *L, Value *ExitCond, BasicBlock *TBB, BasicBlock *FBB,
6607     bool ControlsExit, bool AllowPredicates) {
6608   ScalarEvolution::ExitLimitCacheTy Cache(L, TBB, FBB, AllowPredicates);
6609   return computeExitLimitFromCondCached(Cache, L, ExitCond, TBB, FBB,
6610                                         ControlsExit, AllowPredicates);
6611 }
6612 
6613 Optional<ScalarEvolution::ExitLimit>
6614 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6615                                       BasicBlock *TBB, BasicBlock *FBB,
6616                                       bool ControlsExit, bool AllowPredicates) {
6617   (void)this->L;
6618   (void)this->TBB;
6619   (void)this->FBB;
6620   (void)this->AllowPredicates;
6621 
6622   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6623          this->AllowPredicates == AllowPredicates &&
6624          "Variance in assumed invariant key components!");
6625   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6626   if (Itr == TripCountMap.end())
6627     return None;
6628   return Itr->second;
6629 }
6630 
6631 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6632                                              BasicBlock *TBB, BasicBlock *FBB,
6633                                              bool ControlsExit,
6634                                              bool AllowPredicates,
6635                                              const ExitLimit &EL) {
6636   assert(this->L == L && this->TBB == TBB && this->FBB == FBB &&
6637          this->AllowPredicates == AllowPredicates &&
6638          "Variance in assumed invariant key components!");
6639 
6640   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
6641   assert(InsertResult.second && "Expected successful insertion!");
6642   (void)InsertResult;
6643 }
6644 
6645 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
6646     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6647     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6648 
6649   if (auto MaybeEL =
6650           Cache.find(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates))
6651     return *MaybeEL;
6652 
6653   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, TBB, FBB,
6654                                               ControlsExit, AllowPredicates);
6655   Cache.insert(L, ExitCond, TBB, FBB, ControlsExit, AllowPredicates, EL);
6656   return EL;
6657 }
6658 
6659 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
6660     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, BasicBlock *TBB,
6661     BasicBlock *FBB, bool ControlsExit, bool AllowPredicates) {
6662   // Check if the controlling expression for this loop is an And or Or.
6663   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
6664     if (BO->getOpcode() == Instruction::And) {
6665       // Recurse on the operands of the and.
6666       bool EitherMayExit = L->contains(TBB);
6667       ExitLimit EL0 = computeExitLimitFromCondCached(
6668           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6669           AllowPredicates);
6670       ExitLimit EL1 = computeExitLimitFromCondCached(
6671           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6672           AllowPredicates);
6673       const SCEV *BECount = getCouldNotCompute();
6674       const SCEV *MaxBECount = getCouldNotCompute();
6675       if (EitherMayExit) {
6676         // Both conditions must be true for the loop to continue executing.
6677         // Choose the less conservative count.
6678         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6679             EL1.ExactNotTaken == getCouldNotCompute())
6680           BECount = getCouldNotCompute();
6681         else
6682           BECount =
6683               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6684         if (EL0.MaxNotTaken == getCouldNotCompute())
6685           MaxBECount = EL1.MaxNotTaken;
6686         else if (EL1.MaxNotTaken == getCouldNotCompute())
6687           MaxBECount = EL0.MaxNotTaken;
6688         else
6689           MaxBECount =
6690               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6691       } else {
6692         // Both conditions must be true at the same time for the loop to exit.
6693         // For now, be conservative.
6694         assert(L->contains(FBB) && "Loop block has no successor in loop!");
6695         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6696           MaxBECount = EL0.MaxNotTaken;
6697         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6698           BECount = EL0.ExactNotTaken;
6699       }
6700 
6701       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
6702       // to be more aggressive when computing BECount than when computing
6703       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
6704       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
6705       // to not.
6706       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
6707           !isa<SCEVCouldNotCompute>(BECount))
6708         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
6709 
6710       return ExitLimit(BECount, MaxBECount, false,
6711                        {&EL0.Predicates, &EL1.Predicates});
6712     }
6713     if (BO->getOpcode() == Instruction::Or) {
6714       // Recurse on the operands of the or.
6715       bool EitherMayExit = L->contains(FBB);
6716       ExitLimit EL0 = computeExitLimitFromCondCached(
6717           Cache, L, BO->getOperand(0), TBB, FBB, ControlsExit && !EitherMayExit,
6718           AllowPredicates);
6719       ExitLimit EL1 = computeExitLimitFromCondCached(
6720           Cache, L, BO->getOperand(1), TBB, FBB, ControlsExit && !EitherMayExit,
6721           AllowPredicates);
6722       const SCEV *BECount = getCouldNotCompute();
6723       const SCEV *MaxBECount = getCouldNotCompute();
6724       if (EitherMayExit) {
6725         // Both conditions must be false for the loop to continue executing.
6726         // Choose the less conservative count.
6727         if (EL0.ExactNotTaken == getCouldNotCompute() ||
6728             EL1.ExactNotTaken == getCouldNotCompute())
6729           BECount = getCouldNotCompute();
6730         else
6731           BECount =
6732               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
6733         if (EL0.MaxNotTaken == getCouldNotCompute())
6734           MaxBECount = EL1.MaxNotTaken;
6735         else if (EL1.MaxNotTaken == getCouldNotCompute())
6736           MaxBECount = EL0.MaxNotTaken;
6737         else
6738           MaxBECount =
6739               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
6740       } else {
6741         // Both conditions must be false at the same time for the loop to exit.
6742         // For now, be conservative.
6743         assert(L->contains(TBB) && "Loop block has no successor in loop!");
6744         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
6745           MaxBECount = EL0.MaxNotTaken;
6746         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
6747           BECount = EL0.ExactNotTaken;
6748       }
6749 
6750       return ExitLimit(BECount, MaxBECount, false,
6751                        {&EL0.Predicates, &EL1.Predicates});
6752     }
6753   }
6754 
6755   // With an icmp, it may be feasible to compute an exact backedge-taken count.
6756   // Proceed to the next level to examine the icmp.
6757   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
6758     ExitLimit EL =
6759         computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
6760     if (EL.hasFullInfo() || !AllowPredicates)
6761       return EL;
6762 
6763     // Try again, but use SCEV predicates this time.
6764     return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
6765                                     /*AllowPredicates=*/true);
6766   }
6767 
6768   // Check for a constant condition. These are normally stripped out by
6769   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
6770   // preserve the CFG and is temporarily leaving constant conditions
6771   // in place.
6772   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
6773     if (L->contains(FBB) == !CI->getZExtValue())
6774       // The backedge is always taken.
6775       return getCouldNotCompute();
6776     else
6777       // The backedge is never taken.
6778       return getZero(CI->getType());
6779   }
6780 
6781   // If it's not an integer or pointer comparison then compute it the hard way.
6782   return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6783 }
6784 
6785 ScalarEvolution::ExitLimit
6786 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
6787                                           ICmpInst *ExitCond,
6788                                           BasicBlock *TBB,
6789                                           BasicBlock *FBB,
6790                                           bool ControlsExit,
6791                                           bool AllowPredicates) {
6792 
6793   // If the condition was exit on true, convert the condition to exit on false
6794   ICmpInst::Predicate Cond;
6795   if (!L->contains(FBB))
6796     Cond = ExitCond->getPredicate();
6797   else
6798     Cond = ExitCond->getInversePredicate();
6799 
6800   // Handle common loops like: for (X = "string"; *X; ++X)
6801   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
6802     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
6803       ExitLimit ItCnt =
6804         computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
6805       if (ItCnt.hasAnyInfo())
6806         return ItCnt;
6807     }
6808 
6809   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
6810   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
6811 
6812   // Try to evaluate any dependencies out of the loop.
6813   LHS = getSCEVAtScope(LHS, L);
6814   RHS = getSCEVAtScope(RHS, L);
6815 
6816   // At this point, we would like to compute how many iterations of the
6817   // loop the predicate will return true for these inputs.
6818   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
6819     // If there is a loop-invariant, force it into the RHS.
6820     std::swap(LHS, RHS);
6821     Cond = ICmpInst::getSwappedPredicate(Cond);
6822   }
6823 
6824   // Simplify the operands before analyzing them.
6825   (void)SimplifyICmpOperands(Cond, LHS, RHS);
6826 
6827   // If we have a comparison of a chrec against a constant, try to use value
6828   // ranges to answer this query.
6829   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
6830     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
6831       if (AddRec->getLoop() == L) {
6832         // Form the constant range.
6833         ConstantRange CompRange =
6834             ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt());
6835 
6836         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
6837         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
6838       }
6839 
6840   switch (Cond) {
6841   case ICmpInst::ICMP_NE: {                     // while (X != Y)
6842     // Convert to: while (X-Y != 0)
6843     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
6844                                 AllowPredicates);
6845     if (EL.hasAnyInfo()) return EL;
6846     break;
6847   }
6848   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
6849     // Convert to: while (X-Y == 0)
6850     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
6851     if (EL.hasAnyInfo()) return EL;
6852     break;
6853   }
6854   case ICmpInst::ICMP_SLT:
6855   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
6856     bool IsSigned = Cond == ICmpInst::ICMP_SLT;
6857     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
6858                                     AllowPredicates);
6859     if (EL.hasAnyInfo()) return EL;
6860     break;
6861   }
6862   case ICmpInst::ICMP_SGT:
6863   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
6864     bool IsSigned = Cond == ICmpInst::ICMP_SGT;
6865     ExitLimit EL =
6866         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
6867                             AllowPredicates);
6868     if (EL.hasAnyInfo()) return EL;
6869     break;
6870   }
6871   default:
6872     break;
6873   }
6874 
6875   auto *ExhaustiveCount =
6876       computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
6877 
6878   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
6879     return ExhaustiveCount;
6880 
6881   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
6882                                       ExitCond->getOperand(1), L, Cond);
6883 }
6884 
6885 ScalarEvolution::ExitLimit
6886 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
6887                                                       SwitchInst *Switch,
6888                                                       BasicBlock *ExitingBlock,
6889                                                       bool ControlsExit) {
6890   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
6891 
6892   // Give up if the exit is the default dest of a switch.
6893   if (Switch->getDefaultDest() == ExitingBlock)
6894     return getCouldNotCompute();
6895 
6896   assert(L->contains(Switch->getDefaultDest()) &&
6897          "Default case must not exit the loop!");
6898   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6899   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6900 
6901   // while (X != Y) --> while (X-Y != 0)
6902   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
6903   if (EL.hasAnyInfo())
6904     return EL;
6905 
6906   return getCouldNotCompute();
6907 }
6908 
6909 static ConstantInt *
6910 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6911                                 ScalarEvolution &SE) {
6912   const SCEV *InVal = SE.getConstant(C);
6913   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
6914   assert(isa<SCEVConstant>(Val) &&
6915          "Evaluation of SCEV at constant didn't fold correctly?");
6916   return cast<SCEVConstant>(Val)->getValue();
6917 }
6918 
6919 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
6920 /// compute the backedge execution count.
6921 ScalarEvolution::ExitLimit
6922 ScalarEvolution::computeLoadConstantCompareExitLimit(
6923   LoadInst *LI,
6924   Constant *RHS,
6925   const Loop *L,
6926   ICmpInst::Predicate predicate) {
6927 
6928   if (LI->isVolatile()) return getCouldNotCompute();
6929 
6930   // Check to see if the loaded pointer is a getelementptr of a global.
6931   // TODO: Use SCEV instead of manually grubbing with GEPs.
6932   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
6933   if (!GEP) return getCouldNotCompute();
6934 
6935   // Make sure that it is really a constant global we are gepping, with an
6936   // initializer, and make sure the first IDX is really 0.
6937   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
6938   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
6939       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6940       !cast<Constant>(GEP->getOperand(1))->isNullValue())
6941     return getCouldNotCompute();
6942 
6943   // Okay, we allow one non-constant index into the GEP instruction.
6944   Value *VarIdx = nullptr;
6945   std::vector<Constant*> Indexes;
6946   unsigned VarIdxNum = 0;
6947   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6948     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6949       Indexes.push_back(CI);
6950     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
6951       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
6952       VarIdx = GEP->getOperand(i);
6953       VarIdxNum = i-2;
6954       Indexes.push_back(nullptr);
6955     }
6956 
6957   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6958   if (!VarIdx)
6959     return getCouldNotCompute();
6960 
6961   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6962   // Check to see if X is a loop variant variable value now.
6963   const SCEV *Idx = getSCEV(VarIdx);
6964   Idx = getSCEVAtScope(Idx, L);
6965 
6966   // We can only recognize very limited forms of loop index expressions, in
6967   // particular, only affine AddRec's like {C1,+,C2}.
6968   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
6969   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
6970       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6971       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
6972     return getCouldNotCompute();
6973 
6974   unsigned MaxSteps = MaxBruteForceIterations;
6975   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
6976     ConstantInt *ItCst = ConstantInt::get(
6977                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
6978     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
6979 
6980     // Form the GEP offset.
6981     Indexes[VarIdxNum] = Val;
6982 
6983     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6984                                                          Indexes);
6985     if (!Result) break;  // Cannot compute!
6986 
6987     // Evaluate the condition for this iteration.
6988     Result = ConstantExpr::getICmp(predicate, Result, RHS);
6989     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
6990     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
6991       ++NumArrayLenItCounts;
6992       return getConstant(ItCst);   // Found terminating iteration!
6993     }
6994   }
6995   return getCouldNotCompute();
6996 }
6997 
6998 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6999     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7000   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7001   if (!RHS)
7002     return getCouldNotCompute();
7003 
7004   const BasicBlock *Latch = L->getLoopLatch();
7005   if (!Latch)
7006     return getCouldNotCompute();
7007 
7008   const BasicBlock *Predecessor = L->getLoopPredecessor();
7009   if (!Predecessor)
7010     return getCouldNotCompute();
7011 
7012   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7013   // Return LHS in OutLHS and shift_opt in OutOpCode.
7014   auto MatchPositiveShift =
7015       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7016 
7017     using namespace PatternMatch;
7018 
7019     ConstantInt *ShiftAmt;
7020     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7021       OutOpCode = Instruction::LShr;
7022     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7023       OutOpCode = Instruction::AShr;
7024     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7025       OutOpCode = Instruction::Shl;
7026     else
7027       return false;
7028 
7029     return ShiftAmt->getValue().isStrictlyPositive();
7030   };
7031 
7032   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7033   //
7034   // loop:
7035   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7036   //   %iv.shifted = lshr i32 %iv, <positive constant>
7037   //
7038   // Return true on a successful match.  Return the corresponding PHI node (%iv
7039   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7040   auto MatchShiftRecurrence =
7041       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7042     Optional<Instruction::BinaryOps> PostShiftOpCode;
7043 
7044     {
7045       Instruction::BinaryOps OpC;
7046       Value *V;
7047 
7048       // If we encounter a shift instruction, "peel off" the shift operation,
7049       // and remember that we did so.  Later when we inspect %iv's backedge
7050       // value, we will make sure that the backedge value uses the same
7051       // operation.
7052       //
7053       // Note: the peeled shift operation does not have to be the same
7054       // instruction as the one feeding into the PHI's backedge value.  We only
7055       // really care about it being the same *kind* of shift instruction --
7056       // that's all that is required for our later inferences to hold.
7057       if (MatchPositiveShift(LHS, V, OpC)) {
7058         PostShiftOpCode = OpC;
7059         LHS = V;
7060       }
7061     }
7062 
7063     PNOut = dyn_cast<PHINode>(LHS);
7064     if (!PNOut || PNOut->getParent() != L->getHeader())
7065       return false;
7066 
7067     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7068     Value *OpLHS;
7069 
7070     return
7071         // The backedge value for the PHI node must be a shift by a positive
7072         // amount
7073         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7074 
7075         // of the PHI node itself
7076         OpLHS == PNOut &&
7077 
7078         // and the kind of shift should be match the kind of shift we peeled
7079         // off, if any.
7080         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7081   };
7082 
7083   PHINode *PN;
7084   Instruction::BinaryOps OpCode;
7085   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7086     return getCouldNotCompute();
7087 
7088   const DataLayout &DL = getDataLayout();
7089 
7090   // The key rationale for this optimization is that for some kinds of shift
7091   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7092   // within a finite number of iterations.  If the condition guarding the
7093   // backedge (in the sense that the backedge is taken if the condition is true)
7094   // is false for the value the shift recurrence stabilizes to, then we know
7095   // that the backedge is taken only a finite number of times.
7096 
7097   ConstantInt *StableValue = nullptr;
7098   switch (OpCode) {
7099   default:
7100     llvm_unreachable("Impossible case!");
7101 
7102   case Instruction::AShr: {
7103     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7104     // bitwidth(K) iterations.
7105     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7106     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7107                                        Predecessor->getTerminator(), &DT);
7108     auto *Ty = cast<IntegerType>(RHS->getType());
7109     if (Known.isNonNegative())
7110       StableValue = ConstantInt::get(Ty, 0);
7111     else if (Known.isNegative())
7112       StableValue = ConstantInt::get(Ty, -1, true);
7113     else
7114       return getCouldNotCompute();
7115 
7116     break;
7117   }
7118   case Instruction::LShr:
7119   case Instruction::Shl:
7120     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7121     // stabilize to 0 in at most bitwidth(K) iterations.
7122     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7123     break;
7124   }
7125 
7126   auto *Result =
7127       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7128   assert(Result->getType()->isIntegerTy(1) &&
7129          "Otherwise cannot be an operand to a branch instruction");
7130 
7131   if (Result->isZeroValue()) {
7132     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7133     const SCEV *UpperBound =
7134         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7135     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7136   }
7137 
7138   return getCouldNotCompute();
7139 }
7140 
7141 /// Return true if we can constant fold an instruction of the specified type,
7142 /// assuming that all operands were constants.
7143 static bool CanConstantFold(const Instruction *I) {
7144   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7145       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7146       isa<LoadInst>(I))
7147     return true;
7148 
7149   if (const CallInst *CI = dyn_cast<CallInst>(I))
7150     if (const Function *F = CI->getCalledFunction())
7151       return canConstantFoldCallTo(CI, F);
7152   return false;
7153 }
7154 
7155 /// Determine whether this instruction can constant evolve within this loop
7156 /// assuming its operands can all constant evolve.
7157 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7158   // An instruction outside of the loop can't be derived from a loop PHI.
7159   if (!L->contains(I)) return false;
7160 
7161   if (isa<PHINode>(I)) {
7162     // We don't currently keep track of the control flow needed to evaluate
7163     // PHIs, so we cannot handle PHIs inside of loops.
7164     return L->getHeader() == I->getParent();
7165   }
7166 
7167   // If we won't be able to constant fold this expression even if the operands
7168   // are constants, bail early.
7169   return CanConstantFold(I);
7170 }
7171 
7172 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7173 /// recursing through each instruction operand until reaching a loop header phi.
7174 static PHINode *
7175 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7176                                DenseMap<Instruction *, PHINode *> &PHIMap,
7177                                unsigned Depth) {
7178   if (Depth > MaxConstantEvolvingDepth)
7179     return nullptr;
7180 
7181   // Otherwise, we can evaluate this instruction if all of its operands are
7182   // constant or derived from a PHI node themselves.
7183   PHINode *PHI = nullptr;
7184   for (Value *Op : UseInst->operands()) {
7185     if (isa<Constant>(Op)) continue;
7186 
7187     Instruction *OpInst = dyn_cast<Instruction>(Op);
7188     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7189 
7190     PHINode *P = dyn_cast<PHINode>(OpInst);
7191     if (!P)
7192       // If this operand is already visited, reuse the prior result.
7193       // We may have P != PHI if this is the deepest point at which the
7194       // inconsistent paths meet.
7195       P = PHIMap.lookup(OpInst);
7196     if (!P) {
7197       // Recurse and memoize the results, whether a phi is found or not.
7198       // This recursive call invalidates pointers into PHIMap.
7199       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7200       PHIMap[OpInst] = P;
7201     }
7202     if (!P)
7203       return nullptr;  // Not evolving from PHI
7204     if (PHI && PHI != P)
7205       return nullptr;  // Evolving from multiple different PHIs.
7206     PHI = P;
7207   }
7208   // This is a expression evolving from a constant PHI!
7209   return PHI;
7210 }
7211 
7212 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7213 /// in the loop that V is derived from.  We allow arbitrary operations along the
7214 /// way, but the operands of an operation must either be constants or a value
7215 /// derived from a constant PHI.  If this expression does not fit with these
7216 /// constraints, return null.
7217 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7218   Instruction *I = dyn_cast<Instruction>(V);
7219   if (!I || !canConstantEvolve(I, L)) return nullptr;
7220 
7221   if (PHINode *PN = dyn_cast<PHINode>(I))
7222     return PN;
7223 
7224   // Record non-constant instructions contained by the loop.
7225   DenseMap<Instruction *, PHINode *> PHIMap;
7226   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7227 }
7228 
7229 /// EvaluateExpression - Given an expression that passes the
7230 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7231 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7232 /// reason, return null.
7233 static Constant *EvaluateExpression(Value *V, const Loop *L,
7234                                     DenseMap<Instruction *, Constant *> &Vals,
7235                                     const DataLayout &DL,
7236                                     const TargetLibraryInfo *TLI) {
7237   // Convenient constant check, but redundant for recursive calls.
7238   if (Constant *C = dyn_cast<Constant>(V)) return C;
7239   Instruction *I = dyn_cast<Instruction>(V);
7240   if (!I) return nullptr;
7241 
7242   if (Constant *C = Vals.lookup(I)) return C;
7243 
7244   // An instruction inside the loop depends on a value outside the loop that we
7245   // weren't given a mapping for, or a value such as a call inside the loop.
7246   if (!canConstantEvolve(I, L)) return nullptr;
7247 
7248   // An unmapped PHI can be due to a branch or another loop inside this loop,
7249   // or due to this not being the initial iteration through a loop where we
7250   // couldn't compute the evolution of this particular PHI last time.
7251   if (isa<PHINode>(I)) return nullptr;
7252 
7253   std::vector<Constant*> Operands(I->getNumOperands());
7254 
7255   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7256     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7257     if (!Operand) {
7258       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7259       if (!Operands[i]) return nullptr;
7260       continue;
7261     }
7262     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7263     Vals[Operand] = C;
7264     if (!C) return nullptr;
7265     Operands[i] = C;
7266   }
7267 
7268   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7269     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7270                                            Operands[1], DL, TLI);
7271   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7272     if (!LI->isVolatile())
7273       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7274   }
7275   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7276 }
7277 
7278 
7279 // If every incoming value to PN except the one for BB is a specific Constant,
7280 // return that, else return nullptr.
7281 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7282   Constant *IncomingVal = nullptr;
7283 
7284   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7285     if (PN->getIncomingBlock(i) == BB)
7286       continue;
7287 
7288     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7289     if (!CurrentVal)
7290       return nullptr;
7291 
7292     if (IncomingVal != CurrentVal) {
7293       if (IncomingVal)
7294         return nullptr;
7295       IncomingVal = CurrentVal;
7296     }
7297   }
7298 
7299   return IncomingVal;
7300 }
7301 
7302 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7303 /// in the header of its containing loop, we know the loop executes a
7304 /// constant number of times, and the PHI node is just a recurrence
7305 /// involving constants, fold it.
7306 Constant *
7307 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7308                                                    const APInt &BEs,
7309                                                    const Loop *L) {
7310   auto I = ConstantEvolutionLoopExitValue.find(PN);
7311   if (I != ConstantEvolutionLoopExitValue.end())
7312     return I->second;
7313 
7314   if (BEs.ugt(MaxBruteForceIterations))
7315     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7316 
7317   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7318 
7319   DenseMap<Instruction *, Constant *> CurrentIterVals;
7320   BasicBlock *Header = L->getHeader();
7321   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7322 
7323   BasicBlock *Latch = L->getLoopLatch();
7324   if (!Latch)
7325     return nullptr;
7326 
7327   for (auto &I : *Header) {
7328     PHINode *PHI = dyn_cast<PHINode>(&I);
7329     if (!PHI) break;
7330     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7331     if (!StartCST) continue;
7332     CurrentIterVals[PHI] = StartCST;
7333   }
7334   if (!CurrentIterVals.count(PN))
7335     return RetVal = nullptr;
7336 
7337   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7338 
7339   // Execute the loop symbolically to determine the exit value.
7340   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7341          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7342 
7343   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7344   unsigned IterationNum = 0;
7345   const DataLayout &DL = getDataLayout();
7346   for (; ; ++IterationNum) {
7347     if (IterationNum == NumIterations)
7348       return RetVal = CurrentIterVals[PN];  // Got exit value!
7349 
7350     // Compute the value of the PHIs for the next iteration.
7351     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7352     DenseMap<Instruction *, Constant *> NextIterVals;
7353     Constant *NextPHI =
7354         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7355     if (!NextPHI)
7356       return nullptr;        // Couldn't evaluate!
7357     NextIterVals[PN] = NextPHI;
7358 
7359     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7360 
7361     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7362     // cease to be able to evaluate one of them or if they stop evolving,
7363     // because that doesn't necessarily prevent us from computing PN.
7364     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7365     for (const auto &I : CurrentIterVals) {
7366       PHINode *PHI = dyn_cast<PHINode>(I.first);
7367       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7368       PHIsToCompute.emplace_back(PHI, I.second);
7369     }
7370     // We use two distinct loops because EvaluateExpression may invalidate any
7371     // iterators into CurrentIterVals.
7372     for (const auto &I : PHIsToCompute) {
7373       PHINode *PHI = I.first;
7374       Constant *&NextPHI = NextIterVals[PHI];
7375       if (!NextPHI) {   // Not already computed.
7376         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7377         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7378       }
7379       if (NextPHI != I.second)
7380         StoppedEvolving = false;
7381     }
7382 
7383     // If all entries in CurrentIterVals == NextIterVals then we can stop
7384     // iterating, the loop can't continue to change.
7385     if (StoppedEvolving)
7386       return RetVal = CurrentIterVals[PN];
7387 
7388     CurrentIterVals.swap(NextIterVals);
7389   }
7390 }
7391 
7392 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7393                                                           Value *Cond,
7394                                                           bool ExitWhen) {
7395   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7396   if (!PN) return getCouldNotCompute();
7397 
7398   // If the loop is canonicalized, the PHI will have exactly two entries.
7399   // That's the only form we support here.
7400   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7401 
7402   DenseMap<Instruction *, Constant *> CurrentIterVals;
7403   BasicBlock *Header = L->getHeader();
7404   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7405 
7406   BasicBlock *Latch = L->getLoopLatch();
7407   assert(Latch && "Should follow from NumIncomingValues == 2!");
7408 
7409   for (auto &I : *Header) {
7410     PHINode *PHI = dyn_cast<PHINode>(&I);
7411     if (!PHI)
7412       break;
7413     auto *StartCST = getOtherIncomingValue(PHI, Latch);
7414     if (!StartCST) continue;
7415     CurrentIterVals[PHI] = StartCST;
7416   }
7417   if (!CurrentIterVals.count(PN))
7418     return getCouldNotCompute();
7419 
7420   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7421   // the loop symbolically to determine when the condition gets a value of
7422   // "ExitWhen".
7423   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7424   const DataLayout &DL = getDataLayout();
7425   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7426     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7427         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7428 
7429     // Couldn't symbolically evaluate.
7430     if (!CondVal) return getCouldNotCompute();
7431 
7432     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7433       ++NumBruteForceTripCountsComputed;
7434       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7435     }
7436 
7437     // Update all the PHI nodes for the next iteration.
7438     DenseMap<Instruction *, Constant *> NextIterVals;
7439 
7440     // Create a list of which PHIs we need to compute. We want to do this before
7441     // calling EvaluateExpression on them because that may invalidate iterators
7442     // into CurrentIterVals.
7443     SmallVector<PHINode *, 8> PHIsToCompute;
7444     for (const auto &I : CurrentIterVals) {
7445       PHINode *PHI = dyn_cast<PHINode>(I.first);
7446       if (!PHI || PHI->getParent() != Header) continue;
7447       PHIsToCompute.push_back(PHI);
7448     }
7449     for (PHINode *PHI : PHIsToCompute) {
7450       Constant *&NextPHI = NextIterVals[PHI];
7451       if (NextPHI) continue;    // Already computed!
7452 
7453       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7454       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7455     }
7456     CurrentIterVals.swap(NextIterVals);
7457   }
7458 
7459   // Too many iterations were needed to evaluate.
7460   return getCouldNotCompute();
7461 }
7462 
7463 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7464   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7465       ValuesAtScopes[V];
7466   // Check to see if we've folded this expression at this loop before.
7467   for (auto &LS : Values)
7468     if (LS.first == L)
7469       return LS.second ? LS.second : V;
7470 
7471   Values.emplace_back(L, nullptr);
7472 
7473   // Otherwise compute it.
7474   const SCEV *C = computeSCEVAtScope(V, L);
7475   for (auto &LS : reverse(ValuesAtScopes[V]))
7476     if (LS.first == L) {
7477       LS.second = C;
7478       break;
7479     }
7480   return C;
7481 }
7482 
7483 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7484 /// will return Constants for objects which aren't represented by a
7485 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7486 /// Returns NULL if the SCEV isn't representable as a Constant.
7487 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7488   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7489     case scCouldNotCompute:
7490     case scAddRecExpr:
7491       break;
7492     case scConstant:
7493       return cast<SCEVConstant>(V)->getValue();
7494     case scUnknown:
7495       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7496     case scSignExtend: {
7497       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7498       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7499         return ConstantExpr::getSExt(CastOp, SS->getType());
7500       break;
7501     }
7502     case scZeroExtend: {
7503       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7504       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7505         return ConstantExpr::getZExt(CastOp, SZ->getType());
7506       break;
7507     }
7508     case scTruncate: {
7509       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7510       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7511         return ConstantExpr::getTrunc(CastOp, ST->getType());
7512       break;
7513     }
7514     case scAddExpr: {
7515       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7516       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7517         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7518           unsigned AS = PTy->getAddressSpace();
7519           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7520           C = ConstantExpr::getBitCast(C, DestPtrTy);
7521         }
7522         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7523           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7524           if (!C2) return nullptr;
7525 
7526           // First pointer!
7527           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7528             unsigned AS = C2->getType()->getPointerAddressSpace();
7529             std::swap(C, C2);
7530             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7531             // The offsets have been converted to bytes.  We can add bytes to an
7532             // i8* by GEP with the byte count in the first index.
7533             C = ConstantExpr::getBitCast(C, DestPtrTy);
7534           }
7535 
7536           // Don't bother trying to sum two pointers. We probably can't
7537           // statically compute a load that results from it anyway.
7538           if (C2->getType()->isPointerTy())
7539             return nullptr;
7540 
7541           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7542             if (PTy->getElementType()->isStructTy())
7543               C2 = ConstantExpr::getIntegerCast(
7544                   C2, Type::getInt32Ty(C->getContext()), true);
7545             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7546           } else
7547             C = ConstantExpr::getAdd(C, C2);
7548         }
7549         return C;
7550       }
7551       break;
7552     }
7553     case scMulExpr: {
7554       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7555       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7556         // Don't bother with pointers at all.
7557         if (C->getType()->isPointerTy()) return nullptr;
7558         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7559           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7560           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7561           C = ConstantExpr::getMul(C, C2);
7562         }
7563         return C;
7564       }
7565       break;
7566     }
7567     case scUDivExpr: {
7568       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7569       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7570         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7571           if (LHS->getType() == RHS->getType())
7572             return ConstantExpr::getUDiv(LHS, RHS);
7573       break;
7574     }
7575     case scSMaxExpr:
7576     case scUMaxExpr:
7577       break; // TODO: smax, umax.
7578   }
7579   return nullptr;
7580 }
7581 
7582 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7583   if (isa<SCEVConstant>(V)) return V;
7584 
7585   // If this instruction is evolved from a constant-evolving PHI, compute the
7586   // exit value from the loop without using SCEVs.
7587   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7588     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7589       const Loop *LI = this->LI[I->getParent()];
7590       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7591         if (PHINode *PN = dyn_cast<PHINode>(I))
7592           if (PN->getParent() == LI->getHeader()) {
7593             // Okay, there is no closed form solution for the PHI node.  Check
7594             // to see if the loop that contains it has a known backedge-taken
7595             // count.  If so, we may be able to force computation of the exit
7596             // value.
7597             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7598             if (const SCEVConstant *BTCC =
7599                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7600 
7601               // This trivial case can show up in some degenerate cases where
7602               // the incoming IR has not yet been fully simplified.
7603               if (BTCC->getValue()->isZero()) {
7604                 Value *InitValue = nullptr;
7605                 bool MultipleInitValues = false;
7606                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7607                   if (!LI->contains(PN->getIncomingBlock(i))) {
7608                     if (!InitValue)
7609                       InitValue = PN->getIncomingValue(i);
7610                     else if (InitValue != PN->getIncomingValue(i)) {
7611                       MultipleInitValues = true;
7612                       break;
7613                     }
7614                   }
7615                   if (!MultipleInitValues && InitValue)
7616                     return getSCEV(InitValue);
7617                 }
7618               }
7619               // Okay, we know how many times the containing loop executes.  If
7620               // this is a constant evolving PHI node, get the final value at
7621               // the specified iteration number.
7622               Constant *RV =
7623                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7624               if (RV) return getSCEV(RV);
7625             }
7626           }
7627 
7628       // Okay, this is an expression that we cannot symbolically evaluate
7629       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7630       // the arguments into constants, and if so, try to constant propagate the
7631       // result.  This is particularly useful for computing loop exit values.
7632       if (CanConstantFold(I)) {
7633         SmallVector<Constant *, 4> Operands;
7634         bool MadeImprovement = false;
7635         for (Value *Op : I->operands()) {
7636           if (Constant *C = dyn_cast<Constant>(Op)) {
7637             Operands.push_back(C);
7638             continue;
7639           }
7640 
7641           // If any of the operands is non-constant and if they are
7642           // non-integer and non-pointer, don't even try to analyze them
7643           // with scev techniques.
7644           if (!isSCEVable(Op->getType()))
7645             return V;
7646 
7647           const SCEV *OrigV = getSCEV(Op);
7648           const SCEV *OpV = getSCEVAtScope(OrigV, L);
7649           MadeImprovement |= OrigV != OpV;
7650 
7651           Constant *C = BuildConstantFromSCEV(OpV);
7652           if (!C) return V;
7653           if (C->getType() != Op->getType())
7654             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
7655                                                               Op->getType(),
7656                                                               false),
7657                                       C, Op->getType());
7658           Operands.push_back(C);
7659         }
7660 
7661         // Check to see if getSCEVAtScope actually made an improvement.
7662         if (MadeImprovement) {
7663           Constant *C = nullptr;
7664           const DataLayout &DL = getDataLayout();
7665           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7666             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7667                                                 Operands[1], DL, &TLI);
7668           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
7669             if (!LI->isVolatile())
7670               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7671           } else
7672             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
7673           if (!C) return V;
7674           return getSCEV(C);
7675         }
7676       }
7677     }
7678 
7679     // This is some other type of SCEVUnknown, just return it.
7680     return V;
7681   }
7682 
7683   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
7684     // Avoid performing the look-up in the common case where the specified
7685     // expression has no loop-variant portions.
7686     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
7687       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7688       if (OpAtScope != Comm->getOperand(i)) {
7689         // Okay, at least one of these operands is loop variant but might be
7690         // foldable.  Build a new instance of the folded commutative expression.
7691         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
7692                                             Comm->op_begin()+i);
7693         NewOps.push_back(OpAtScope);
7694 
7695         for (++i; i != e; ++i) {
7696           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
7697           NewOps.push_back(OpAtScope);
7698         }
7699         if (isa<SCEVAddExpr>(Comm))
7700           return getAddExpr(NewOps);
7701         if (isa<SCEVMulExpr>(Comm))
7702           return getMulExpr(NewOps);
7703         if (isa<SCEVSMaxExpr>(Comm))
7704           return getSMaxExpr(NewOps);
7705         if (isa<SCEVUMaxExpr>(Comm))
7706           return getUMaxExpr(NewOps);
7707         llvm_unreachable("Unknown commutative SCEV type!");
7708       }
7709     }
7710     // If we got here, all operands are loop invariant.
7711     return Comm;
7712   }
7713 
7714   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
7715     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
7716     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
7717     if (LHS == Div->getLHS() && RHS == Div->getRHS())
7718       return Div;   // must be loop invariant
7719     return getUDivExpr(LHS, RHS);
7720   }
7721 
7722   // If this is a loop recurrence for a loop that does not contain L, then we
7723   // are dealing with the final value computed by the loop.
7724   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
7725     // First, attempt to evaluate each operand.
7726     // Avoid performing the look-up in the common case where the specified
7727     // expression has no loop-variant portions.
7728     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
7729       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
7730       if (OpAtScope == AddRec->getOperand(i))
7731         continue;
7732 
7733       // Okay, at least one of these operands is loop variant but might be
7734       // foldable.  Build a new instance of the folded commutative expression.
7735       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
7736                                           AddRec->op_begin()+i);
7737       NewOps.push_back(OpAtScope);
7738       for (++i; i != e; ++i)
7739         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
7740 
7741       const SCEV *FoldedRec =
7742         getAddRecExpr(NewOps, AddRec->getLoop(),
7743                       AddRec->getNoWrapFlags(SCEV::FlagNW));
7744       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
7745       // The addrec may be folded to a nonrecurrence, for example, if the
7746       // induction variable is multiplied by zero after constant folding. Go
7747       // ahead and return the folded value.
7748       if (!AddRec)
7749         return FoldedRec;
7750       break;
7751     }
7752 
7753     // If the scope is outside the addrec's loop, evaluate it by using the
7754     // loop exit value of the addrec.
7755     if (!AddRec->getLoop()->contains(L)) {
7756       // To evaluate this recurrence, we need to know how many times the AddRec
7757       // loop iterates.  Compute this now.
7758       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
7759       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
7760 
7761       // Then, evaluate the AddRec.
7762       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
7763     }
7764 
7765     return AddRec;
7766   }
7767 
7768   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
7769     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7770     if (Op == Cast->getOperand())
7771       return Cast;  // must be loop invariant
7772     return getZeroExtendExpr(Op, Cast->getType());
7773   }
7774 
7775   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
7776     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7777     if (Op == Cast->getOperand())
7778       return Cast;  // must be loop invariant
7779     return getSignExtendExpr(Op, Cast->getType());
7780   }
7781 
7782   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
7783     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
7784     if (Op == Cast->getOperand())
7785       return Cast;  // must be loop invariant
7786     return getTruncateExpr(Op, Cast->getType());
7787   }
7788 
7789   llvm_unreachable("Unknown SCEV type!");
7790 }
7791 
7792 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
7793   return getSCEVAtScope(getSCEV(V), L);
7794 }
7795 
7796 /// Finds the minimum unsigned root of the following equation:
7797 ///
7798 ///     A * X = B (mod N)
7799 ///
7800 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
7801 /// A and B isn't important.
7802 ///
7803 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
7804 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
7805                                                ScalarEvolution &SE) {
7806   uint32_t BW = A.getBitWidth();
7807   assert(BW == SE.getTypeSizeInBits(B->getType()));
7808   assert(A != 0 && "A must be non-zero.");
7809 
7810   // 1. D = gcd(A, N)
7811   //
7812   // The gcd of A and N may have only one prime factor: 2. The number of
7813   // trailing zeros in A is its multiplicity
7814   uint32_t Mult2 = A.countTrailingZeros();
7815   // D = 2^Mult2
7816 
7817   // 2. Check if B is divisible by D.
7818   //
7819   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
7820   // is not less than multiplicity of this prime factor for D.
7821   if (SE.GetMinTrailingZeros(B) < Mult2)
7822     return SE.getCouldNotCompute();
7823 
7824   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
7825   // modulo (N / D).
7826   //
7827   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
7828   // (N / D) in general. The inverse itself always fits into BW bits, though,
7829   // so we immediately truncate it.
7830   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
7831   APInt Mod(BW + 1, 0);
7832   Mod.setBit(BW - Mult2);  // Mod = N / D
7833   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
7834 
7835   // 4. Compute the minimum unsigned root of the equation:
7836   // I * (B / D) mod (N / D)
7837   // To simplify the computation, we factor out the divide by D:
7838   // (I * B mod N) / D
7839   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
7840   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
7841 }
7842 
7843 /// Find the roots of the quadratic equation for the given quadratic chrec
7844 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
7845 /// two SCEVCouldNotCompute objects.
7846 ///
7847 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
7848 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
7849   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
7850   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
7851   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
7852   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
7853 
7854   // We currently can only solve this if the coefficients are constants.
7855   if (!LC || !MC || !NC)
7856     return None;
7857 
7858   uint32_t BitWidth = LC->getAPInt().getBitWidth();
7859   const APInt &L = LC->getAPInt();
7860   const APInt &M = MC->getAPInt();
7861   const APInt &N = NC->getAPInt();
7862   APInt Two(BitWidth, 2);
7863 
7864   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
7865 
7866   // The A coefficient is N/2
7867   APInt A = N.sdiv(Two);
7868 
7869   // The B coefficient is M-N/2
7870   APInt B = M;
7871   B -= A; // A is the same as N/2.
7872 
7873   // The C coefficient is L.
7874   const APInt& C = L;
7875 
7876   // Compute the B^2-4ac term.
7877   APInt SqrtTerm = B;
7878   SqrtTerm *= B;
7879   SqrtTerm -= 4 * (A * C);
7880 
7881   if (SqrtTerm.isNegative()) {
7882     // The loop is provably infinite.
7883     return None;
7884   }
7885 
7886   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
7887   // integer value or else APInt::sqrt() will assert.
7888   APInt SqrtVal = SqrtTerm.sqrt();
7889 
7890   // Compute the two solutions for the quadratic formula.
7891   // The divisions must be performed as signed divisions.
7892   APInt NegB = -std::move(B);
7893   APInt TwoA = std::move(A);
7894   TwoA <<= 1;
7895   if (TwoA.isNullValue())
7896     return None;
7897 
7898   LLVMContext &Context = SE.getContext();
7899 
7900   ConstantInt *Solution1 =
7901     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
7902   ConstantInt *Solution2 =
7903     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
7904 
7905   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
7906                         cast<SCEVConstant>(SE.getConstant(Solution2)));
7907 }
7908 
7909 ScalarEvolution::ExitLimit
7910 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7911                               bool AllowPredicates) {
7912 
7913   // This is only used for loops with a "x != y" exit test. The exit condition
7914   // is now expressed as a single expression, V = x-y. So the exit test is
7915   // effectively V != 0.  We know and take advantage of the fact that this
7916   // expression only being used in a comparison by zero context.
7917 
7918   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
7919   // If the value is a constant
7920   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
7921     // If the value is already zero, the branch will execute zero times.
7922     if (C->getValue()->isZero()) return C;
7923     return getCouldNotCompute();  // Otherwise it will loop infinitely.
7924   }
7925 
7926   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
7927   if (!AddRec && AllowPredicates)
7928     // Try to make this an AddRec using runtime tests, in the first X
7929     // iterations of this loop, where X is the SCEV expression found by the
7930     // algorithm below.
7931     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
7932 
7933   if (!AddRec || AddRec->getLoop() != L)
7934     return getCouldNotCompute();
7935 
7936   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7937   // the quadratic equation to solve it.
7938   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7939     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
7940       const SCEVConstant *R1 = Roots->first;
7941       const SCEVConstant *R2 = Roots->second;
7942       // Pick the smallest positive root value.
7943       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
7944               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
7945         if (!CB->getZExtValue())
7946           std::swap(R1, R2); // R1 is the minimum root now.
7947 
7948         // We can only use this value if the chrec ends up with an exact zero
7949         // value at this index.  When solving for "X*X != 5", for example, we
7950         // should not accept a root of 2.
7951         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
7952         if (Val->isZero())
7953           // We found a quadratic root!
7954           return ExitLimit(R1, R1, false, Predicates);
7955       }
7956     }
7957     return getCouldNotCompute();
7958   }
7959 
7960   // Otherwise we can only handle this if it is affine.
7961   if (!AddRec->isAffine())
7962     return getCouldNotCompute();
7963 
7964   // If this is an affine expression, the execution count of this branch is
7965   // the minimum unsigned root of the following equation:
7966   //
7967   //     Start + Step*N = 0 (mod 2^BW)
7968   //
7969   // equivalent to:
7970   //
7971   //             Step*N = -Start (mod 2^BW)
7972   //
7973   // where BW is the common bit width of Start and Step.
7974 
7975   // Get the initial value for the loop.
7976   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7977   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7978 
7979   // For now we handle only constant steps.
7980   //
7981   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7982   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7983   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7984   // We have not yet seen any such cases.
7985   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
7986   if (!StepC || StepC->getValue()->isZero())
7987     return getCouldNotCompute();
7988 
7989   // For positive steps (counting up until unsigned overflow):
7990   //   N = -Start/Step (as unsigned)
7991   // For negative steps (counting down to zero):
7992   //   N = Start/-Step
7993   // First compute the unsigned distance from zero in the direction of Step.
7994   bool CountDown = StepC->getAPInt().isNegative();
7995   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
7996 
7997   // Handle unitary steps, which cannot wraparound.
7998   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7999   //   N = Distance (as unsigned)
8000   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8001     APInt MaxBECount = getUnsignedRangeMax(Distance);
8002 
8003     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8004     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8005     // case, and see if we can improve the bound.
8006     //
8007     // Explicitly handling this here is necessary because getUnsignedRange
8008     // isn't context-sensitive; it doesn't know that we only care about the
8009     // range inside the loop.
8010     const SCEV *Zero = getZero(Distance->getType());
8011     const SCEV *One = getOne(Distance->getType());
8012     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8013     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8014       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8015       // as "unsigned_max(Distance + 1) - 1".
8016       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8017       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8018     }
8019     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8020   }
8021 
8022   // If the condition controls loop exit (the loop exits only if the expression
8023   // is true) and the addition is no-wrap we can use unsigned divide to
8024   // compute the backedge count.  In this case, the step may not divide the
8025   // distance, but we don't care because if the condition is "missed" the loop
8026   // will have undefined behavior due to wrapping.
8027   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8028       loopHasNoAbnormalExits(AddRec->getLoop())) {
8029     const SCEV *Exact =
8030         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8031     const SCEV *Max =
8032         Exact == getCouldNotCompute()
8033             ? Exact
8034             : getConstant(getUnsignedRangeMax(Exact));
8035     return ExitLimit(Exact, Max, false, Predicates);
8036   }
8037 
8038   // Solve the general equation.
8039   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8040                                                getNegativeSCEV(Start), *this);
8041   const SCEV *M = E == getCouldNotCompute()
8042                       ? E
8043                       : getConstant(getUnsignedRangeMax(E));
8044   return ExitLimit(E, M, false, Predicates);
8045 }
8046 
8047 ScalarEvolution::ExitLimit
8048 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8049   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8050   // handle them yet except for the trivial case.  This could be expanded in the
8051   // future as needed.
8052 
8053   // If the value is a constant, check to see if it is known to be non-zero
8054   // already.  If so, the backedge will execute zero times.
8055   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8056     if (!C->getValue()->isZero())
8057       return getZero(C->getType());
8058     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8059   }
8060 
8061   // We could implement others, but I really doubt anyone writes loops like
8062   // this, and if they did, they would already be constant folded.
8063   return getCouldNotCompute();
8064 }
8065 
8066 std::pair<BasicBlock *, BasicBlock *>
8067 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8068   // If the block has a unique predecessor, then there is no path from the
8069   // predecessor to the block that does not go through the direct edge
8070   // from the predecessor to the block.
8071   if (BasicBlock *Pred = BB->getSinglePredecessor())
8072     return {Pred, BB};
8073 
8074   // A loop's header is defined to be a block that dominates the loop.
8075   // If the header has a unique predecessor outside the loop, it must be
8076   // a block that has exactly one successor that can reach the loop.
8077   if (Loop *L = LI.getLoopFor(BB))
8078     return {L->getLoopPredecessor(), L->getHeader()};
8079 
8080   return {nullptr, nullptr};
8081 }
8082 
8083 /// SCEV structural equivalence is usually sufficient for testing whether two
8084 /// expressions are equal, however for the purposes of looking for a condition
8085 /// guarding a loop, it can be useful to be a little more general, since a
8086 /// front-end may have replicated the controlling expression.
8087 ///
8088 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8089   // Quick check to see if they are the same SCEV.
8090   if (A == B) return true;
8091 
8092   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8093     // Not all instructions that are "identical" compute the same value.  For
8094     // instance, two distinct alloca instructions allocating the same type are
8095     // identical and do not read memory; but compute distinct values.
8096     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8097   };
8098 
8099   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8100   // two different instructions with the same value. Check for this case.
8101   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8102     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8103       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8104         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8105           if (ComputesEqualValues(AI, BI))
8106             return true;
8107 
8108   // Otherwise assume they may have a different value.
8109   return false;
8110 }
8111 
8112 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8113                                            const SCEV *&LHS, const SCEV *&RHS,
8114                                            unsigned Depth) {
8115   bool Changed = false;
8116 
8117   // If we hit the max recursion limit bail out.
8118   if (Depth >= 3)
8119     return false;
8120 
8121   // Canonicalize a constant to the right side.
8122   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8123     // Check for both operands constant.
8124     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8125       if (ConstantExpr::getICmp(Pred,
8126                                 LHSC->getValue(),
8127                                 RHSC->getValue())->isNullValue())
8128         goto trivially_false;
8129       else
8130         goto trivially_true;
8131     }
8132     // Otherwise swap the operands to put the constant on the right.
8133     std::swap(LHS, RHS);
8134     Pred = ICmpInst::getSwappedPredicate(Pred);
8135     Changed = true;
8136   }
8137 
8138   // If we're comparing an addrec with a value which is loop-invariant in the
8139   // addrec's loop, put the addrec on the left. Also make a dominance check,
8140   // as both operands could be addrecs loop-invariant in each other's loop.
8141   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8142     const Loop *L = AR->getLoop();
8143     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8144       std::swap(LHS, RHS);
8145       Pred = ICmpInst::getSwappedPredicate(Pred);
8146       Changed = true;
8147     }
8148   }
8149 
8150   // If there's a constant operand, canonicalize comparisons with boundary
8151   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8152   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8153     const APInt &RA = RC->getAPInt();
8154 
8155     bool SimplifiedByConstantRange = false;
8156 
8157     if (!ICmpInst::isEquality(Pred)) {
8158       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8159       if (ExactCR.isFullSet())
8160         goto trivially_true;
8161       else if (ExactCR.isEmptySet())
8162         goto trivially_false;
8163 
8164       APInt NewRHS;
8165       CmpInst::Predicate NewPred;
8166       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8167           ICmpInst::isEquality(NewPred)) {
8168         // We were able to convert an inequality to an equality.
8169         Pred = NewPred;
8170         RHS = getConstant(NewRHS);
8171         Changed = SimplifiedByConstantRange = true;
8172       }
8173     }
8174 
8175     if (!SimplifiedByConstantRange) {
8176       switch (Pred) {
8177       default:
8178         break;
8179       case ICmpInst::ICMP_EQ:
8180       case ICmpInst::ICMP_NE:
8181         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8182         if (!RA)
8183           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8184             if (const SCEVMulExpr *ME =
8185                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8186               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8187                   ME->getOperand(0)->isAllOnesValue()) {
8188                 RHS = AE->getOperand(1);
8189                 LHS = ME->getOperand(1);
8190                 Changed = true;
8191               }
8192         break;
8193 
8194 
8195         // The "Should have been caught earlier!" messages refer to the fact
8196         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8197         // should have fired on the corresponding cases, and canonicalized the
8198         // check to trivially_true or trivially_false.
8199 
8200       case ICmpInst::ICMP_UGE:
8201         assert(!RA.isMinValue() && "Should have been caught earlier!");
8202         Pred = ICmpInst::ICMP_UGT;
8203         RHS = getConstant(RA - 1);
8204         Changed = true;
8205         break;
8206       case ICmpInst::ICMP_ULE:
8207         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8208         Pred = ICmpInst::ICMP_ULT;
8209         RHS = getConstant(RA + 1);
8210         Changed = true;
8211         break;
8212       case ICmpInst::ICMP_SGE:
8213         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8214         Pred = ICmpInst::ICMP_SGT;
8215         RHS = getConstant(RA - 1);
8216         Changed = true;
8217         break;
8218       case ICmpInst::ICMP_SLE:
8219         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8220         Pred = ICmpInst::ICMP_SLT;
8221         RHS = getConstant(RA + 1);
8222         Changed = true;
8223         break;
8224       }
8225     }
8226   }
8227 
8228   // Check for obvious equality.
8229   if (HasSameValue(LHS, RHS)) {
8230     if (ICmpInst::isTrueWhenEqual(Pred))
8231       goto trivially_true;
8232     if (ICmpInst::isFalseWhenEqual(Pred))
8233       goto trivially_false;
8234   }
8235 
8236   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8237   // adding or subtracting 1 from one of the operands.
8238   switch (Pred) {
8239   case ICmpInst::ICMP_SLE:
8240     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8241       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8242                        SCEV::FlagNSW);
8243       Pred = ICmpInst::ICMP_SLT;
8244       Changed = true;
8245     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8246       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8247                        SCEV::FlagNSW);
8248       Pred = ICmpInst::ICMP_SLT;
8249       Changed = true;
8250     }
8251     break;
8252   case ICmpInst::ICMP_SGE:
8253     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8254       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8255                        SCEV::FlagNSW);
8256       Pred = ICmpInst::ICMP_SGT;
8257       Changed = true;
8258     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8259       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8260                        SCEV::FlagNSW);
8261       Pred = ICmpInst::ICMP_SGT;
8262       Changed = true;
8263     }
8264     break;
8265   case ICmpInst::ICMP_ULE:
8266     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8267       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8268                        SCEV::FlagNUW);
8269       Pred = ICmpInst::ICMP_ULT;
8270       Changed = true;
8271     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8272       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8273       Pred = ICmpInst::ICMP_ULT;
8274       Changed = true;
8275     }
8276     break;
8277   case ICmpInst::ICMP_UGE:
8278     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8279       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8280       Pred = ICmpInst::ICMP_UGT;
8281       Changed = true;
8282     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8283       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8284                        SCEV::FlagNUW);
8285       Pred = ICmpInst::ICMP_UGT;
8286       Changed = true;
8287     }
8288     break;
8289   default:
8290     break;
8291   }
8292 
8293   // TODO: More simplifications are possible here.
8294 
8295   // Recursively simplify until we either hit a recursion limit or nothing
8296   // changes.
8297   if (Changed)
8298     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8299 
8300   return Changed;
8301 
8302 trivially_true:
8303   // Return 0 == 0.
8304   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8305   Pred = ICmpInst::ICMP_EQ;
8306   return true;
8307 
8308 trivially_false:
8309   // Return 0 != 0.
8310   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8311   Pred = ICmpInst::ICMP_NE;
8312   return true;
8313 }
8314 
8315 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8316   return getSignedRangeMax(S).isNegative();
8317 }
8318 
8319 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8320   return getSignedRangeMin(S).isStrictlyPositive();
8321 }
8322 
8323 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8324   return !getSignedRangeMin(S).isNegative();
8325 }
8326 
8327 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8328   return !getSignedRangeMax(S).isStrictlyPositive();
8329 }
8330 
8331 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8332   return isKnownNegative(S) || isKnownPositive(S);
8333 }
8334 
8335 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8336                                        const SCEV *LHS, const SCEV *RHS) {
8337   // Canonicalize the inputs first.
8338   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8339 
8340   // If LHS or RHS is an addrec, check to see if the condition is true in
8341   // every iteration of the loop.
8342   // If LHS and RHS are both addrec, both conditions must be true in
8343   // every iteration of the loop.
8344   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8345   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8346   bool LeftGuarded = false;
8347   bool RightGuarded = false;
8348   if (LAR) {
8349     const Loop *L = LAR->getLoop();
8350     if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
8351         isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
8352       if (!RAR) return true;
8353       LeftGuarded = true;
8354     }
8355   }
8356   if (RAR) {
8357     const Loop *L = RAR->getLoop();
8358     if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
8359         isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
8360       if (!LAR) return true;
8361       RightGuarded = true;
8362     }
8363   }
8364   if (LeftGuarded && RightGuarded)
8365     return true;
8366 
8367   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8368     return true;
8369 
8370   // Otherwise see what can be done with known constant ranges.
8371   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
8372 }
8373 
8374 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8375                                            ICmpInst::Predicate Pred,
8376                                            bool &Increasing) {
8377   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8378 
8379 #ifndef NDEBUG
8380   // Verify an invariant: inverting the predicate should turn a monotonically
8381   // increasing change to a monotonically decreasing one, and vice versa.
8382   bool IncreasingSwapped;
8383   bool ResultSwapped = isMonotonicPredicateImpl(
8384       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8385 
8386   assert(Result == ResultSwapped && "should be able to analyze both!");
8387   if (ResultSwapped)
8388     assert(Increasing == !IncreasingSwapped &&
8389            "monotonicity should flip as we flip the predicate");
8390 #endif
8391 
8392   return Result;
8393 }
8394 
8395 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8396                                                ICmpInst::Predicate Pred,
8397                                                bool &Increasing) {
8398 
8399   // A zero step value for LHS means the induction variable is essentially a
8400   // loop invariant value. We don't really depend on the predicate actually
8401   // flipping from false to true (for increasing predicates, and the other way
8402   // around for decreasing predicates), all we care about is that *if* the
8403   // predicate changes then it only changes from false to true.
8404   //
8405   // A zero step value in itself is not very useful, but there may be places
8406   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8407   // as general as possible.
8408 
8409   switch (Pred) {
8410   default:
8411     return false; // Conservative answer
8412 
8413   case ICmpInst::ICMP_UGT:
8414   case ICmpInst::ICMP_UGE:
8415   case ICmpInst::ICMP_ULT:
8416   case ICmpInst::ICMP_ULE:
8417     if (!LHS->hasNoUnsignedWrap())
8418       return false;
8419 
8420     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8421     return true;
8422 
8423   case ICmpInst::ICMP_SGT:
8424   case ICmpInst::ICMP_SGE:
8425   case ICmpInst::ICMP_SLT:
8426   case ICmpInst::ICMP_SLE: {
8427     if (!LHS->hasNoSignedWrap())
8428       return false;
8429 
8430     const SCEV *Step = LHS->getStepRecurrence(*this);
8431 
8432     if (isKnownNonNegative(Step)) {
8433       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8434       return true;
8435     }
8436 
8437     if (isKnownNonPositive(Step)) {
8438       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8439       return true;
8440     }
8441 
8442     return false;
8443   }
8444 
8445   }
8446 
8447   llvm_unreachable("switch has default clause!");
8448 }
8449 
8450 bool ScalarEvolution::isLoopInvariantPredicate(
8451     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8452     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8453     const SCEV *&InvariantRHS) {
8454 
8455   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8456   if (!isLoopInvariant(RHS, L)) {
8457     if (!isLoopInvariant(LHS, L))
8458       return false;
8459 
8460     std::swap(LHS, RHS);
8461     Pred = ICmpInst::getSwappedPredicate(Pred);
8462   }
8463 
8464   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8465   if (!ArLHS || ArLHS->getLoop() != L)
8466     return false;
8467 
8468   bool Increasing;
8469   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8470     return false;
8471 
8472   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8473   // true as the loop iterates, and the backedge is control dependent on
8474   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8475   //
8476   //   * if the predicate was false in the first iteration then the predicate
8477   //     is never evaluated again, since the loop exits without taking the
8478   //     backedge.
8479   //   * if the predicate was true in the first iteration then it will
8480   //     continue to be true for all future iterations since it is
8481   //     monotonically increasing.
8482   //
8483   // For both the above possibilities, we can replace the loop varying
8484   // predicate with its value on the first iteration of the loop (which is
8485   // loop invariant).
8486   //
8487   // A similar reasoning applies for a monotonically decreasing predicate, by
8488   // replacing true with false and false with true in the above two bullets.
8489 
8490   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8491 
8492   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8493     return false;
8494 
8495   InvariantPred = Pred;
8496   InvariantLHS = ArLHS->getStart();
8497   InvariantRHS = RHS;
8498   return true;
8499 }
8500 
8501 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8502     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8503   if (HasSameValue(LHS, RHS))
8504     return ICmpInst::isTrueWhenEqual(Pred);
8505 
8506   // This code is split out from isKnownPredicate because it is called from
8507   // within isLoopEntryGuardedByCond.
8508 
8509   auto CheckRanges =
8510       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8511     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8512         .contains(RangeLHS);
8513   };
8514 
8515   // The check at the top of the function catches the case where the values are
8516   // known to be equal.
8517   if (Pred == CmpInst::ICMP_EQ)
8518     return false;
8519 
8520   if (Pred == CmpInst::ICMP_NE)
8521     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8522            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8523            isKnownNonZero(getMinusSCEV(LHS, RHS));
8524 
8525   if (CmpInst::isSigned(Pred))
8526     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8527 
8528   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8529 }
8530 
8531 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8532                                                     const SCEV *LHS,
8533                                                     const SCEV *RHS) {
8534 
8535   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8536   // Return Y via OutY.
8537   auto MatchBinaryAddToConst =
8538       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8539              SCEV::NoWrapFlags ExpectedFlags) {
8540     const SCEV *NonConstOp, *ConstOp;
8541     SCEV::NoWrapFlags FlagsPresent;
8542 
8543     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8544         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8545       return false;
8546 
8547     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8548     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8549   };
8550 
8551   APInt C;
8552 
8553   switch (Pred) {
8554   default:
8555     break;
8556 
8557   case ICmpInst::ICMP_SGE:
8558     std::swap(LHS, RHS);
8559     LLVM_FALLTHROUGH;
8560   case ICmpInst::ICMP_SLE:
8561     // X s<= (X + C)<nsw> if C >= 0
8562     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8563       return true;
8564 
8565     // (X + C)<nsw> s<= X if C <= 0
8566     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8567         !C.isStrictlyPositive())
8568       return true;
8569     break;
8570 
8571   case ICmpInst::ICMP_SGT:
8572     std::swap(LHS, RHS);
8573     LLVM_FALLTHROUGH;
8574   case ICmpInst::ICMP_SLT:
8575     // X s< (X + C)<nsw> if C > 0
8576     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8577         C.isStrictlyPositive())
8578       return true;
8579 
8580     // (X + C)<nsw> s< X if C < 0
8581     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8582       return true;
8583     break;
8584   }
8585 
8586   return false;
8587 }
8588 
8589 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8590                                                    const SCEV *LHS,
8591                                                    const SCEV *RHS) {
8592   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8593     return false;
8594 
8595   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8596   // the stack can result in exponential time complexity.
8597   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8598 
8599   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8600   //
8601   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
8602   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
8603   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
8604   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
8605   // use isKnownPredicate later if needed.
8606   return isKnownNonNegative(RHS) &&
8607          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
8608          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
8609 }
8610 
8611 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
8612                                         ICmpInst::Predicate Pred,
8613                                         const SCEV *LHS, const SCEV *RHS) {
8614   // No need to even try if we know the module has no guards.
8615   if (!HasGuards)
8616     return false;
8617 
8618   return any_of(*BB, [&](Instruction &I) {
8619     using namespace llvm::PatternMatch;
8620 
8621     Value *Condition;
8622     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
8623                          m_Value(Condition))) &&
8624            isImpliedCond(Pred, LHS, RHS, Condition, false);
8625   });
8626 }
8627 
8628 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
8629 /// protected by a conditional between LHS and RHS.  This is used to
8630 /// to eliminate casts.
8631 bool
8632 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
8633                                              ICmpInst::Predicate Pred,
8634                                              const SCEV *LHS, const SCEV *RHS) {
8635   // Interpret a null as meaning no loop, where there is obviously no guard
8636   // (interprocedural conditions notwithstanding).
8637   if (!L) return true;
8638 
8639   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8640     return true;
8641 
8642   BasicBlock *Latch = L->getLoopLatch();
8643   if (!Latch)
8644     return false;
8645 
8646   BranchInst *LoopContinuePredicate =
8647     dyn_cast<BranchInst>(Latch->getTerminator());
8648   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
8649       isImpliedCond(Pred, LHS, RHS,
8650                     LoopContinuePredicate->getCondition(),
8651                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
8652     return true;
8653 
8654   // We don't want more than one activation of the following loops on the stack
8655   // -- that can lead to O(n!) time complexity.
8656   if (WalkingBEDominatingConds)
8657     return false;
8658 
8659   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
8660 
8661   // See if we can exploit a trip count to prove the predicate.
8662   const auto &BETakenInfo = getBackedgeTakenInfo(L);
8663   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
8664   if (LatchBECount != getCouldNotCompute()) {
8665     // We know that Latch branches back to the loop header exactly
8666     // LatchBECount times.  This means the backdege condition at Latch is
8667     // equivalent to  "{0,+,1} u< LatchBECount".
8668     Type *Ty = LatchBECount->getType();
8669     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
8670     const SCEV *LoopCounter =
8671       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
8672     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
8673                       LatchBECount))
8674       return true;
8675   }
8676 
8677   // Check conditions due to any @llvm.assume intrinsics.
8678   for (auto &AssumeVH : AC.assumptions()) {
8679     if (!AssumeVH)
8680       continue;
8681     auto *CI = cast<CallInst>(AssumeVH);
8682     if (!DT.dominates(CI, Latch->getTerminator()))
8683       continue;
8684 
8685     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8686       return true;
8687   }
8688 
8689   // If the loop is not reachable from the entry block, we risk running into an
8690   // infinite loop as we walk up into the dom tree.  These loops do not matter
8691   // anyway, so we just return a conservative answer when we see them.
8692   if (!DT.isReachableFromEntry(L->getHeader()))
8693     return false;
8694 
8695   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
8696     return true;
8697 
8698   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
8699        DTN != HeaderDTN; DTN = DTN->getIDom()) {
8700 
8701     assert(DTN && "should reach the loop header before reaching the root!");
8702 
8703     BasicBlock *BB = DTN->getBlock();
8704     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
8705       return true;
8706 
8707     BasicBlock *PBB = BB->getSinglePredecessor();
8708     if (!PBB)
8709       continue;
8710 
8711     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
8712     if (!ContinuePredicate || !ContinuePredicate->isConditional())
8713       continue;
8714 
8715     Value *Condition = ContinuePredicate->getCondition();
8716 
8717     // If we have an edge `E` within the loop body that dominates the only
8718     // latch, the condition guarding `E` also guards the backedge.  This
8719     // reasoning works only for loops with a single latch.
8720 
8721     BasicBlockEdge DominatingEdge(PBB, BB);
8722     if (DominatingEdge.isSingleEdge()) {
8723       // We're constructively (and conservatively) enumerating edges within the
8724       // loop body that dominate the latch.  The dominator tree better agree
8725       // with us on this:
8726       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
8727 
8728       if (isImpliedCond(Pred, LHS, RHS, Condition,
8729                         BB != ContinuePredicate->getSuccessor(0)))
8730         return true;
8731     }
8732   }
8733 
8734   return false;
8735 }
8736 
8737 bool
8738 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
8739                                           ICmpInst::Predicate Pred,
8740                                           const SCEV *LHS, const SCEV *RHS) {
8741   // Interpret a null as meaning no loop, where there is obviously no guard
8742   // (interprocedural conditions notwithstanding).
8743   if (!L) return false;
8744 
8745   if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
8746     return true;
8747 
8748   // Starting at the loop predecessor, climb up the predecessor chain, as long
8749   // as there are predecessors that can be found that have unique successors
8750   // leading to the original header.
8751   for (std::pair<BasicBlock *, BasicBlock *>
8752          Pair(L->getLoopPredecessor(), L->getHeader());
8753        Pair.first;
8754        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
8755 
8756     if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS))
8757       return true;
8758 
8759     BranchInst *LoopEntryPredicate =
8760       dyn_cast<BranchInst>(Pair.first->getTerminator());
8761     if (!LoopEntryPredicate ||
8762         LoopEntryPredicate->isUnconditional())
8763       continue;
8764 
8765     if (isImpliedCond(Pred, LHS, RHS,
8766                       LoopEntryPredicate->getCondition(),
8767                       LoopEntryPredicate->getSuccessor(0) != Pair.second))
8768       return true;
8769   }
8770 
8771   // Check conditions due to any @llvm.assume intrinsics.
8772   for (auto &AssumeVH : AC.assumptions()) {
8773     if (!AssumeVH)
8774       continue;
8775     auto *CI = cast<CallInst>(AssumeVH);
8776     if (!DT.dominates(CI, L->getHeader()))
8777       continue;
8778 
8779     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
8780       return true;
8781   }
8782 
8783   return false;
8784 }
8785 
8786 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
8787                                     const SCEV *LHS, const SCEV *RHS,
8788                                     Value *FoundCondValue,
8789                                     bool Inverse) {
8790   if (!PendingLoopPredicates.insert(FoundCondValue).second)
8791     return false;
8792 
8793   auto ClearOnExit =
8794       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
8795 
8796   // Recursively handle And and Or conditions.
8797   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
8798     if (BO->getOpcode() == Instruction::And) {
8799       if (!Inverse)
8800         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8801                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8802     } else if (BO->getOpcode() == Instruction::Or) {
8803       if (Inverse)
8804         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8805                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
8806     }
8807   }
8808 
8809   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
8810   if (!ICI) return false;
8811 
8812   // Now that we found a conditional branch that dominates the loop or controls
8813   // the loop latch. Check to see if it is the comparison we are looking for.
8814   ICmpInst::Predicate FoundPred;
8815   if (Inverse)
8816     FoundPred = ICI->getInversePredicate();
8817   else
8818     FoundPred = ICI->getPredicate();
8819 
8820   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8821   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
8822 
8823   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8824 }
8825 
8826 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8827                                     const SCEV *RHS,
8828                                     ICmpInst::Predicate FoundPred,
8829                                     const SCEV *FoundLHS,
8830                                     const SCEV *FoundRHS) {
8831   // Balance the types.
8832   if (getTypeSizeInBits(LHS->getType()) <
8833       getTypeSizeInBits(FoundLHS->getType())) {
8834     if (CmpInst::isSigned(Pred)) {
8835       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8836       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8837     } else {
8838       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8839       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8840     }
8841   } else if (getTypeSizeInBits(LHS->getType()) >
8842       getTypeSizeInBits(FoundLHS->getType())) {
8843     if (CmpInst::isSigned(FoundPred)) {
8844       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8845       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8846     } else {
8847       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8848       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8849     }
8850   }
8851 
8852   // Canonicalize the query to match the way instcombine will have
8853   // canonicalized the comparison.
8854   if (SimplifyICmpOperands(Pred, LHS, RHS))
8855     if (LHS == RHS)
8856       return CmpInst::isTrueWhenEqual(Pred);
8857   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8858     if (FoundLHS == FoundRHS)
8859       return CmpInst::isFalseWhenEqual(FoundPred);
8860 
8861   // Check to see if we can make the LHS or RHS match.
8862   if (LHS == FoundRHS || RHS == FoundLHS) {
8863     if (isa<SCEVConstant>(RHS)) {
8864       std::swap(FoundLHS, FoundRHS);
8865       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8866     } else {
8867       std::swap(LHS, RHS);
8868       Pred = ICmpInst::getSwappedPredicate(Pred);
8869     }
8870   }
8871 
8872   // Check whether the found predicate is the same as the desired predicate.
8873   if (FoundPred == Pred)
8874     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8875 
8876   // Check whether swapping the found predicate makes it the same as the
8877   // desired predicate.
8878   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8879     if (isa<SCEVConstant>(RHS))
8880       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8881     else
8882       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8883                                    RHS, LHS, FoundLHS, FoundRHS);
8884   }
8885 
8886   // Unsigned comparison is the same as signed comparison when both the operands
8887   // are non-negative.
8888   if (CmpInst::isUnsigned(FoundPred) &&
8889       CmpInst::getSignedPredicate(FoundPred) == Pred &&
8890       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8891     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8892 
8893   // Check if we can make progress by sharpening ranges.
8894   if (FoundPred == ICmpInst::ICMP_NE &&
8895       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8896 
8897     const SCEVConstant *C = nullptr;
8898     const SCEV *V = nullptr;
8899 
8900     if (isa<SCEVConstant>(FoundLHS)) {
8901       C = cast<SCEVConstant>(FoundLHS);
8902       V = FoundRHS;
8903     } else {
8904       C = cast<SCEVConstant>(FoundRHS);
8905       V = FoundLHS;
8906     }
8907 
8908     // The guarding predicate tells us that C != V. If the known range
8909     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
8910     // range we consider has to correspond to same signedness as the
8911     // predicate we're interested in folding.
8912 
8913     APInt Min = ICmpInst::isSigned(Pred) ?
8914         getSignedRangeMin(V) : getUnsignedRangeMin(V);
8915 
8916     if (Min == C->getAPInt()) {
8917       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8918       // This is true even if (Min + 1) wraps around -- in case of
8919       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8920 
8921       APInt SharperMin = Min + 1;
8922 
8923       switch (Pred) {
8924         case ICmpInst::ICMP_SGE:
8925         case ICmpInst::ICMP_UGE:
8926           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
8927           // RHS, we're done.
8928           if (isImpliedCondOperands(Pred, LHS, RHS, V,
8929                                     getConstant(SharperMin)))
8930             return true;
8931           LLVM_FALLTHROUGH;
8932 
8933         case ICmpInst::ICMP_SGT:
8934         case ICmpInst::ICMP_UGT:
8935           // We know from the range information that (V `Pred` Min ||
8936           // V == Min).  We know from the guarding condition that !(V
8937           // == Min).  This gives us
8938           //
8939           //       V `Pred` Min || V == Min && !(V == Min)
8940           //   =>  V `Pred` Min
8941           //
8942           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8943 
8944           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8945             return true;
8946           LLVM_FALLTHROUGH;
8947 
8948         default:
8949           // No change
8950           break;
8951       }
8952     }
8953   }
8954 
8955   // Check whether the actual condition is beyond sufficient.
8956   if (FoundPred == ICmpInst::ICMP_EQ)
8957     if (ICmpInst::isTrueWhenEqual(Pred))
8958       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8959         return true;
8960   if (Pred == ICmpInst::ICMP_NE)
8961     if (!ICmpInst::isTrueWhenEqual(FoundPred))
8962       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8963         return true;
8964 
8965   // Otherwise assume the worst.
8966   return false;
8967 }
8968 
8969 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8970                                      const SCEV *&L, const SCEV *&R,
8971                                      SCEV::NoWrapFlags &Flags) {
8972   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8973   if (!AE || AE->getNumOperands() != 2)
8974     return false;
8975 
8976   L = AE->getOperand(0);
8977   R = AE->getOperand(1);
8978   Flags = AE->getNoWrapFlags();
8979   return true;
8980 }
8981 
8982 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
8983                                                            const SCEV *Less) {
8984   // We avoid subtracting expressions here because this function is usually
8985   // fairly deep in the call stack (i.e. is called many times).
8986 
8987   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8988     const auto *LAR = cast<SCEVAddRecExpr>(Less);
8989     const auto *MAR = cast<SCEVAddRecExpr>(More);
8990 
8991     if (LAR->getLoop() != MAR->getLoop())
8992       return None;
8993 
8994     // We look at affine expressions only; not for correctness but to keep
8995     // getStepRecurrence cheap.
8996     if (!LAR->isAffine() || !MAR->isAffine())
8997       return None;
8998 
8999     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9000       return None;
9001 
9002     Less = LAR->getStart();
9003     More = MAR->getStart();
9004 
9005     // fall through
9006   }
9007 
9008   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9009     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9010     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9011     return M - L;
9012   }
9013 
9014   const SCEV *L, *R;
9015   SCEV::NoWrapFlags Flags;
9016   if (splitBinaryAdd(Less, L, R, Flags))
9017     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9018       if (R == More)
9019         return -(LC->getAPInt());
9020 
9021   if (splitBinaryAdd(More, L, R, Flags))
9022     if (const auto *LC = dyn_cast<SCEVConstant>(L))
9023       if (R == Less)
9024         return LC->getAPInt();
9025 
9026   return None;
9027 }
9028 
9029 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9030     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9031     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9032   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9033     return false;
9034 
9035   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9036   if (!AddRecLHS)
9037     return false;
9038 
9039   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9040   if (!AddRecFoundLHS)
9041     return false;
9042 
9043   // We'd like to let SCEV reason about control dependencies, so we constrain
9044   // both the inequalities to be about add recurrences on the same loop.  This
9045   // way we can use isLoopEntryGuardedByCond later.
9046 
9047   const Loop *L = AddRecFoundLHS->getLoop();
9048   if (L != AddRecLHS->getLoop())
9049     return false;
9050 
9051   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9052   //
9053   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9054   //                                                                  ... (2)
9055   //
9056   // Informal proof for (2), assuming (1) [*]:
9057   //
9058   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9059   //
9060   // Then
9061   //
9062   //       FoundLHS s< FoundRHS s< INT_MIN - C
9063   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9064   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9065   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9066   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9067   // <=>  FoundLHS + C s< FoundRHS + C
9068   //
9069   // [*]: (1) can be proved by ruling out overflow.
9070   //
9071   // [**]: This can be proved by analyzing all the four possibilities:
9072   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9073   //    (A s>= 0, B s>= 0).
9074   //
9075   // Note:
9076   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9077   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9078   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9079   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9080   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9081   // C)".
9082 
9083   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9084   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9085   if (!LDiff || !RDiff || *LDiff != *RDiff)
9086     return false;
9087 
9088   if (LDiff->isMinValue())
9089     return true;
9090 
9091   APInt FoundRHSLimit;
9092 
9093   if (Pred == CmpInst::ICMP_ULT) {
9094     FoundRHSLimit = -(*RDiff);
9095   } else {
9096     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9097     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9098   }
9099 
9100   // Try to prove (1) or (2), as needed.
9101   return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9102                                   getConstant(FoundRHSLimit));
9103 }
9104 
9105 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9106                                             const SCEV *LHS, const SCEV *RHS,
9107                                             const SCEV *FoundLHS,
9108                                             const SCEV *FoundRHS) {
9109   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9110     return true;
9111 
9112   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9113     return true;
9114 
9115   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9116                                      FoundLHS, FoundRHS) ||
9117          // ~x < ~y --> x > y
9118          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9119                                      getNotSCEV(FoundRHS),
9120                                      getNotSCEV(FoundLHS));
9121 }
9122 
9123 
9124 /// If Expr computes ~A, return A else return nullptr
9125 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9126   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9127   if (!Add || Add->getNumOperands() != 2 ||
9128       !Add->getOperand(0)->isAllOnesValue())
9129     return nullptr;
9130 
9131   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9132   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9133       !AddRHS->getOperand(0)->isAllOnesValue())
9134     return nullptr;
9135 
9136   return AddRHS->getOperand(1);
9137 }
9138 
9139 
9140 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9141 template<typename MaxExprType>
9142 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9143                               const SCEV *Candidate) {
9144   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9145   if (!MaxExpr) return false;
9146 
9147   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9148 }
9149 
9150 
9151 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9152 template<typename MaxExprType>
9153 static bool IsMinConsistingOf(ScalarEvolution &SE,
9154                               const SCEV *MaybeMinExpr,
9155                               const SCEV *Candidate) {
9156   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9157   if (!MaybeMaxExpr)
9158     return false;
9159 
9160   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9161 }
9162 
9163 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9164                                            ICmpInst::Predicate Pred,
9165                                            const SCEV *LHS, const SCEV *RHS) {
9166 
9167   // If both sides are affine addrecs for the same loop, with equal
9168   // steps, and we know the recurrences don't wrap, then we only
9169   // need to check the predicate on the starting values.
9170 
9171   if (!ICmpInst::isRelational(Pred))
9172     return false;
9173 
9174   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9175   if (!LAR)
9176     return false;
9177   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9178   if (!RAR)
9179     return false;
9180   if (LAR->getLoop() != RAR->getLoop())
9181     return false;
9182   if (!LAR->isAffine() || !RAR->isAffine())
9183     return false;
9184 
9185   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9186     return false;
9187 
9188   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9189                          SCEV::FlagNSW : SCEV::FlagNUW;
9190   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9191     return false;
9192 
9193   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9194 }
9195 
9196 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9197 /// expression?
9198 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9199                                         ICmpInst::Predicate Pred,
9200                                         const SCEV *LHS, const SCEV *RHS) {
9201   switch (Pred) {
9202   default:
9203     return false;
9204 
9205   case ICmpInst::ICMP_SGE:
9206     std::swap(LHS, RHS);
9207     LLVM_FALLTHROUGH;
9208   case ICmpInst::ICMP_SLE:
9209     return
9210       // min(A, ...) <= A
9211       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9212       // A <= max(A, ...)
9213       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9214 
9215   case ICmpInst::ICMP_UGE:
9216     std::swap(LHS, RHS);
9217     LLVM_FALLTHROUGH;
9218   case ICmpInst::ICMP_ULE:
9219     return
9220       // min(A, ...) <= A
9221       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9222       // A <= max(A, ...)
9223       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9224   }
9225 
9226   llvm_unreachable("covered switch fell through?!");
9227 }
9228 
9229 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9230                                              const SCEV *LHS, const SCEV *RHS,
9231                                              const SCEV *FoundLHS,
9232                                              const SCEV *FoundRHS,
9233                                              unsigned Depth) {
9234   assert(getTypeSizeInBits(LHS->getType()) ==
9235              getTypeSizeInBits(RHS->getType()) &&
9236          "LHS and RHS have different sizes?");
9237   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9238              getTypeSizeInBits(FoundRHS->getType()) &&
9239          "FoundLHS and FoundRHS have different sizes?");
9240   // We want to avoid hurting the compile time with analysis of too big trees.
9241   if (Depth > MaxSCEVOperationsImplicationDepth)
9242     return false;
9243   // We only want to work with ICMP_SGT comparison so far.
9244   // TODO: Extend to ICMP_UGT?
9245   if (Pred == ICmpInst::ICMP_SLT) {
9246     Pred = ICmpInst::ICMP_SGT;
9247     std::swap(LHS, RHS);
9248     std::swap(FoundLHS, FoundRHS);
9249   }
9250   if (Pred != ICmpInst::ICMP_SGT)
9251     return false;
9252 
9253   auto GetOpFromSExt = [&](const SCEV *S) {
9254     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9255       return Ext->getOperand();
9256     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9257     // the constant in some cases.
9258     return S;
9259   };
9260 
9261   // Acquire values from extensions.
9262   auto *OrigFoundLHS = FoundLHS;
9263   LHS = GetOpFromSExt(LHS);
9264   FoundLHS = GetOpFromSExt(FoundLHS);
9265 
9266   // Is the SGT predicate can be proved trivially or using the found context.
9267   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9268     return isKnownViaSimpleReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9269            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9270                                   FoundRHS, Depth + 1);
9271   };
9272 
9273   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9274     // We want to avoid creation of any new non-constant SCEV. Since we are
9275     // going to compare the operands to RHS, we should be certain that we don't
9276     // need any size extensions for this. So let's decline all cases when the
9277     // sizes of types of LHS and RHS do not match.
9278     // TODO: Maybe try to get RHS from sext to catch more cases?
9279     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9280       return false;
9281 
9282     // Should not overflow.
9283     if (!LHSAddExpr->hasNoSignedWrap())
9284       return false;
9285 
9286     auto *LL = LHSAddExpr->getOperand(0);
9287     auto *LR = LHSAddExpr->getOperand(1);
9288     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9289 
9290     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9291     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9292       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9293     };
9294     // Try to prove the following rule:
9295     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9296     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9297     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9298       return true;
9299   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9300     Value *LL, *LR;
9301     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9302     using namespace llvm::PatternMatch;
9303     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9304       // Rules for division.
9305       // We are going to perform some comparisons with Denominator and its
9306       // derivative expressions. In general case, creating a SCEV for it may
9307       // lead to a complex analysis of the entire graph, and in particular it
9308       // can request trip count recalculation for the same loop. This would
9309       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9310       // this, we only want to create SCEVs that are constants in this section.
9311       // So we bail if Denominator is not a constant.
9312       if (!isa<ConstantInt>(LR))
9313         return false;
9314 
9315       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9316 
9317       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9318       // then a SCEV for the numerator already exists and matches with FoundLHS.
9319       auto *Numerator = getExistingSCEV(LL);
9320       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9321         return false;
9322 
9323       // Make sure that the numerator matches with FoundLHS and the denominator
9324       // is positive.
9325       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9326         return false;
9327 
9328       auto *DTy = Denominator->getType();
9329       auto *FRHSTy = FoundRHS->getType();
9330       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9331         // One of types is a pointer and another one is not. We cannot extend
9332         // them properly to a wider type, so let us just reject this case.
9333         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9334         // to avoid this check.
9335         return false;
9336 
9337       // Given that:
9338       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9339       auto *WTy = getWiderType(DTy, FRHSTy);
9340       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9341       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9342 
9343       // Try to prove the following rule:
9344       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9345       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9346       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9347       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9348       if (isKnownNonPositive(RHS) &&
9349           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9350         return true;
9351 
9352       // Try to prove the following rule:
9353       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9354       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9355       // If we divide it by Denominator > 2, then:
9356       // 1. If FoundLHS is negative, then the result is 0.
9357       // 2. If FoundLHS is non-negative, then the result is non-negative.
9358       // Anyways, the result is non-negative.
9359       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9360       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9361       if (isKnownNegative(RHS) &&
9362           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9363         return true;
9364     }
9365   }
9366 
9367   return false;
9368 }
9369 
9370 bool
9371 ScalarEvolution::isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
9372                                            const SCEV *LHS, const SCEV *RHS) {
9373   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9374          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9375          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9376          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9377 }
9378 
9379 bool
9380 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9381                                              const SCEV *LHS, const SCEV *RHS,
9382                                              const SCEV *FoundLHS,
9383                                              const SCEV *FoundRHS) {
9384   switch (Pred) {
9385   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9386   case ICmpInst::ICMP_EQ:
9387   case ICmpInst::ICMP_NE:
9388     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9389       return true;
9390     break;
9391   case ICmpInst::ICMP_SLT:
9392   case ICmpInst::ICMP_SLE:
9393     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9394         isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9395       return true;
9396     break;
9397   case ICmpInst::ICMP_SGT:
9398   case ICmpInst::ICMP_SGE:
9399     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9400         isKnownViaSimpleReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9401       return true;
9402     break;
9403   case ICmpInst::ICMP_ULT:
9404   case ICmpInst::ICMP_ULE:
9405     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9406         isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9407       return true;
9408     break;
9409   case ICmpInst::ICMP_UGT:
9410   case ICmpInst::ICMP_UGE:
9411     if (isKnownViaSimpleReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9412         isKnownViaSimpleReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9413       return true;
9414     break;
9415   }
9416 
9417   // Maybe it can be proved via operations?
9418   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9419     return true;
9420 
9421   return false;
9422 }
9423 
9424 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
9425                                                      const SCEV *LHS,
9426                                                      const SCEV *RHS,
9427                                                      const SCEV *FoundLHS,
9428                                                      const SCEV *FoundRHS) {
9429   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
9430     // The restriction on `FoundRHS` be lifted easily -- it exists only to
9431     // reduce the compile time impact of this optimization.
9432     return false;
9433 
9434   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
9435   if (!Addend)
9436     return false;
9437 
9438   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
9439 
9440   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
9441   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
9442   ConstantRange FoundLHSRange =
9443       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
9444 
9445   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
9446   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
9447 
9448   // We can also compute the range of values for `LHS` that satisfy the
9449   // consequent, "`LHS` `Pred` `RHS`":
9450   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
9451   ConstantRange SatisfyingLHSRange =
9452       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
9453 
9454   // The antecedent implies the consequent if every value of `LHS` that
9455   // satisfies the antecedent also satisfies the consequent.
9456   return SatisfyingLHSRange.contains(LHSRange);
9457 }
9458 
9459 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
9460                                          bool IsSigned, bool NoWrap) {
9461   assert(isKnownPositive(Stride) && "Positive stride expected!");
9462 
9463   if (NoWrap) return false;
9464 
9465   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9466   const SCEV *One = getOne(Stride->getType());
9467 
9468   if (IsSigned) {
9469     APInt MaxRHS = getSignedRangeMax(RHS);
9470     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
9471     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9472 
9473     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
9474     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
9475   }
9476 
9477   APInt MaxRHS = getUnsignedRangeMax(RHS);
9478   APInt MaxValue = APInt::getMaxValue(BitWidth);
9479   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9480 
9481   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
9482   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
9483 }
9484 
9485 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
9486                                          bool IsSigned, bool NoWrap) {
9487   if (NoWrap) return false;
9488 
9489   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9490   const SCEV *One = getOne(Stride->getType());
9491 
9492   if (IsSigned) {
9493     APInt MinRHS = getSignedRangeMin(RHS);
9494     APInt MinValue = APInt::getSignedMinValue(BitWidth);
9495     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
9496 
9497     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
9498     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
9499   }
9500 
9501   APInt MinRHS = getUnsignedRangeMin(RHS);
9502   APInt MinValue = APInt::getMinValue(BitWidth);
9503   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
9504 
9505   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
9506   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
9507 }
9508 
9509 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
9510                                             bool Equality) {
9511   const SCEV *One = getOne(Step->getType());
9512   Delta = Equality ? getAddExpr(Delta, Step)
9513                    : getAddExpr(Delta, getMinusSCEV(Step, One));
9514   return getUDivExpr(Delta, Step);
9515 }
9516 
9517 ScalarEvolution::ExitLimit
9518 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
9519                                   const Loop *L, bool IsSigned,
9520                                   bool ControlsExit, bool AllowPredicates) {
9521   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9522   // We handle only IV < Invariant
9523   if (!isLoopInvariant(RHS, L))
9524     return getCouldNotCompute();
9525 
9526   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9527   bool PredicatedIV = false;
9528 
9529   if (!IV && AllowPredicates) {
9530     // Try to make this an AddRec using runtime tests, in the first X
9531     // iterations of this loop, where X is the SCEV expression found by the
9532     // algorithm below.
9533     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9534     PredicatedIV = true;
9535   }
9536 
9537   // Avoid weird loops
9538   if (!IV || IV->getLoop() != L || !IV->isAffine())
9539     return getCouldNotCompute();
9540 
9541   bool NoWrap = ControlsExit &&
9542                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9543 
9544   const SCEV *Stride = IV->getStepRecurrence(*this);
9545 
9546   bool PositiveStride = isKnownPositive(Stride);
9547 
9548   // Avoid negative or zero stride values.
9549   if (!PositiveStride) {
9550     // We can compute the correct backedge taken count for loops with unknown
9551     // strides if we can prove that the loop is not an infinite loop with side
9552     // effects. Here's the loop structure we are trying to handle -
9553     //
9554     // i = start
9555     // do {
9556     //   A[i] = i;
9557     //   i += s;
9558     // } while (i < end);
9559     //
9560     // The backedge taken count for such loops is evaluated as -
9561     // (max(end, start + stride) - start - 1) /u stride
9562     //
9563     // The additional preconditions that we need to check to prove correctness
9564     // of the above formula is as follows -
9565     //
9566     // a) IV is either nuw or nsw depending upon signedness (indicated by the
9567     //    NoWrap flag).
9568     // b) loop is single exit with no side effects.
9569     //
9570     //
9571     // Precondition a) implies that if the stride is negative, this is a single
9572     // trip loop. The backedge taken count formula reduces to zero in this case.
9573     //
9574     // Precondition b) implies that the unknown stride cannot be zero otherwise
9575     // we have UB.
9576     //
9577     // The positive stride case is the same as isKnownPositive(Stride) returning
9578     // true (original behavior of the function).
9579     //
9580     // We want to make sure that the stride is truly unknown as there are edge
9581     // cases where ScalarEvolution propagates no wrap flags to the
9582     // post-increment/decrement IV even though the increment/decrement operation
9583     // itself is wrapping. The computed backedge taken count may be wrong in
9584     // such cases. This is prevented by checking that the stride is not known to
9585     // be either positive or non-positive. For example, no wrap flags are
9586     // propagated to the post-increment IV of this loop with a trip count of 2 -
9587     //
9588     // unsigned char i;
9589     // for(i=127; i<128; i+=129)
9590     //   A[i] = i;
9591     //
9592     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
9593         !loopHasNoSideEffects(L))
9594       return getCouldNotCompute();
9595 
9596   } else if (!Stride->isOne() &&
9597              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
9598     // Avoid proven overflow cases: this will ensure that the backedge taken
9599     // count will not generate any unsigned overflow. Relaxed no-overflow
9600     // conditions exploit NoWrapFlags, allowing to optimize in presence of
9601     // undefined behaviors like the case of C language.
9602     return getCouldNotCompute();
9603 
9604   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
9605                                       : ICmpInst::ICMP_ULT;
9606   const SCEV *Start = IV->getStart();
9607   const SCEV *End = RHS;
9608   // If the backedge is taken at least once, then it will be taken
9609   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
9610   // is the LHS value of the less-than comparison the first time it is evaluated
9611   // and End is the RHS.
9612   const SCEV *BECountIfBackedgeTaken =
9613     computeBECount(getMinusSCEV(End, Start), Stride, false);
9614   // If the loop entry is guarded by the result of the backedge test of the
9615   // first loop iteration, then we know the backedge will be taken at least
9616   // once and so the backedge taken count is as above. If not then we use the
9617   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
9618   // as if the backedge is taken at least once max(End,Start) is End and so the
9619   // result is as above, and if not max(End,Start) is Start so we get a backedge
9620   // count of zero.
9621   const SCEV *BECount;
9622   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
9623     BECount = BECountIfBackedgeTaken;
9624   else {
9625     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
9626     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
9627   }
9628 
9629   const SCEV *MaxBECount;
9630   bool MaxOrZero = false;
9631   if (isa<SCEVConstant>(BECount))
9632     MaxBECount = BECount;
9633   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
9634     // If we know exactly how many times the backedge will be taken if it's
9635     // taken at least once, then the backedge count will either be that or
9636     // zero.
9637     MaxBECount = BECountIfBackedgeTaken;
9638     MaxOrZero = true;
9639   } else {
9640     // Calculate the maximum backedge count based on the range of values
9641     // permitted by Start, End, and Stride.
9642     APInt MinStart = IsSigned ? getSignedRangeMin(Start)
9643                               : getUnsignedRangeMin(Start);
9644 
9645     unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9646 
9647     APInt StrideForMaxBECount;
9648 
9649     if (PositiveStride)
9650       StrideForMaxBECount =
9651         IsSigned ? getSignedRangeMin(Stride)
9652                  : getUnsignedRangeMin(Stride);
9653     else
9654       // Using a stride of 1 is safe when computing max backedge taken count for
9655       // a loop with unknown stride.
9656       StrideForMaxBECount = APInt(BitWidth, 1, IsSigned);
9657 
9658     APInt Limit =
9659       IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1)
9660                : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1);
9661 
9662     // Although End can be a MAX expression we estimate MaxEnd considering only
9663     // the case End = RHS. This is safe because in the other case (End - Start)
9664     // is zero, leading to a zero maximum backedge taken count.
9665     APInt MaxEnd =
9666       IsSigned ? APIntOps::smin(getSignedRangeMax(RHS), Limit)
9667                : APIntOps::umin(getUnsignedRangeMax(RHS), Limit);
9668 
9669     MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
9670                                 getConstant(StrideForMaxBECount), false);
9671   }
9672 
9673   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
9674       !isa<SCEVCouldNotCompute>(BECount))
9675     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
9676 
9677   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
9678 }
9679 
9680 ScalarEvolution::ExitLimit
9681 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
9682                                      const Loop *L, bool IsSigned,
9683                                      bool ControlsExit, bool AllowPredicates) {
9684   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9685   // We handle only IV > Invariant
9686   if (!isLoopInvariant(RHS, L))
9687     return getCouldNotCompute();
9688 
9689   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
9690   if (!IV && AllowPredicates)
9691     // Try to make this an AddRec using runtime tests, in the first X
9692     // iterations of this loop, where X is the SCEV expression found by the
9693     // algorithm below.
9694     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
9695 
9696   // Avoid weird loops
9697   if (!IV || IV->getLoop() != L || !IV->isAffine())
9698     return getCouldNotCompute();
9699 
9700   bool NoWrap = ControlsExit &&
9701                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
9702 
9703   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
9704 
9705   // Avoid negative or zero stride values
9706   if (!isKnownPositive(Stride))
9707     return getCouldNotCompute();
9708 
9709   // Avoid proven overflow cases: this will ensure that the backedge taken count
9710   // will not generate any unsigned overflow. Relaxed no-overflow conditions
9711   // exploit NoWrapFlags, allowing to optimize in presence of undefined
9712   // behaviors like the case of C language.
9713   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
9714     return getCouldNotCompute();
9715 
9716   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
9717                                       : ICmpInst::ICMP_UGT;
9718 
9719   const SCEV *Start = IV->getStart();
9720   const SCEV *End = RHS;
9721   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
9722     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
9723 
9724   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
9725 
9726   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
9727                             : getUnsignedRangeMax(Start);
9728 
9729   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
9730                              : getUnsignedRangeMin(Stride);
9731 
9732   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
9733   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
9734                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
9735 
9736   // Although End can be a MIN expression we estimate MinEnd considering only
9737   // the case End = RHS. This is safe because in the other case (Start - End)
9738   // is zero, leading to a zero maximum backedge taken count.
9739   APInt MinEnd =
9740     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
9741              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
9742 
9743 
9744   const SCEV *MaxBECount = getCouldNotCompute();
9745   if (isa<SCEVConstant>(BECount))
9746     MaxBECount = BECount;
9747   else
9748     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
9749                                 getConstant(MinStride), false);
9750 
9751   if (isa<SCEVCouldNotCompute>(MaxBECount))
9752     MaxBECount = BECount;
9753 
9754   return ExitLimit(BECount, MaxBECount, false, Predicates);
9755 }
9756 
9757 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
9758                                                     ScalarEvolution &SE) const {
9759   if (Range.isFullSet())  // Infinite loop.
9760     return SE.getCouldNotCompute();
9761 
9762   // If the start is a non-zero constant, shift the range to simplify things.
9763   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
9764     if (!SC->getValue()->isZero()) {
9765       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
9766       Operands[0] = SE.getZero(SC->getType());
9767       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
9768                                              getNoWrapFlags(FlagNW));
9769       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
9770         return ShiftedAddRec->getNumIterationsInRange(
9771             Range.subtract(SC->getAPInt()), SE);
9772       // This is strange and shouldn't happen.
9773       return SE.getCouldNotCompute();
9774     }
9775 
9776   // The only time we can solve this is when we have all constant indices.
9777   // Otherwise, we cannot determine the overflow conditions.
9778   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
9779     return SE.getCouldNotCompute();
9780 
9781   // Okay at this point we know that all elements of the chrec are constants and
9782   // that the start element is zero.
9783 
9784   // First check to see if the range contains zero.  If not, the first
9785   // iteration exits.
9786   unsigned BitWidth = SE.getTypeSizeInBits(getType());
9787   if (!Range.contains(APInt(BitWidth, 0)))
9788     return SE.getZero(getType());
9789 
9790   if (isAffine()) {
9791     // If this is an affine expression then we have this situation:
9792     //   Solve {0,+,A} in Range  ===  Ax in Range
9793 
9794     // We know that zero is in the range.  If A is positive then we know that
9795     // the upper value of the range must be the first possible exit value.
9796     // If A is negative then the lower of the range is the last possible loop
9797     // value.  Also note that we already checked for a full range.
9798     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
9799     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
9800 
9801     // The exit value should be (End+A)/A.
9802     APInt ExitVal = (End + A).udiv(A);
9803     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
9804 
9805     // Evaluate at the exit value.  If we really did fall out of the valid
9806     // range, then we computed our trip count, otherwise wrap around or other
9807     // things must have happened.
9808     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
9809     if (Range.contains(Val->getValue()))
9810       return SE.getCouldNotCompute();  // Something strange happened
9811 
9812     // Ensure that the previous value is in the range.  This is a sanity check.
9813     assert(Range.contains(
9814            EvaluateConstantChrecAtConstant(this,
9815            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
9816            "Linear scev computation is off in a bad way!");
9817     return SE.getConstant(ExitValue);
9818   } else if (isQuadratic()) {
9819     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
9820     // quadratic equation to solve it.  To do this, we must frame our problem in
9821     // terms of figuring out when zero is crossed, instead of when
9822     // Range.getUpper() is crossed.
9823     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
9824     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
9825     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
9826 
9827     // Next, solve the constructed addrec
9828     if (auto Roots =
9829             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
9830       const SCEVConstant *R1 = Roots->first;
9831       const SCEVConstant *R2 = Roots->second;
9832       // Pick the smallest positive root value.
9833       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
9834               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
9835         if (!CB->getZExtValue())
9836           std::swap(R1, R2); // R1 is the minimum root now.
9837 
9838         // Make sure the root is not off by one.  The returned iteration should
9839         // not be in the range, but the previous one should be.  When solving
9840         // for "X*X < 5", for example, we should not return a root of 2.
9841         ConstantInt *R1Val =
9842             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
9843         if (Range.contains(R1Val->getValue())) {
9844           // The next iteration must be out of the range...
9845           ConstantInt *NextVal =
9846               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
9847 
9848           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9849           if (!Range.contains(R1Val->getValue()))
9850             return SE.getConstant(NextVal);
9851           return SE.getCouldNotCompute(); // Something strange happened
9852         }
9853 
9854         // If R1 was not in the range, then it is a good return value.  Make
9855         // sure that R1-1 WAS in the range though, just in case.
9856         ConstantInt *NextVal =
9857             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
9858         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
9859         if (Range.contains(R1Val->getValue()))
9860           return R1;
9861         return SE.getCouldNotCompute(); // Something strange happened
9862       }
9863     }
9864   }
9865 
9866   return SE.getCouldNotCompute();
9867 }
9868 
9869 // Return true when S contains at least an undef value.
9870 static inline bool containsUndefs(const SCEV *S) {
9871   return SCEVExprContains(S, [](const SCEV *S) {
9872     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
9873       return isa<UndefValue>(SU->getValue());
9874     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
9875       return isa<UndefValue>(SC->getValue());
9876     return false;
9877   });
9878 }
9879 
9880 namespace {
9881 // Collect all steps of SCEV expressions.
9882 struct SCEVCollectStrides {
9883   ScalarEvolution &SE;
9884   SmallVectorImpl<const SCEV *> &Strides;
9885 
9886   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
9887       : SE(SE), Strides(S) {}
9888 
9889   bool follow(const SCEV *S) {
9890     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
9891       Strides.push_back(AR->getStepRecurrence(SE));
9892     return true;
9893   }
9894   bool isDone() const { return false; }
9895 };
9896 
9897 // Collect all SCEVUnknown and SCEVMulExpr expressions.
9898 struct SCEVCollectTerms {
9899   SmallVectorImpl<const SCEV *> &Terms;
9900 
9901   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
9902       : Terms(T) {}
9903 
9904   bool follow(const SCEV *S) {
9905     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
9906         isa<SCEVSignExtendExpr>(S)) {
9907       if (!containsUndefs(S))
9908         Terms.push_back(S);
9909 
9910       // Stop recursion: once we collected a term, do not walk its operands.
9911       return false;
9912     }
9913 
9914     // Keep looking.
9915     return true;
9916   }
9917   bool isDone() const { return false; }
9918 };
9919 
9920 // Check if a SCEV contains an AddRecExpr.
9921 struct SCEVHasAddRec {
9922   bool &ContainsAddRec;
9923 
9924   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9925    ContainsAddRec = false;
9926   }
9927 
9928   bool follow(const SCEV *S) {
9929     if (isa<SCEVAddRecExpr>(S)) {
9930       ContainsAddRec = true;
9931 
9932       // Stop recursion: once we collected a term, do not walk its operands.
9933       return false;
9934     }
9935 
9936     // Keep looking.
9937     return true;
9938   }
9939   bool isDone() const { return false; }
9940 };
9941 
9942 // Find factors that are multiplied with an expression that (possibly as a
9943 // subexpression) contains an AddRecExpr. In the expression:
9944 //
9945 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
9946 //
9947 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9948 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9949 // parameters as they form a product with an induction variable.
9950 //
9951 // This collector expects all array size parameters to be in the same MulExpr.
9952 // It might be necessary to later add support for collecting parameters that are
9953 // spread over different nested MulExpr.
9954 struct SCEVCollectAddRecMultiplies {
9955   SmallVectorImpl<const SCEV *> &Terms;
9956   ScalarEvolution &SE;
9957 
9958   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9959       : Terms(T), SE(SE) {}
9960 
9961   bool follow(const SCEV *S) {
9962     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9963       bool HasAddRec = false;
9964       SmallVector<const SCEV *, 0> Operands;
9965       for (auto Op : Mul->operands()) {
9966         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
9967         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
9968           Operands.push_back(Op);
9969         } else if (Unknown) {
9970           HasAddRec = true;
9971         } else {
9972           bool ContainsAddRec;
9973           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9974           visitAll(Op, ContiansAddRec);
9975           HasAddRec |= ContainsAddRec;
9976         }
9977       }
9978       if (Operands.size() == 0)
9979         return true;
9980 
9981       if (!HasAddRec)
9982         return false;
9983 
9984       Terms.push_back(SE.getMulExpr(Operands));
9985       // Stop recursion: once we collected a term, do not walk its operands.
9986       return false;
9987     }
9988 
9989     // Keep looking.
9990     return true;
9991   }
9992   bool isDone() const { return false; }
9993 };
9994 }
9995 
9996 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9997 /// two places:
9998 ///   1) The strides of AddRec expressions.
9999 ///   2) Unknowns that are multiplied with AddRec expressions.
10000 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10001     SmallVectorImpl<const SCEV *> &Terms) {
10002   SmallVector<const SCEV *, 4> Strides;
10003   SCEVCollectStrides StrideCollector(*this, Strides);
10004   visitAll(Expr, StrideCollector);
10005 
10006   DEBUG({
10007       dbgs() << "Strides:\n";
10008       for (const SCEV *S : Strides)
10009         dbgs() << *S << "\n";
10010     });
10011 
10012   for (const SCEV *S : Strides) {
10013     SCEVCollectTerms TermCollector(Terms);
10014     visitAll(S, TermCollector);
10015   }
10016 
10017   DEBUG({
10018       dbgs() << "Terms:\n";
10019       for (const SCEV *T : Terms)
10020         dbgs() << *T << "\n";
10021     });
10022 
10023   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10024   visitAll(Expr, MulCollector);
10025 }
10026 
10027 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10028                                    SmallVectorImpl<const SCEV *> &Terms,
10029                                    SmallVectorImpl<const SCEV *> &Sizes) {
10030   int Last = Terms.size() - 1;
10031   const SCEV *Step = Terms[Last];
10032 
10033   // End of recursion.
10034   if (Last == 0) {
10035     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10036       SmallVector<const SCEV *, 2> Qs;
10037       for (const SCEV *Op : M->operands())
10038         if (!isa<SCEVConstant>(Op))
10039           Qs.push_back(Op);
10040 
10041       Step = SE.getMulExpr(Qs);
10042     }
10043 
10044     Sizes.push_back(Step);
10045     return true;
10046   }
10047 
10048   for (const SCEV *&Term : Terms) {
10049     // Normalize the terms before the next call to findArrayDimensionsRec.
10050     const SCEV *Q, *R;
10051     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10052 
10053     // Bail out when GCD does not evenly divide one of the terms.
10054     if (!R->isZero())
10055       return false;
10056 
10057     Term = Q;
10058   }
10059 
10060   // Remove all SCEVConstants.
10061   Terms.erase(
10062       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10063       Terms.end());
10064 
10065   if (Terms.size() > 0)
10066     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10067       return false;
10068 
10069   Sizes.push_back(Step);
10070   return true;
10071 }
10072 
10073 
10074 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10075 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10076   for (const SCEV *T : Terms)
10077     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10078       return true;
10079   return false;
10080 }
10081 
10082 // Return the number of product terms in S.
10083 static inline int numberOfTerms(const SCEV *S) {
10084   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10085     return Expr->getNumOperands();
10086   return 1;
10087 }
10088 
10089 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10090   if (isa<SCEVConstant>(T))
10091     return nullptr;
10092 
10093   if (isa<SCEVUnknown>(T))
10094     return T;
10095 
10096   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10097     SmallVector<const SCEV *, 2> Factors;
10098     for (const SCEV *Op : M->operands())
10099       if (!isa<SCEVConstant>(Op))
10100         Factors.push_back(Op);
10101 
10102     return SE.getMulExpr(Factors);
10103   }
10104 
10105   return T;
10106 }
10107 
10108 /// Return the size of an element read or written by Inst.
10109 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10110   Type *Ty;
10111   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10112     Ty = Store->getValueOperand()->getType();
10113   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10114     Ty = Load->getType();
10115   else
10116     return nullptr;
10117 
10118   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10119   return getSizeOfExpr(ETy, Ty);
10120 }
10121 
10122 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10123                                           SmallVectorImpl<const SCEV *> &Sizes,
10124                                           const SCEV *ElementSize) {
10125   if (Terms.size() < 1 || !ElementSize)
10126     return;
10127 
10128   // Early return when Terms do not contain parameters: we do not delinearize
10129   // non parametric SCEVs.
10130   if (!containsParameters(Terms))
10131     return;
10132 
10133   DEBUG({
10134       dbgs() << "Terms:\n";
10135       for (const SCEV *T : Terms)
10136         dbgs() << *T << "\n";
10137     });
10138 
10139   // Remove duplicates.
10140   array_pod_sort(Terms.begin(), Terms.end());
10141   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10142 
10143   // Put larger terms first.
10144   std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10145     return numberOfTerms(LHS) > numberOfTerms(RHS);
10146   });
10147 
10148   // Try to divide all terms by the element size. If term is not divisible by
10149   // element size, proceed with the original term.
10150   for (const SCEV *&Term : Terms) {
10151     const SCEV *Q, *R;
10152     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10153     if (!Q->isZero())
10154       Term = Q;
10155   }
10156 
10157   SmallVector<const SCEV *, 4> NewTerms;
10158 
10159   // Remove constant factors.
10160   for (const SCEV *T : Terms)
10161     if (const SCEV *NewT = removeConstantFactors(*this, T))
10162       NewTerms.push_back(NewT);
10163 
10164   DEBUG({
10165       dbgs() << "Terms after sorting:\n";
10166       for (const SCEV *T : NewTerms)
10167         dbgs() << *T << "\n";
10168     });
10169 
10170   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10171     Sizes.clear();
10172     return;
10173   }
10174 
10175   // The last element to be pushed into Sizes is the size of an element.
10176   Sizes.push_back(ElementSize);
10177 
10178   DEBUG({
10179       dbgs() << "Sizes:\n";
10180       for (const SCEV *S : Sizes)
10181         dbgs() << *S << "\n";
10182     });
10183 }
10184 
10185 void ScalarEvolution::computeAccessFunctions(
10186     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10187     SmallVectorImpl<const SCEV *> &Sizes) {
10188 
10189   // Early exit in case this SCEV is not an affine multivariate function.
10190   if (Sizes.empty())
10191     return;
10192 
10193   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10194     if (!AR->isAffine())
10195       return;
10196 
10197   const SCEV *Res = Expr;
10198   int Last = Sizes.size() - 1;
10199   for (int i = Last; i >= 0; i--) {
10200     const SCEV *Q, *R;
10201     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10202 
10203     DEBUG({
10204         dbgs() << "Res: " << *Res << "\n";
10205         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10206         dbgs() << "Res divided by Sizes[i]:\n";
10207         dbgs() << "Quotient: " << *Q << "\n";
10208         dbgs() << "Remainder: " << *R << "\n";
10209       });
10210 
10211     Res = Q;
10212 
10213     // Do not record the last subscript corresponding to the size of elements in
10214     // the array.
10215     if (i == Last) {
10216 
10217       // Bail out if the remainder is too complex.
10218       if (isa<SCEVAddRecExpr>(R)) {
10219         Subscripts.clear();
10220         Sizes.clear();
10221         return;
10222       }
10223 
10224       continue;
10225     }
10226 
10227     // Record the access function for the current subscript.
10228     Subscripts.push_back(R);
10229   }
10230 
10231   // Also push in last position the remainder of the last division: it will be
10232   // the access function of the innermost dimension.
10233   Subscripts.push_back(Res);
10234 
10235   std::reverse(Subscripts.begin(), Subscripts.end());
10236 
10237   DEBUG({
10238       dbgs() << "Subscripts:\n";
10239       for (const SCEV *S : Subscripts)
10240         dbgs() << *S << "\n";
10241     });
10242 }
10243 
10244 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10245 /// sizes of an array access. Returns the remainder of the delinearization that
10246 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10247 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10248 /// expressions in the stride and base of a SCEV corresponding to the
10249 /// computation of a GCD (greatest common divisor) of base and stride.  When
10250 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10251 ///
10252 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10253 ///
10254 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10255 ///
10256 ///    for (long i = 0; i < n; i++)
10257 ///      for (long j = 0; j < m; j++)
10258 ///        for (long k = 0; k < o; k++)
10259 ///          A[i][j][k] = 1.0;
10260 ///  }
10261 ///
10262 /// the delinearization input is the following AddRec SCEV:
10263 ///
10264 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10265 ///
10266 /// From this SCEV, we are able to say that the base offset of the access is %A
10267 /// because it appears as an offset that does not divide any of the strides in
10268 /// the loops:
10269 ///
10270 ///  CHECK: Base offset: %A
10271 ///
10272 /// and then SCEV->delinearize determines the size of some of the dimensions of
10273 /// the array as these are the multiples by which the strides are happening:
10274 ///
10275 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10276 ///
10277 /// Note that the outermost dimension remains of UnknownSize because there are
10278 /// no strides that would help identifying the size of the last dimension: when
10279 /// the array has been statically allocated, one could compute the size of that
10280 /// dimension by dividing the overall size of the array by the size of the known
10281 /// dimensions: %m * %o * 8.
10282 ///
10283 /// Finally delinearize provides the access functions for the array reference
10284 /// that does correspond to A[i][j][k] of the above C testcase:
10285 ///
10286 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10287 ///
10288 /// The testcases are checking the output of a function pass:
10289 /// DelinearizationPass that walks through all loads and stores of a function
10290 /// asking for the SCEV of the memory access with respect to all enclosing
10291 /// loops, calling SCEV->delinearize on that and printing the results.
10292 
10293 void ScalarEvolution::delinearize(const SCEV *Expr,
10294                                  SmallVectorImpl<const SCEV *> &Subscripts,
10295                                  SmallVectorImpl<const SCEV *> &Sizes,
10296                                  const SCEV *ElementSize) {
10297   // First step: collect parametric terms.
10298   SmallVector<const SCEV *, 4> Terms;
10299   collectParametricTerms(Expr, Terms);
10300 
10301   if (Terms.empty())
10302     return;
10303 
10304   // Second step: find subscript sizes.
10305   findArrayDimensions(Terms, Sizes, ElementSize);
10306 
10307   if (Sizes.empty())
10308     return;
10309 
10310   // Third step: compute the access functions for each subscript.
10311   computeAccessFunctions(Expr, Subscripts, Sizes);
10312 
10313   if (Subscripts.empty())
10314     return;
10315 
10316   DEBUG({
10317       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10318       dbgs() << "ArrayDecl[UnknownSize]";
10319       for (const SCEV *S : Sizes)
10320         dbgs() << "[" << *S << "]";
10321 
10322       dbgs() << "\nArrayRef";
10323       for (const SCEV *S : Subscripts)
10324         dbgs() << "[" << *S << "]";
10325       dbgs() << "\n";
10326     });
10327 }
10328 
10329 //===----------------------------------------------------------------------===//
10330 //                   SCEVCallbackVH Class Implementation
10331 //===----------------------------------------------------------------------===//
10332 
10333 void ScalarEvolution::SCEVCallbackVH::deleted() {
10334   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10335   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10336     SE->ConstantEvolutionLoopExitValue.erase(PN);
10337   SE->eraseValueFromMap(getValPtr());
10338   // this now dangles!
10339 }
10340 
10341 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10342   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10343 
10344   // Forget all the expressions associated with users of the old value,
10345   // so that future queries will recompute the expressions using the new
10346   // value.
10347   Value *Old = getValPtr();
10348   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10349   SmallPtrSet<User *, 8> Visited;
10350   while (!Worklist.empty()) {
10351     User *U = Worklist.pop_back_val();
10352     // Deleting the Old value will cause this to dangle. Postpone
10353     // that until everything else is done.
10354     if (U == Old)
10355       continue;
10356     if (!Visited.insert(U).second)
10357       continue;
10358     if (PHINode *PN = dyn_cast<PHINode>(U))
10359       SE->ConstantEvolutionLoopExitValue.erase(PN);
10360     SE->eraseValueFromMap(U);
10361     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10362   }
10363   // Delete the Old value.
10364   if (PHINode *PN = dyn_cast<PHINode>(Old))
10365     SE->ConstantEvolutionLoopExitValue.erase(PN);
10366   SE->eraseValueFromMap(Old);
10367   // this now dangles!
10368 }
10369 
10370 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10371   : CallbackVH(V), SE(se) {}
10372 
10373 //===----------------------------------------------------------------------===//
10374 //                   ScalarEvolution Class Implementation
10375 //===----------------------------------------------------------------------===//
10376 
10377 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
10378                                  AssumptionCache &AC, DominatorTree &DT,
10379                                  LoopInfo &LI)
10380     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
10381       CouldNotCompute(new SCEVCouldNotCompute()),
10382       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
10383       ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
10384       FirstUnknown(nullptr) {
10385 
10386   // To use guards for proving predicates, we need to scan every instruction in
10387   // relevant basic blocks, and not just terminators.  Doing this is a waste of
10388   // time if the IR does not actually contain any calls to
10389   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
10390   //
10391   // This pessimizes the case where a pass that preserves ScalarEvolution wants
10392   // to _add_ guards to the module when there weren't any before, and wants
10393   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
10394   // efficient in lieu of being smart in that rather obscure case.
10395 
10396   auto *GuardDecl = F.getParent()->getFunction(
10397       Intrinsic::getName(Intrinsic::experimental_guard));
10398   HasGuards = GuardDecl && !GuardDecl->use_empty();
10399 }
10400 
10401 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
10402     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
10403       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
10404       ValueExprMap(std::move(Arg.ValueExprMap)),
10405       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
10406       WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
10407       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
10408       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
10409       PredicatedBackedgeTakenCounts(
10410           std::move(Arg.PredicatedBackedgeTakenCounts)),
10411       ConstantEvolutionLoopExitValue(
10412           std::move(Arg.ConstantEvolutionLoopExitValue)),
10413       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
10414       LoopDispositions(std::move(Arg.LoopDispositions)),
10415       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
10416       BlockDispositions(std::move(Arg.BlockDispositions)),
10417       UnsignedRanges(std::move(Arg.UnsignedRanges)),
10418       SignedRanges(std::move(Arg.SignedRanges)),
10419       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
10420       UniquePreds(std::move(Arg.UniquePreds)),
10421       SCEVAllocator(std::move(Arg.SCEVAllocator)),
10422       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
10423       FirstUnknown(Arg.FirstUnknown) {
10424   Arg.FirstUnknown = nullptr;
10425 }
10426 
10427 ScalarEvolution::~ScalarEvolution() {
10428   // Iterate through all the SCEVUnknown instances and call their
10429   // destructors, so that they release their references to their values.
10430   for (SCEVUnknown *U = FirstUnknown; U;) {
10431     SCEVUnknown *Tmp = U;
10432     U = U->Next;
10433     Tmp->~SCEVUnknown();
10434   }
10435   FirstUnknown = nullptr;
10436 
10437   ExprValueMap.clear();
10438   ValueExprMap.clear();
10439   HasRecMap.clear();
10440 
10441   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
10442   // that a loop had multiple computable exits.
10443   for (auto &BTCI : BackedgeTakenCounts)
10444     BTCI.second.clear();
10445   for (auto &BTCI : PredicatedBackedgeTakenCounts)
10446     BTCI.second.clear();
10447 
10448   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
10449   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
10450   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
10451 }
10452 
10453 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
10454   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
10455 }
10456 
10457 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
10458                           const Loop *L) {
10459   // Print all inner loops first
10460   for (Loop *I : *L)
10461     PrintLoopInfo(OS, SE, I);
10462 
10463   OS << "Loop ";
10464   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10465   OS << ": ";
10466 
10467   SmallVector<BasicBlock *, 8> ExitBlocks;
10468   L->getExitBlocks(ExitBlocks);
10469   if (ExitBlocks.size() != 1)
10470     OS << "<multiple exits> ";
10471 
10472   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10473     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
10474   } else {
10475     OS << "Unpredictable backedge-taken count. ";
10476   }
10477 
10478   OS << "\n"
10479         "Loop ";
10480   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10481   OS << ": ";
10482 
10483   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
10484     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
10485     if (SE->isBackedgeTakenCountMaxOrZero(L))
10486       OS << ", actual taken count either this or zero.";
10487   } else {
10488     OS << "Unpredictable max backedge-taken count. ";
10489   }
10490 
10491   OS << "\n"
10492         "Loop ";
10493   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10494   OS << ": ";
10495 
10496   SCEVUnionPredicate Pred;
10497   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
10498   if (!isa<SCEVCouldNotCompute>(PBT)) {
10499     OS << "Predicated backedge-taken count is " << *PBT << "\n";
10500     OS << " Predicates:\n";
10501     Pred.print(OS, 4);
10502   } else {
10503     OS << "Unpredictable predicated backedge-taken count. ";
10504   }
10505   OS << "\n";
10506 
10507   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
10508     OS << "Loop ";
10509     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10510     OS << ": ";
10511     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
10512   }
10513 }
10514 
10515 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
10516   switch (LD) {
10517   case ScalarEvolution::LoopVariant:
10518     return "Variant";
10519   case ScalarEvolution::LoopInvariant:
10520     return "Invariant";
10521   case ScalarEvolution::LoopComputable:
10522     return "Computable";
10523   }
10524   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
10525 }
10526 
10527 void ScalarEvolution::print(raw_ostream &OS) const {
10528   // ScalarEvolution's implementation of the print method is to print
10529   // out SCEV values of all instructions that are interesting. Doing
10530   // this potentially causes it to create new SCEV objects though,
10531   // which technically conflicts with the const qualifier. This isn't
10532   // observable from outside the class though, so casting away the
10533   // const isn't dangerous.
10534   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10535 
10536   OS << "Classifying expressions for: ";
10537   F.printAsOperand(OS, /*PrintType=*/false);
10538   OS << "\n";
10539   for (Instruction &I : instructions(F))
10540     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
10541       OS << I << '\n';
10542       OS << "  -->  ";
10543       const SCEV *SV = SE.getSCEV(&I);
10544       SV->print(OS);
10545       if (!isa<SCEVCouldNotCompute>(SV)) {
10546         OS << " U: ";
10547         SE.getUnsignedRange(SV).print(OS);
10548         OS << " S: ";
10549         SE.getSignedRange(SV).print(OS);
10550       }
10551 
10552       const Loop *L = LI.getLoopFor(I.getParent());
10553 
10554       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
10555       if (AtUse != SV) {
10556         OS << "  -->  ";
10557         AtUse->print(OS);
10558         if (!isa<SCEVCouldNotCompute>(AtUse)) {
10559           OS << " U: ";
10560           SE.getUnsignedRange(AtUse).print(OS);
10561           OS << " S: ";
10562           SE.getSignedRange(AtUse).print(OS);
10563         }
10564       }
10565 
10566       if (L) {
10567         OS << "\t\t" "Exits: ";
10568         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
10569         if (!SE.isLoopInvariant(ExitValue, L)) {
10570           OS << "<<Unknown>>";
10571         } else {
10572           OS << *ExitValue;
10573         }
10574 
10575         bool First = true;
10576         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
10577           if (First) {
10578             OS << "\t\t" "LoopDispositions: { ";
10579             First = false;
10580           } else {
10581             OS << ", ";
10582           }
10583 
10584           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10585           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
10586         }
10587 
10588         for (auto *InnerL : depth_first(L)) {
10589           if (InnerL == L)
10590             continue;
10591           if (First) {
10592             OS << "\t\t" "LoopDispositions: { ";
10593             First = false;
10594           } else {
10595             OS << ", ";
10596           }
10597 
10598           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
10599           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
10600         }
10601 
10602         OS << " }";
10603       }
10604 
10605       OS << "\n";
10606     }
10607 
10608   OS << "Determining loop execution counts for: ";
10609   F.printAsOperand(OS, /*PrintType=*/false);
10610   OS << "\n";
10611   for (Loop *I : LI)
10612     PrintLoopInfo(OS, &SE, I);
10613 }
10614 
10615 ScalarEvolution::LoopDisposition
10616 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
10617   auto &Values = LoopDispositions[S];
10618   for (auto &V : Values) {
10619     if (V.getPointer() == L)
10620       return V.getInt();
10621   }
10622   Values.emplace_back(L, LoopVariant);
10623   LoopDisposition D = computeLoopDisposition(S, L);
10624   auto &Values2 = LoopDispositions[S];
10625   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10626     if (V.getPointer() == L) {
10627       V.setInt(D);
10628       break;
10629     }
10630   }
10631   return D;
10632 }
10633 
10634 ScalarEvolution::LoopDisposition
10635 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
10636   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10637   case scConstant:
10638     return LoopInvariant;
10639   case scTruncate:
10640   case scZeroExtend:
10641   case scSignExtend:
10642     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
10643   case scAddRecExpr: {
10644     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10645 
10646     // If L is the addrec's loop, it's computable.
10647     if (AR->getLoop() == L)
10648       return LoopComputable;
10649 
10650     // Add recurrences are never invariant in the function-body (null loop).
10651     if (!L)
10652       return LoopVariant;
10653 
10654     // This recurrence is variant w.r.t. L if L contains AR's loop.
10655     if (L->contains(AR->getLoop()))
10656       return LoopVariant;
10657 
10658     // This recurrence is invariant w.r.t. L if AR's loop contains L.
10659     if (AR->getLoop()->contains(L))
10660       return LoopInvariant;
10661 
10662     // This recurrence is variant w.r.t. L if any of its operands
10663     // are variant.
10664     for (auto *Op : AR->operands())
10665       if (!isLoopInvariant(Op, L))
10666         return LoopVariant;
10667 
10668     // Otherwise it's loop-invariant.
10669     return LoopInvariant;
10670   }
10671   case scAddExpr:
10672   case scMulExpr:
10673   case scUMaxExpr:
10674   case scSMaxExpr: {
10675     bool HasVarying = false;
10676     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
10677       LoopDisposition D = getLoopDisposition(Op, L);
10678       if (D == LoopVariant)
10679         return LoopVariant;
10680       if (D == LoopComputable)
10681         HasVarying = true;
10682     }
10683     return HasVarying ? LoopComputable : LoopInvariant;
10684   }
10685   case scUDivExpr: {
10686     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10687     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
10688     if (LD == LoopVariant)
10689       return LoopVariant;
10690     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
10691     if (RD == LoopVariant)
10692       return LoopVariant;
10693     return (LD == LoopInvariant && RD == LoopInvariant) ?
10694            LoopInvariant : LoopComputable;
10695   }
10696   case scUnknown:
10697     // All non-instruction values are loop invariant.  All instructions are loop
10698     // invariant if they are not contained in the specified loop.
10699     // Instructions are never considered invariant in the function body
10700     // (null loop) because they are defined within the "loop".
10701     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
10702       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
10703     return LoopInvariant;
10704   case scCouldNotCompute:
10705     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10706   }
10707   llvm_unreachable("Unknown SCEV kind!");
10708 }
10709 
10710 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
10711   return getLoopDisposition(S, L) == LoopInvariant;
10712 }
10713 
10714 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
10715   return getLoopDisposition(S, L) == LoopComputable;
10716 }
10717 
10718 ScalarEvolution::BlockDisposition
10719 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10720   auto &Values = BlockDispositions[S];
10721   for (auto &V : Values) {
10722     if (V.getPointer() == BB)
10723       return V.getInt();
10724   }
10725   Values.emplace_back(BB, DoesNotDominateBlock);
10726   BlockDisposition D = computeBlockDisposition(S, BB);
10727   auto &Values2 = BlockDispositions[S];
10728   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
10729     if (V.getPointer() == BB) {
10730       V.setInt(D);
10731       break;
10732     }
10733   }
10734   return D;
10735 }
10736 
10737 ScalarEvolution::BlockDisposition
10738 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
10739   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
10740   case scConstant:
10741     return ProperlyDominatesBlock;
10742   case scTruncate:
10743   case scZeroExtend:
10744   case scSignExtend:
10745     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
10746   case scAddRecExpr: {
10747     // This uses a "dominates" query instead of "properly dominates" query
10748     // to test for proper dominance too, because the instruction which
10749     // produces the addrec's value is a PHI, and a PHI effectively properly
10750     // dominates its entire containing block.
10751     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
10752     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
10753       return DoesNotDominateBlock;
10754 
10755     // Fall through into SCEVNAryExpr handling.
10756     LLVM_FALLTHROUGH;
10757   }
10758   case scAddExpr:
10759   case scMulExpr:
10760   case scUMaxExpr:
10761   case scSMaxExpr: {
10762     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
10763     bool Proper = true;
10764     for (const SCEV *NAryOp : NAry->operands()) {
10765       BlockDisposition D = getBlockDisposition(NAryOp, BB);
10766       if (D == DoesNotDominateBlock)
10767         return DoesNotDominateBlock;
10768       if (D == DominatesBlock)
10769         Proper = false;
10770     }
10771     return Proper ? ProperlyDominatesBlock : DominatesBlock;
10772   }
10773   case scUDivExpr: {
10774     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
10775     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
10776     BlockDisposition LD = getBlockDisposition(LHS, BB);
10777     if (LD == DoesNotDominateBlock)
10778       return DoesNotDominateBlock;
10779     BlockDisposition RD = getBlockDisposition(RHS, BB);
10780     if (RD == DoesNotDominateBlock)
10781       return DoesNotDominateBlock;
10782     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
10783       ProperlyDominatesBlock : DominatesBlock;
10784   }
10785   case scUnknown:
10786     if (Instruction *I =
10787           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
10788       if (I->getParent() == BB)
10789         return DominatesBlock;
10790       if (DT.properlyDominates(I->getParent(), BB))
10791         return ProperlyDominatesBlock;
10792       return DoesNotDominateBlock;
10793     }
10794     return ProperlyDominatesBlock;
10795   case scCouldNotCompute:
10796     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10797   }
10798   llvm_unreachable("Unknown SCEV kind!");
10799 }
10800 
10801 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
10802   return getBlockDisposition(S, BB) >= DominatesBlock;
10803 }
10804 
10805 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
10806   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
10807 }
10808 
10809 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
10810   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
10811 }
10812 
10813 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
10814   ValuesAtScopes.erase(S);
10815   LoopDispositions.erase(S);
10816   BlockDispositions.erase(S);
10817   UnsignedRanges.erase(S);
10818   SignedRanges.erase(S);
10819   ExprValueMap.erase(S);
10820   HasRecMap.erase(S);
10821   MinTrailingZerosCache.erase(S);
10822 
10823   for (auto I = PredicatedSCEVRewrites.begin();
10824        I != PredicatedSCEVRewrites.end();) {
10825     std::pair<const SCEV *, const Loop *> Entry = I->first;
10826     if (Entry.first == S)
10827       PredicatedSCEVRewrites.erase(I++);
10828     else
10829       ++I;
10830   }
10831 
10832   auto RemoveSCEVFromBackedgeMap =
10833       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
10834         for (auto I = Map.begin(), E = Map.end(); I != E;) {
10835           BackedgeTakenInfo &BEInfo = I->second;
10836           if (BEInfo.hasOperand(S, this)) {
10837             BEInfo.clear();
10838             Map.erase(I++);
10839           } else
10840             ++I;
10841         }
10842       };
10843 
10844   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
10845   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
10846 }
10847 
10848 void ScalarEvolution::verify() const {
10849   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
10850   ScalarEvolution SE2(F, TLI, AC, DT, LI);
10851 
10852   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
10853 
10854   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
10855   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
10856     const SCEV *visitConstant(const SCEVConstant *Constant) {
10857       return SE.getConstant(Constant->getAPInt());
10858     }
10859     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10860       return SE.getUnknown(Expr->getValue());
10861     }
10862 
10863     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
10864       return SE.getCouldNotCompute();
10865     }
10866     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
10867   };
10868 
10869   SCEVMapper SCM(SE2);
10870 
10871   while (!LoopStack.empty()) {
10872     auto *L = LoopStack.pop_back_val();
10873     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
10874 
10875     auto *CurBECount = SCM.visit(
10876         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
10877     auto *NewBECount = SE2.getBackedgeTakenCount(L);
10878 
10879     if (CurBECount == SE2.getCouldNotCompute() ||
10880         NewBECount == SE2.getCouldNotCompute()) {
10881       // NB! This situation is legal, but is very suspicious -- whatever pass
10882       // change the loop to make a trip count go from could not compute to
10883       // computable or vice-versa *should have* invalidated SCEV.  However, we
10884       // choose not to assert here (for now) since we don't want false
10885       // positives.
10886       continue;
10887     }
10888 
10889     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
10890       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
10891       // not propagate undef aggressively).  This means we can (and do) fail
10892       // verification in cases where a transform makes the trip count of a loop
10893       // go from "undef" to "undef+1" (say).  The transform is fine, since in
10894       // both cases the loop iterates "undef" times, but SCEV thinks we
10895       // increased the trip count of the loop by 1 incorrectly.
10896       continue;
10897     }
10898 
10899     if (SE.getTypeSizeInBits(CurBECount->getType()) >
10900         SE.getTypeSizeInBits(NewBECount->getType()))
10901       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
10902     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
10903              SE.getTypeSizeInBits(NewBECount->getType()))
10904       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
10905 
10906     auto *ConstantDelta =
10907         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
10908 
10909     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
10910       dbgs() << "Trip Count Changed!\n";
10911       dbgs() << "Old: " << *CurBECount << "\n";
10912       dbgs() << "New: " << *NewBECount << "\n";
10913       dbgs() << "Delta: " << *ConstantDelta << "\n";
10914       std::abort();
10915     }
10916   }
10917 }
10918 
10919 bool ScalarEvolution::invalidate(
10920     Function &F, const PreservedAnalyses &PA,
10921     FunctionAnalysisManager::Invalidator &Inv) {
10922   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
10923   // of its dependencies is invalidated.
10924   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
10925   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
10926          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
10927          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
10928          Inv.invalidate<LoopAnalysis>(F, PA);
10929 }
10930 
10931 AnalysisKey ScalarEvolutionAnalysis::Key;
10932 
10933 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
10934                                              FunctionAnalysisManager &AM) {
10935   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
10936                          AM.getResult<AssumptionAnalysis>(F),
10937                          AM.getResult<DominatorTreeAnalysis>(F),
10938                          AM.getResult<LoopAnalysis>(F));
10939 }
10940 
10941 PreservedAnalyses
10942 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10943   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
10944   return PreservedAnalyses::all();
10945 }
10946 
10947 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
10948                       "Scalar Evolution Analysis", false, true)
10949 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10950 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
10951 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
10952 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
10953 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10954                     "Scalar Evolution Analysis", false, true)
10955 char ScalarEvolutionWrapperPass::ID = 0;
10956 
10957 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10958   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10959 }
10960 
10961 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10962   SE.reset(new ScalarEvolution(
10963       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10964       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10965       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10966       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10967   return false;
10968 }
10969 
10970 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10971 
10972 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10973   SE->print(OS);
10974 }
10975 
10976 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10977   if (!VerifySCEV)
10978     return;
10979 
10980   SE->verify();
10981 }
10982 
10983 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10984   AU.setPreservesAll();
10985   AU.addRequiredTransitive<AssumptionCacheTracker>();
10986   AU.addRequiredTransitive<LoopInfoWrapperPass>();
10987   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10988   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10989 }
10990 
10991 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
10992                                                         const SCEV *RHS) {
10993   FoldingSetNodeID ID;
10994   assert(LHS->getType() == RHS->getType() &&
10995          "Type mismatch between LHS and RHS");
10996   // Unique this node based on the arguments
10997   ID.AddInteger(SCEVPredicate::P_Equal);
10998   ID.AddPointer(LHS);
10999   ID.AddPointer(RHS);
11000   void *IP = nullptr;
11001   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11002     return S;
11003   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11004       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11005   UniquePreds.InsertNode(Eq, IP);
11006   return Eq;
11007 }
11008 
11009 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11010     const SCEVAddRecExpr *AR,
11011     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11012   FoldingSetNodeID ID;
11013   // Unique this node based on the arguments
11014   ID.AddInteger(SCEVPredicate::P_Wrap);
11015   ID.AddPointer(AR);
11016   ID.AddInteger(AddedFlags);
11017   void *IP = nullptr;
11018   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11019     return S;
11020   auto *OF = new (SCEVAllocator)
11021       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11022   UniquePreds.InsertNode(OF, IP);
11023   return OF;
11024 }
11025 
11026 namespace {
11027 
11028 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11029 public:
11030   /// Rewrites \p S in the context of a loop L and the SCEV predication
11031   /// infrastructure.
11032   ///
11033   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11034   /// equivalences present in \p Pred.
11035   ///
11036   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11037   /// \p NewPreds such that the result will be an AddRecExpr.
11038   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11039                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11040                              SCEVUnionPredicate *Pred) {
11041     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11042     return Rewriter.visit(S);
11043   }
11044 
11045   SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11046                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11047                         SCEVUnionPredicate *Pred)
11048       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11049 
11050   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11051     if (Pred) {
11052       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11053       for (auto *Pred : ExprPreds)
11054         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11055           if (IPred->getLHS() == Expr)
11056             return IPred->getRHS();
11057     }
11058     return convertToAddRecWithPreds(Expr);
11059   }
11060 
11061   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11062     const SCEV *Operand = visit(Expr->getOperand());
11063     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11064     if (AR && AR->getLoop() == L && AR->isAffine()) {
11065       // This couldn't be folded because the operand didn't have the nuw
11066       // flag. Add the nusw flag as an assumption that we could make.
11067       const SCEV *Step = AR->getStepRecurrence(SE);
11068       Type *Ty = Expr->getType();
11069       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11070         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11071                                 SE.getSignExtendExpr(Step, Ty), L,
11072                                 AR->getNoWrapFlags());
11073     }
11074     return SE.getZeroExtendExpr(Operand, Expr->getType());
11075   }
11076 
11077   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11078     const SCEV *Operand = visit(Expr->getOperand());
11079     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11080     if (AR && AR->getLoop() == L && AR->isAffine()) {
11081       // This couldn't be folded because the operand didn't have the nsw
11082       // flag. Add the nssw flag as an assumption that we could make.
11083       const SCEV *Step = AR->getStepRecurrence(SE);
11084       Type *Ty = Expr->getType();
11085       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11086         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11087                                 SE.getSignExtendExpr(Step, Ty), L,
11088                                 AR->getNoWrapFlags());
11089     }
11090     return SE.getSignExtendExpr(Operand, Expr->getType());
11091   }
11092 
11093 private:
11094   bool addOverflowAssumption(const SCEVPredicate *P) {
11095     if (!NewPreds) {
11096       // Check if we've already made this assumption.
11097       return Pred && Pred->implies(P);
11098     }
11099     NewPreds->insert(P);
11100     return true;
11101   }
11102 
11103   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11104                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11105     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11106     return addOverflowAssumption(A);
11107   }
11108 
11109   // If \p Expr represents a PHINode, we try to see if it can be represented
11110   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11111   // to add this predicate as a runtime overflow check, we return the AddRec.
11112   // If \p Expr does not meet these conditions (is not a PHI node, or we
11113   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11114   // return \p Expr.
11115   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11116     if (!isa<PHINode>(Expr->getValue()))
11117       return Expr;
11118     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11119     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11120     if (!PredicatedRewrite)
11121       return Expr;
11122     for (auto *P : PredicatedRewrite->second){
11123       if (!addOverflowAssumption(P))
11124         return Expr;
11125     }
11126     return PredicatedRewrite->first;
11127   }
11128 
11129   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11130   SCEVUnionPredicate *Pred;
11131   const Loop *L;
11132 };
11133 } // end anonymous namespace
11134 
11135 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11136                                                    SCEVUnionPredicate &Preds) {
11137   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11138 }
11139 
11140 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11141     const SCEV *S, const Loop *L,
11142     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11143 
11144   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11145   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11146   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11147 
11148   if (!AddRec)
11149     return nullptr;
11150 
11151   // Since the transformation was successful, we can now transfer the SCEV
11152   // predicates.
11153   for (auto *P : TransformPreds)
11154     Preds.insert(P);
11155 
11156   return AddRec;
11157 }
11158 
11159 /// SCEV predicates
11160 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11161                              SCEVPredicateKind Kind)
11162     : FastID(ID), Kind(Kind) {}
11163 
11164 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11165                                        const SCEV *LHS, const SCEV *RHS)
11166     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11167   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11168   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11169 }
11170 
11171 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11172   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11173 
11174   if (!Op)
11175     return false;
11176 
11177   return Op->LHS == LHS && Op->RHS == RHS;
11178 }
11179 
11180 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11181 
11182 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11183 
11184 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11185   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11186 }
11187 
11188 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11189                                      const SCEVAddRecExpr *AR,
11190                                      IncrementWrapFlags Flags)
11191     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11192 
11193 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11194 
11195 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11196   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11197 
11198   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11199 }
11200 
11201 bool SCEVWrapPredicate::isAlwaysTrue() const {
11202   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11203   IncrementWrapFlags IFlags = Flags;
11204 
11205   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11206     IFlags = clearFlags(IFlags, IncrementNSSW);
11207 
11208   return IFlags == IncrementAnyWrap;
11209 }
11210 
11211 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11212   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11213   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11214     OS << "<nusw>";
11215   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11216     OS << "<nssw>";
11217   OS << "\n";
11218 }
11219 
11220 SCEVWrapPredicate::IncrementWrapFlags
11221 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11222                                    ScalarEvolution &SE) {
11223   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11224   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11225 
11226   // We can safely transfer the NSW flag as NSSW.
11227   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11228     ImpliedFlags = IncrementNSSW;
11229 
11230   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11231     // If the increment is positive, the SCEV NUW flag will also imply the
11232     // WrapPredicate NUSW flag.
11233     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11234       if (Step->getValue()->getValue().isNonNegative())
11235         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11236   }
11237 
11238   return ImpliedFlags;
11239 }
11240 
11241 /// Union predicates don't get cached so create a dummy set ID for it.
11242 SCEVUnionPredicate::SCEVUnionPredicate()
11243     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11244 
11245 bool SCEVUnionPredicate::isAlwaysTrue() const {
11246   return all_of(Preds,
11247                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11248 }
11249 
11250 ArrayRef<const SCEVPredicate *>
11251 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11252   auto I = SCEVToPreds.find(Expr);
11253   if (I == SCEVToPreds.end())
11254     return ArrayRef<const SCEVPredicate *>();
11255   return I->second;
11256 }
11257 
11258 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11259   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11260     return all_of(Set->Preds,
11261                   [this](const SCEVPredicate *I) { return this->implies(I); });
11262 
11263   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11264   if (ScevPredsIt == SCEVToPreds.end())
11265     return false;
11266   auto &SCEVPreds = ScevPredsIt->second;
11267 
11268   return any_of(SCEVPreds,
11269                 [N](const SCEVPredicate *I) { return I->implies(N); });
11270 }
11271 
11272 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11273 
11274 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11275   for (auto Pred : Preds)
11276     Pred->print(OS, Depth);
11277 }
11278 
11279 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11280   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11281     for (auto Pred : Set->Preds)
11282       add(Pred);
11283     return;
11284   }
11285 
11286   if (implies(N))
11287     return;
11288 
11289   const SCEV *Key = N->getExpr();
11290   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11291                 " associated expression!");
11292 
11293   SCEVToPreds[Key].push_back(N);
11294   Preds.push_back(N);
11295 }
11296 
11297 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11298                                                      Loop &L)
11299     : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
11300 
11301 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11302   const SCEV *Expr = SE.getSCEV(V);
11303   RewriteEntry &Entry = RewriteMap[Expr];
11304 
11305   // If we already have an entry and the version matches, return it.
11306   if (Entry.second && Generation == Entry.first)
11307     return Entry.second;
11308 
11309   // We found an entry but it's stale. Rewrite the stale entry
11310   // according to the current predicate.
11311   if (Entry.second)
11312     Expr = Entry.second;
11313 
11314   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11315   Entry = {Generation, NewSCEV};
11316 
11317   return NewSCEV;
11318 }
11319 
11320 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11321   if (!BackedgeCount) {
11322     SCEVUnionPredicate BackedgePred;
11323     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11324     addPredicate(BackedgePred);
11325   }
11326   return BackedgeCount;
11327 }
11328 
11329 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
11330   if (Preds.implies(&Pred))
11331     return;
11332   Preds.add(&Pred);
11333   updateGeneration();
11334 }
11335 
11336 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
11337   return Preds;
11338 }
11339 
11340 void PredicatedScalarEvolution::updateGeneration() {
11341   // If the generation number wrapped recompute everything.
11342   if (++Generation == 0) {
11343     for (auto &II : RewriteMap) {
11344       const SCEV *Rewritten = II.second.second;
11345       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
11346     }
11347   }
11348 }
11349 
11350 void PredicatedScalarEvolution::setNoOverflow(
11351     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11352   const SCEV *Expr = getSCEV(V);
11353   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11354 
11355   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
11356 
11357   // Clear the statically implied flags.
11358   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
11359   addPredicate(*SE.getWrapPredicate(AR, Flags));
11360 
11361   auto II = FlagsMap.insert({V, Flags});
11362   if (!II.second)
11363     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
11364 }
11365 
11366 bool PredicatedScalarEvolution::hasNoOverflow(
11367     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
11368   const SCEV *Expr = getSCEV(V);
11369   const auto *AR = cast<SCEVAddRecExpr>(Expr);
11370 
11371   Flags = SCEVWrapPredicate::clearFlags(
11372       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
11373 
11374   auto II = FlagsMap.find(V);
11375 
11376   if (II != FlagsMap.end())
11377     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
11378 
11379   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
11380 }
11381 
11382 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
11383   const SCEV *Expr = this->getSCEV(V);
11384   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
11385   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
11386 
11387   if (!New)
11388     return nullptr;
11389 
11390   for (auto *P : NewPreds)
11391     Preds.add(P);
11392 
11393   updateGeneration();
11394   RewriteMap[SE.getSCEV(V)] = {Generation, New};
11395   return New;
11396 }
11397 
11398 PredicatedScalarEvolution::PredicatedScalarEvolution(
11399     const PredicatedScalarEvolution &Init)
11400     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
11401       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
11402   for (const auto &I : Init.FlagsMap)
11403     FlagsMap.insert(I);
11404 }
11405 
11406 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
11407   // For each block.
11408   for (auto *BB : L.getBlocks())
11409     for (auto &I : *BB) {
11410       if (!SE.isSCEVable(I.getType()))
11411         continue;
11412 
11413       auto *Expr = SE.getSCEV(&I);
11414       auto II = RewriteMap.find(Expr);
11415 
11416       if (II == RewriteMap.end())
11417         continue;
11418 
11419       // Don't print things that are not interesting.
11420       if (II->second.second == Expr)
11421         continue;
11422 
11423       OS.indent(Depth) << "[PSE]" << I << ":\n";
11424       OS.indent(Depth + 2) << *Expr << "\n";
11425       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
11426     }
11427 }
11428