1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution analysis
11 // engine, which is used primarily to analyze expressions involving induction
12 // variables in loops.
13 //
14 // There are several aspects to this library.  First is the representation of
15 // scalar expressions, which are represented as subclasses of the SCEV class.
16 // These classes are used to represent certain types of subexpressions that we
17 // can handle. We only create one SCEV of a particular shape, so
18 // pointer-comparisons for equality are legal.
19 //
20 // One important aspect of the SCEV objects is that they are never cyclic, even
21 // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
22 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 // recurrence) then we represent it directly as a recurrence node, otherwise we
24 // represent it as a SCEVUnknown node.
25 //
26 // In addition to being able to represent expressions of various types, we also
27 // have folders that are used to build the *canonical* representation for a
28 // particular expression.  These folders are capable of using a variety of
29 // rewrite rules to simplify the expressions.
30 //
31 // Once the folders are defined, we can implement the more interesting
32 // higher-level code, such as the code that recognizes PHI nodes of various
33 // types, computes the execution count of a loop, etc.
34 //
35 // TODO: We should use these routines and value representations to implement
36 // dependence analysis!
37 //
38 //===----------------------------------------------------------------------===//
39 //
40 // There are several good references for the techniques used in this analysis.
41 //
42 //  Chains of recurrences -- a method to expedite the evaluation
43 //  of closed-form functions
44 //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 //
46 //  On computational properties of chains of recurrences
47 //  Eugene V. Zima
48 //
49 //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 //  Robert A. van Engelen
51 //
52 //  Efficient Symbolic Analysis for Optimizing Compilers
53 //  Robert A. van Engelen
54 //
55 //  Using the chains of recurrences algebra for data dependence testing and
56 //  induction variable substitution
57 //  MS Thesis, Johnie Birch
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DepthFirstIterator.h"
66 #include "llvm/ADT/EquivalenceClasses.h"
67 #include "llvm/ADT/FoldingSet.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/ScopeExit.h"
72 #include "llvm/ADT/Sequence.h"
73 #include "llvm/ADT/SetVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/Statistic.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/ConstantFolding.h"
81 #include "llvm/Analysis/InstructionSimplify.h"
82 #include "llvm/Analysis/LoopInfo.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/CallSite.h"
91 #include "llvm/IR/Constant.h"
92 #include "llvm/IR/ConstantRange.h"
93 #include "llvm/IR/Constants.h"
94 #include "llvm/IR/DataLayout.h"
95 #include "llvm/IR/DerivedTypes.h"
96 #include "llvm/IR/Dominators.h"
97 #include "llvm/IR/Function.h"
98 #include "llvm/IR/GlobalAlias.h"
99 #include "llvm/IR/GlobalValue.h"
100 #include "llvm/IR/GlobalVariable.h"
101 #include "llvm/IR/InstIterator.h"
102 #include "llvm/IR/InstrTypes.h"
103 #include "llvm/IR/Instruction.h"
104 #include "llvm/IR/Instructions.h"
105 #include "llvm/IR/IntrinsicInst.h"
106 #include "llvm/IR/Intrinsics.h"
107 #include "llvm/IR/LLVMContext.h"
108 #include "llvm/IR/Metadata.h"
109 #include "llvm/IR/Operator.h"
110 #include "llvm/IR/PatternMatch.h"
111 #include "llvm/IR/Type.h"
112 #include "llvm/IR/Use.h"
113 #include "llvm/IR/User.h"
114 #include "llvm/IR/Value.h"
115 #include "llvm/Pass.h"
116 #include "llvm/Support/Casting.h"
117 #include "llvm/Support/CommandLine.h"
118 #include "llvm/Support/Compiler.h"
119 #include "llvm/Support/Debug.h"
120 #include "llvm/Support/ErrorHandling.h"
121 #include "llvm/Support/KnownBits.h"
122 #include "llvm/Support/SaveAndRestore.h"
123 #include "llvm/Support/raw_ostream.h"
124 #include <algorithm>
125 #include <cassert>
126 #include <climits>
127 #include <cstddef>
128 #include <cstdint>
129 #include <cstdlib>
130 #include <map>
131 #include <memory>
132 #include <tuple>
133 #include <utility>
134 #include <vector>
135 
136 using namespace llvm;
137 
138 #define DEBUG_TYPE "scalar-evolution"
139 
140 STATISTIC(NumArrayLenItCounts,
141           "Number of trip counts computed with array length");
142 STATISTIC(NumTripCountsComputed,
143           "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145           "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147           "Number of loops with trip counts computed by force");
148 
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151                         cl::desc("Maximum number of iterations SCEV will "
152                                  "symbolically execute a constant "
153                                  "derived loop"),
154                         cl::init(100));
155 
156 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157 static cl::opt<bool> VerifySCEV(
158     "verify-scev", cl::Hidden,
159     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160 static cl::opt<bool>
161     VerifySCEVMap("verify-scev-maps", cl::Hidden,
162                   cl::desc("Verify no dangling value in ScalarEvolution's "
163                            "ExprValueMap (slow)"));
164 
165 static cl::opt<unsigned> MulOpsInlineThreshold(
166     "scev-mulops-inline-threshold", cl::Hidden,
167     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
168     cl::init(32));
169 
170 static cl::opt<unsigned> AddOpsInlineThreshold(
171     "scev-addops-inline-threshold", cl::Hidden,
172     cl::desc("Threshold for inlining addition operands into a SCEV"),
173     cl::init(500));
174 
175 static cl::opt<unsigned> MaxSCEVCompareDepth(
176     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
177     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
181     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
182     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
183     cl::init(2));
184 
185 static cl::opt<unsigned> MaxValueCompareDepth(
186     "scalar-evolution-max-value-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive value complexity comparisons"),
188     cl::init(2));
189 
190 static cl::opt<unsigned>
191     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
192                   cl::desc("Maximum depth of recursive arithmetics"),
193                   cl::init(32));
194 
195 static cl::opt<unsigned> MaxConstantEvolvingDepth(
196     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
198 
199 static cl::opt<unsigned>
200     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
201                 cl::desc("Maximum depth of recursive SExt/ZExt"),
202                 cl::init(8));
203 
204 static cl::opt<unsigned>
205     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
206                   cl::desc("Max coefficients in AddRec during evolving"),
207                   cl::init(16));
208 
209 //===----------------------------------------------------------------------===//
210 //                           SCEV class definitions
211 //===----------------------------------------------------------------------===//
212 
213 //===----------------------------------------------------------------------===//
214 // Implementation of the SCEV class.
215 //
216 
217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218 LLVM_DUMP_METHOD void SCEV::dump() const {
219   print(dbgs());
220   dbgs() << '\n';
221 }
222 #endif
223 
224 void SCEV::print(raw_ostream &OS) const {
225   switch (static_cast<SCEVTypes>(getSCEVType())) {
226   case scConstant:
227     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
228     return;
229   case scTruncate: {
230     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
231     const SCEV *Op = Trunc->getOperand();
232     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
233        << *Trunc->getType() << ")";
234     return;
235   }
236   case scZeroExtend: {
237     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
238     const SCEV *Op = ZExt->getOperand();
239     OS << "(zext " << *Op->getType() << " " << *Op << " to "
240        << *ZExt->getType() << ")";
241     return;
242   }
243   case scSignExtend: {
244     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
245     const SCEV *Op = SExt->getOperand();
246     OS << "(sext " << *Op->getType() << " " << *Op << " to "
247        << *SExt->getType() << ")";
248     return;
249   }
250   case scAddRecExpr: {
251     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
252     OS << "{" << *AR->getOperand(0);
253     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
254       OS << ",+," << *AR->getOperand(i);
255     OS << "}<";
256     if (AR->hasNoUnsignedWrap())
257       OS << "nuw><";
258     if (AR->hasNoSignedWrap())
259       OS << "nsw><";
260     if (AR->hasNoSelfWrap() &&
261         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
262       OS << "nw><";
263     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
264     OS << ">";
265     return;
266   }
267   case scAddExpr:
268   case scMulExpr:
269   case scUMaxExpr:
270   case scSMaxExpr: {
271     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
272     const char *OpStr = nullptr;
273     switch (NAry->getSCEVType()) {
274     case scAddExpr: OpStr = " + "; break;
275     case scMulExpr: OpStr = " * "; break;
276     case scUMaxExpr: OpStr = " umax "; break;
277     case scSMaxExpr: OpStr = " smax "; break;
278     }
279     OS << "(";
280     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
281          I != E; ++I) {
282       OS << **I;
283       if (std::next(I) != E)
284         OS << OpStr;
285     }
286     OS << ")";
287     switch (NAry->getSCEVType()) {
288     case scAddExpr:
289     case scMulExpr:
290       if (NAry->hasNoUnsignedWrap())
291         OS << "<nuw>";
292       if (NAry->hasNoSignedWrap())
293         OS << "<nsw>";
294     }
295     return;
296   }
297   case scUDivExpr: {
298     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
299     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
300     return;
301   }
302   case scUnknown: {
303     const SCEVUnknown *U = cast<SCEVUnknown>(this);
304     Type *AllocTy;
305     if (U->isSizeOf(AllocTy)) {
306       OS << "sizeof(" << *AllocTy << ")";
307       return;
308     }
309     if (U->isAlignOf(AllocTy)) {
310       OS << "alignof(" << *AllocTy << ")";
311       return;
312     }
313 
314     Type *CTy;
315     Constant *FieldNo;
316     if (U->isOffsetOf(CTy, FieldNo)) {
317       OS << "offsetof(" << *CTy << ", ";
318       FieldNo->printAsOperand(OS, false);
319       OS << ")";
320       return;
321     }
322 
323     // Otherwise just print it normally.
324     U->getValue()->printAsOperand(OS, false);
325     return;
326   }
327   case scCouldNotCompute:
328     OS << "***COULDNOTCOMPUTE***";
329     return;
330   }
331   llvm_unreachable("Unknown SCEV kind!");
332 }
333 
334 Type *SCEV::getType() const {
335   switch (static_cast<SCEVTypes>(getSCEVType())) {
336   case scConstant:
337     return cast<SCEVConstant>(this)->getType();
338   case scTruncate:
339   case scZeroExtend:
340   case scSignExtend:
341     return cast<SCEVCastExpr>(this)->getType();
342   case scAddRecExpr:
343   case scMulExpr:
344   case scUMaxExpr:
345   case scSMaxExpr:
346     return cast<SCEVNAryExpr>(this)->getType();
347   case scAddExpr:
348     return cast<SCEVAddExpr>(this)->getType();
349   case scUDivExpr:
350     return cast<SCEVUDivExpr>(this)->getType();
351   case scUnknown:
352     return cast<SCEVUnknown>(this)->getType();
353   case scCouldNotCompute:
354     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
355   }
356   llvm_unreachable("Unknown SCEV kind!");
357 }
358 
359 bool SCEV::isZero() const {
360   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
361     return SC->getValue()->isZero();
362   return false;
363 }
364 
365 bool SCEV::isOne() const {
366   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
367     return SC->getValue()->isOne();
368   return false;
369 }
370 
371 bool SCEV::isAllOnesValue() const {
372   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
373     return SC->getValue()->isMinusOne();
374   return false;
375 }
376 
377 bool SCEV::isNonConstantNegative() const {
378   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
379   if (!Mul) return false;
380 
381   // If there is a constant factor, it will be first.
382   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
383   if (!SC) return false;
384 
385   // Return true if the value is negative, this matches things like (-42 * V).
386   return SC->getAPInt().isNegative();
387 }
388 
389 SCEVCouldNotCompute::SCEVCouldNotCompute() :
390   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
391 
392 bool SCEVCouldNotCompute::classof(const SCEV *S) {
393   return S->getSCEVType() == scCouldNotCompute;
394 }
395 
396 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
397   FoldingSetNodeID ID;
398   ID.AddInteger(scConstant);
399   ID.AddPointer(V);
400   void *IP = nullptr;
401   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
402   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
403   UniqueSCEVs.InsertNode(S, IP);
404   return S;
405 }
406 
407 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
408   return getConstant(ConstantInt::get(getContext(), Val));
409 }
410 
411 const SCEV *
412 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
413   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
414   return getConstant(ConstantInt::get(ITy, V, isSigned));
415 }
416 
417 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
418                            unsigned SCEVTy, const SCEV *op, Type *ty)
419   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
420 
421 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
422                                    const SCEV *op, Type *ty)
423   : SCEVCastExpr(ID, scTruncate, op, ty) {
424   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
425          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
426          "Cannot truncate non-integer value!");
427 }
428 
429 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
430                                        const SCEV *op, Type *ty)
431   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
432   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
433          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
434          "Cannot zero extend non-integer value!");
435 }
436 
437 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
438                                        const SCEV *op, Type *ty)
439   : SCEVCastExpr(ID, scSignExtend, op, ty) {
440   assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
441          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
442          "Cannot sign extend non-integer value!");
443 }
444 
445 void SCEVUnknown::deleted() {
446   // Clear this SCEVUnknown from various maps.
447   SE->forgetMemoizedResults(this);
448 
449   // Remove this SCEVUnknown from the uniquing map.
450   SE->UniqueSCEVs.RemoveNode(this);
451 
452   // Release the value.
453   setValPtr(nullptr);
454 }
455 
456 void SCEVUnknown::allUsesReplacedWith(Value *New) {
457   // Remove this SCEVUnknown from the uniquing map.
458   SE->UniqueSCEVs.RemoveNode(this);
459 
460   // Update this SCEVUnknown to point to the new value. This is needed
461   // because there may still be outstanding SCEVs which still point to
462   // this SCEVUnknown.
463   setValPtr(New);
464 }
465 
466 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
467   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
468     if (VCE->getOpcode() == Instruction::PtrToInt)
469       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
470         if (CE->getOpcode() == Instruction::GetElementPtr &&
471             CE->getOperand(0)->isNullValue() &&
472             CE->getNumOperands() == 2)
473           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
474             if (CI->isOne()) {
475               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
476                                  ->getElementType();
477               return true;
478             }
479 
480   return false;
481 }
482 
483 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
484   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
485     if (VCE->getOpcode() == Instruction::PtrToInt)
486       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
487         if (CE->getOpcode() == Instruction::GetElementPtr &&
488             CE->getOperand(0)->isNullValue()) {
489           Type *Ty =
490             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
491           if (StructType *STy = dyn_cast<StructType>(Ty))
492             if (!STy->isPacked() &&
493                 CE->getNumOperands() == 3 &&
494                 CE->getOperand(1)->isNullValue()) {
495               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
496                 if (CI->isOne() &&
497                     STy->getNumElements() == 2 &&
498                     STy->getElementType(0)->isIntegerTy(1)) {
499                   AllocTy = STy->getElementType(1);
500                   return true;
501                 }
502             }
503         }
504 
505   return false;
506 }
507 
508 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
509   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
510     if (VCE->getOpcode() == Instruction::PtrToInt)
511       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
512         if (CE->getOpcode() == Instruction::GetElementPtr &&
513             CE->getNumOperands() == 3 &&
514             CE->getOperand(0)->isNullValue() &&
515             CE->getOperand(1)->isNullValue()) {
516           Type *Ty =
517             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
518           // Ignore vector types here so that ScalarEvolutionExpander doesn't
519           // emit getelementptrs that index into vectors.
520           if (Ty->isStructTy() || Ty->isArrayTy()) {
521             CTy = Ty;
522             FieldNo = CE->getOperand(2);
523             return true;
524           }
525         }
526 
527   return false;
528 }
529 
530 //===----------------------------------------------------------------------===//
531 //                               SCEV Utilities
532 //===----------------------------------------------------------------------===//
533 
534 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
535 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
536 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
537 /// have been previously deemed to be "equally complex" by this routine.  It is
538 /// intended to avoid exponential time complexity in cases like:
539 ///
540 ///   %a = f(%x, %y)
541 ///   %b = f(%a, %a)
542 ///   %c = f(%b, %b)
543 ///
544 ///   %d = f(%x, %y)
545 ///   %e = f(%d, %d)
546 ///   %f = f(%e, %e)
547 ///
548 ///   CompareValueComplexity(%f, %c)
549 ///
550 /// Since we do not continue running this routine on expression trees once we
551 /// have seen unequal values, there is no need to track them in the cache.
552 static int
553 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
554                        const LoopInfo *const LI, Value *LV, Value *RV,
555                        unsigned Depth) {
556   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
557     return 0;
558 
559   // Order pointer values after integer values. This helps SCEVExpander form
560   // GEPs.
561   bool LIsPointer = LV->getType()->isPointerTy(),
562        RIsPointer = RV->getType()->isPointerTy();
563   if (LIsPointer != RIsPointer)
564     return (int)LIsPointer - (int)RIsPointer;
565 
566   // Compare getValueID values.
567   unsigned LID = LV->getValueID(), RID = RV->getValueID();
568   if (LID != RID)
569     return (int)LID - (int)RID;
570 
571   // Sort arguments by their position.
572   if (const auto *LA = dyn_cast<Argument>(LV)) {
573     const auto *RA = cast<Argument>(RV);
574     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
575     return (int)LArgNo - (int)RArgNo;
576   }
577 
578   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
579     const auto *RGV = cast<GlobalValue>(RV);
580 
581     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
582       auto LT = GV->getLinkage();
583       return !(GlobalValue::isPrivateLinkage(LT) ||
584                GlobalValue::isInternalLinkage(LT));
585     };
586 
587     // Use the names to distinguish the two values, but only if the
588     // names are semantically important.
589     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
590       return LGV->getName().compare(RGV->getName());
591   }
592 
593   // For instructions, compare their loop depth, and their operand count.  This
594   // is pretty loose.
595   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
596     const auto *RInst = cast<Instruction>(RV);
597 
598     // Compare loop depths.
599     const BasicBlock *LParent = LInst->getParent(),
600                      *RParent = RInst->getParent();
601     if (LParent != RParent) {
602       unsigned LDepth = LI->getLoopDepth(LParent),
603                RDepth = LI->getLoopDepth(RParent);
604       if (LDepth != RDepth)
605         return (int)LDepth - (int)RDepth;
606     }
607 
608     // Compare the number of operands.
609     unsigned LNumOps = LInst->getNumOperands(),
610              RNumOps = RInst->getNumOperands();
611     if (LNumOps != RNumOps)
612       return (int)LNumOps - (int)RNumOps;
613 
614     for (unsigned Idx : seq(0u, LNumOps)) {
615       int Result =
616           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
617                                  RInst->getOperand(Idx), Depth + 1);
618       if (Result != 0)
619         return Result;
620     }
621   }
622 
623   EqCacheValue.unionSets(LV, RV);
624   return 0;
625 }
626 
627 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
628 // than RHS, respectively. A three-way result allows recursive comparisons to be
629 // more efficient.
630 static int CompareSCEVComplexity(
631     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
632     EquivalenceClasses<const Value *> &EqCacheValue,
633     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
634     DominatorTree &DT, unsigned Depth = 0) {
635   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
636   if (LHS == RHS)
637     return 0;
638 
639   // Primarily, sort the SCEVs by their getSCEVType().
640   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
641   if (LType != RType)
642     return (int)LType - (int)RType;
643 
644   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
645     return 0;
646   // Aside from the getSCEVType() ordering, the particular ordering
647   // isn't very important except that it's beneficial to be consistent,
648   // so that (a + b) and (b + a) don't end up as different expressions.
649   switch (static_cast<SCEVTypes>(LType)) {
650   case scUnknown: {
651     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
652     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
653 
654     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
655                                    RU->getValue(), Depth + 1);
656     if (X == 0)
657       EqCacheSCEV.unionSets(LHS, RHS);
658     return X;
659   }
660 
661   case scConstant: {
662     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
663     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
664 
665     // Compare constant values.
666     const APInt &LA = LC->getAPInt();
667     const APInt &RA = RC->getAPInt();
668     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
669     if (LBitWidth != RBitWidth)
670       return (int)LBitWidth - (int)RBitWidth;
671     return LA.ult(RA) ? -1 : 1;
672   }
673 
674   case scAddRecExpr: {
675     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
676     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
677 
678     // There is always a dominance between two recs that are used by one SCEV,
679     // so we can safely sort recs by loop header dominance. We require such
680     // order in getAddExpr.
681     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
682     if (LLoop != RLoop) {
683       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
684       assert(LHead != RHead && "Two loops share the same header?");
685       if (DT.dominates(LHead, RHead))
686         return 1;
687       else
688         assert(DT.dominates(RHead, LHead) &&
689                "No dominance between recurrences used by one SCEV?");
690       return -1;
691     }
692 
693     // Addrec complexity grows with operand count.
694     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
695     if (LNumOps != RNumOps)
696       return (int)LNumOps - (int)RNumOps;
697 
698     // Compare NoWrap flags.
699     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
700       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
701 
702     // Lexicographically compare.
703     for (unsigned i = 0; i != LNumOps; ++i) {
704       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
705                                     LA->getOperand(i), RA->getOperand(i), DT,
706                                     Depth + 1);
707       if (X != 0)
708         return X;
709     }
710     EqCacheSCEV.unionSets(LHS, RHS);
711     return 0;
712   }
713 
714   case scAddExpr:
715   case scMulExpr:
716   case scSMaxExpr:
717   case scUMaxExpr: {
718     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
719     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
720 
721     // Lexicographically compare n-ary expressions.
722     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
723     if (LNumOps != RNumOps)
724       return (int)LNumOps - (int)RNumOps;
725 
726     // Compare NoWrap flags.
727     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
728       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
729 
730     for (unsigned i = 0; i != LNumOps; ++i) {
731       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
732                                     LC->getOperand(i), RC->getOperand(i), DT,
733                                     Depth + 1);
734       if (X != 0)
735         return X;
736     }
737     EqCacheSCEV.unionSets(LHS, RHS);
738     return 0;
739   }
740 
741   case scUDivExpr: {
742     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
743     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
744 
745     // Lexicographically compare udiv expressions.
746     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
747                                   RC->getLHS(), DT, Depth + 1);
748     if (X != 0)
749       return X;
750     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
751                               RC->getRHS(), DT, Depth + 1);
752     if (X == 0)
753       EqCacheSCEV.unionSets(LHS, RHS);
754     return X;
755   }
756 
757   case scTruncate:
758   case scZeroExtend:
759   case scSignExtend: {
760     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
761     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
762 
763     // Compare cast expressions by operand.
764     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
765                                   LC->getOperand(), RC->getOperand(), DT,
766                                   Depth + 1);
767     if (X == 0)
768       EqCacheSCEV.unionSets(LHS, RHS);
769     return X;
770   }
771 
772   case scCouldNotCompute:
773     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
774   }
775   llvm_unreachable("Unknown SCEV kind!");
776 }
777 
778 /// Given a list of SCEV objects, order them by their complexity, and group
779 /// objects of the same complexity together by value.  When this routine is
780 /// finished, we know that any duplicates in the vector are consecutive and that
781 /// complexity is monotonically increasing.
782 ///
783 /// Note that we go take special precautions to ensure that we get deterministic
784 /// results from this routine.  In other words, we don't want the results of
785 /// this to depend on where the addresses of various SCEV objects happened to
786 /// land in memory.
787 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
788                               LoopInfo *LI, DominatorTree &DT) {
789   if (Ops.size() < 2) return;  // Noop
790 
791   EquivalenceClasses<const SCEV *> EqCacheSCEV;
792   EquivalenceClasses<const Value *> EqCacheValue;
793   if (Ops.size() == 2) {
794     // This is the common case, which also happens to be trivially simple.
795     // Special case it.
796     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
797     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
798       std::swap(LHS, RHS);
799     return;
800   }
801 
802   // Do the rough sort by complexity.
803   std::stable_sort(Ops.begin(), Ops.end(),
804                    [&](const SCEV *LHS, const SCEV *RHS) {
805                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
806                                                   LHS, RHS, DT) < 0;
807                    });
808 
809   // Now that we are sorted by complexity, group elements of the same
810   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
811   // be extremely short in practice.  Note that we take this approach because we
812   // do not want to depend on the addresses of the objects we are grouping.
813   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
814     const SCEV *S = Ops[i];
815     unsigned Complexity = S->getSCEVType();
816 
817     // If there are any objects of the same complexity and same value as this
818     // one, group them.
819     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
820       if (Ops[j] == S) { // Found a duplicate.
821         // Move it to immediately after i'th element.
822         std::swap(Ops[i+1], Ops[j]);
823         ++i;   // no need to rescan it.
824         if (i == e-2) return;  // Done!
825       }
826     }
827   }
828 }
829 
830 // Returns the size of the SCEV S.
831 static inline int sizeOfSCEV(const SCEV *S) {
832   struct FindSCEVSize {
833     int Size = 0;
834 
835     FindSCEVSize() = default;
836 
837     bool follow(const SCEV *S) {
838       ++Size;
839       // Keep looking at all operands of S.
840       return true;
841     }
842 
843     bool isDone() const {
844       return false;
845     }
846   };
847 
848   FindSCEVSize F;
849   SCEVTraversal<FindSCEVSize> ST(F);
850   ST.visitAll(S);
851   return F.Size;
852 }
853 
854 namespace {
855 
856 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
857 public:
858   // Computes the Quotient and Remainder of the division of Numerator by
859   // Denominator.
860   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
861                      const SCEV *Denominator, const SCEV **Quotient,
862                      const SCEV **Remainder) {
863     assert(Numerator && Denominator && "Uninitialized SCEV");
864 
865     SCEVDivision D(SE, Numerator, Denominator);
866 
867     // Check for the trivial case here to avoid having to check for it in the
868     // rest of the code.
869     if (Numerator == Denominator) {
870       *Quotient = D.One;
871       *Remainder = D.Zero;
872       return;
873     }
874 
875     if (Numerator->isZero()) {
876       *Quotient = D.Zero;
877       *Remainder = D.Zero;
878       return;
879     }
880 
881     // A simple case when N/1. The quotient is N.
882     if (Denominator->isOne()) {
883       *Quotient = Numerator;
884       *Remainder = D.Zero;
885       return;
886     }
887 
888     // Split the Denominator when it is a product.
889     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
890       const SCEV *Q, *R;
891       *Quotient = Numerator;
892       for (const SCEV *Op : T->operands()) {
893         divide(SE, *Quotient, Op, &Q, &R);
894         *Quotient = Q;
895 
896         // Bail out when the Numerator is not divisible by one of the terms of
897         // the Denominator.
898         if (!R->isZero()) {
899           *Quotient = D.Zero;
900           *Remainder = Numerator;
901           return;
902         }
903       }
904       *Remainder = D.Zero;
905       return;
906     }
907 
908     D.visit(Numerator);
909     *Quotient = D.Quotient;
910     *Remainder = D.Remainder;
911   }
912 
913   // Except in the trivial case described above, we do not know how to divide
914   // Expr by Denominator for the following functions with empty implementation.
915   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
916   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
917   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
918   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
919   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
920   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
921   void visitUnknown(const SCEVUnknown *Numerator) {}
922   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
923 
924   void visitConstant(const SCEVConstant *Numerator) {
925     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
926       APInt NumeratorVal = Numerator->getAPInt();
927       APInt DenominatorVal = D->getAPInt();
928       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
929       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
930 
931       if (NumeratorBW > DenominatorBW)
932         DenominatorVal = DenominatorVal.sext(NumeratorBW);
933       else if (NumeratorBW < DenominatorBW)
934         NumeratorVal = NumeratorVal.sext(DenominatorBW);
935 
936       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
937       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
938       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
939       Quotient = SE.getConstant(QuotientVal);
940       Remainder = SE.getConstant(RemainderVal);
941       return;
942     }
943   }
944 
945   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
946     const SCEV *StartQ, *StartR, *StepQ, *StepR;
947     if (!Numerator->isAffine())
948       return cannotDivide(Numerator);
949     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
950     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
951     // Bail out if the types do not match.
952     Type *Ty = Denominator->getType();
953     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
954         Ty != StepQ->getType() || Ty != StepR->getType())
955       return cannotDivide(Numerator);
956     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
957                                 Numerator->getNoWrapFlags());
958     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
959                                  Numerator->getNoWrapFlags());
960   }
961 
962   void visitAddExpr(const SCEVAddExpr *Numerator) {
963     SmallVector<const SCEV *, 2> Qs, Rs;
964     Type *Ty = Denominator->getType();
965 
966     for (const SCEV *Op : Numerator->operands()) {
967       const SCEV *Q, *R;
968       divide(SE, Op, Denominator, &Q, &R);
969 
970       // Bail out if types do not match.
971       if (Ty != Q->getType() || Ty != R->getType())
972         return cannotDivide(Numerator);
973 
974       Qs.push_back(Q);
975       Rs.push_back(R);
976     }
977 
978     if (Qs.size() == 1) {
979       Quotient = Qs[0];
980       Remainder = Rs[0];
981       return;
982     }
983 
984     Quotient = SE.getAddExpr(Qs);
985     Remainder = SE.getAddExpr(Rs);
986   }
987 
988   void visitMulExpr(const SCEVMulExpr *Numerator) {
989     SmallVector<const SCEV *, 2> Qs;
990     Type *Ty = Denominator->getType();
991 
992     bool FoundDenominatorTerm = false;
993     for (const SCEV *Op : Numerator->operands()) {
994       // Bail out if types do not match.
995       if (Ty != Op->getType())
996         return cannotDivide(Numerator);
997 
998       if (FoundDenominatorTerm) {
999         Qs.push_back(Op);
1000         continue;
1001       }
1002 
1003       // Check whether Denominator divides one of the product operands.
1004       const SCEV *Q, *R;
1005       divide(SE, Op, Denominator, &Q, &R);
1006       if (!R->isZero()) {
1007         Qs.push_back(Op);
1008         continue;
1009       }
1010 
1011       // Bail out if types do not match.
1012       if (Ty != Q->getType())
1013         return cannotDivide(Numerator);
1014 
1015       FoundDenominatorTerm = true;
1016       Qs.push_back(Q);
1017     }
1018 
1019     if (FoundDenominatorTerm) {
1020       Remainder = Zero;
1021       if (Qs.size() == 1)
1022         Quotient = Qs[0];
1023       else
1024         Quotient = SE.getMulExpr(Qs);
1025       return;
1026     }
1027 
1028     if (!isa<SCEVUnknown>(Denominator))
1029       return cannotDivide(Numerator);
1030 
1031     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1032     ValueToValueMap RewriteMap;
1033     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1034         cast<SCEVConstant>(Zero)->getValue();
1035     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1036 
1037     if (Remainder->isZero()) {
1038       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1039       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1040           cast<SCEVConstant>(One)->getValue();
1041       Quotient =
1042           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1043       return;
1044     }
1045 
1046     // Quotient is (Numerator - Remainder) divided by Denominator.
1047     const SCEV *Q, *R;
1048     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1049     // This SCEV does not seem to simplify: fail the division here.
1050     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1051       return cannotDivide(Numerator);
1052     divide(SE, Diff, Denominator, &Q, &R);
1053     if (R != Zero)
1054       return cannotDivide(Numerator);
1055     Quotient = Q;
1056   }
1057 
1058 private:
1059   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1060                const SCEV *Denominator)
1061       : SE(S), Denominator(Denominator) {
1062     Zero = SE.getZero(Denominator->getType());
1063     One = SE.getOne(Denominator->getType());
1064 
1065     // We generally do not know how to divide Expr by Denominator. We
1066     // initialize the division to a "cannot divide" state to simplify the rest
1067     // of the code.
1068     cannotDivide(Numerator);
1069   }
1070 
1071   // Convenience function for giving up on the division. We set the quotient to
1072   // be equal to zero and the remainder to be equal to the numerator.
1073   void cannotDivide(const SCEV *Numerator) {
1074     Quotient = Zero;
1075     Remainder = Numerator;
1076   }
1077 
1078   ScalarEvolution &SE;
1079   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1080 };
1081 
1082 } // end anonymous namespace
1083 
1084 //===----------------------------------------------------------------------===//
1085 //                      Simple SCEV method implementations
1086 //===----------------------------------------------------------------------===//
1087 
1088 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
1089 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1090                                        ScalarEvolution &SE,
1091                                        Type *ResultTy) {
1092   // Handle the simplest case efficiently.
1093   if (K == 1)
1094     return SE.getTruncateOrZeroExtend(It, ResultTy);
1095 
1096   // We are using the following formula for BC(It, K):
1097   //
1098   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1099   //
1100   // Suppose, W is the bitwidth of the return value.  We must be prepared for
1101   // overflow.  Hence, we must assure that the result of our computation is
1102   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
1103   // safe in modular arithmetic.
1104   //
1105   // However, this code doesn't use exactly that formula; the formula it uses
1106   // is something like the following, where T is the number of factors of 2 in
1107   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1108   // exponentiation:
1109   //
1110   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1111   //
1112   // This formula is trivially equivalent to the previous formula.  However,
1113   // this formula can be implemented much more efficiently.  The trick is that
1114   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1115   // arithmetic.  To do exact division in modular arithmetic, all we have
1116   // to do is multiply by the inverse.  Therefore, this step can be done at
1117   // width W.
1118   //
1119   // The next issue is how to safely do the division by 2^T.  The way this
1120   // is done is by doing the multiplication step at a width of at least W + T
1121   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
1122   // when we perform the division by 2^T (which is equivalent to a right shift
1123   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
1124   // truncated out after the division by 2^T.
1125   //
1126   // In comparison to just directly using the first formula, this technique
1127   // is much more efficient; using the first formula requires W * K bits,
1128   // but this formula less than W + K bits. Also, the first formula requires
1129   // a division step, whereas this formula only requires multiplies and shifts.
1130   //
1131   // It doesn't matter whether the subtraction step is done in the calculation
1132   // width or the input iteration count's width; if the subtraction overflows,
1133   // the result must be zero anyway.  We prefer here to do it in the width of
1134   // the induction variable because it helps a lot for certain cases; CodeGen
1135   // isn't smart enough to ignore the overflow, which leads to much less
1136   // efficient code if the width of the subtraction is wider than the native
1137   // register width.
1138   //
1139   // (It's possible to not widen at all by pulling out factors of 2 before
1140   // the multiplication; for example, K=2 can be calculated as
1141   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1142   // extra arithmetic, so it's not an obvious win, and it gets
1143   // much more complicated for K > 3.)
1144 
1145   // Protection from insane SCEVs; this bound is conservative,
1146   // but it probably doesn't matter.
1147   if (K > 1000)
1148     return SE.getCouldNotCompute();
1149 
1150   unsigned W = SE.getTypeSizeInBits(ResultTy);
1151 
1152   // Calculate K! / 2^T and T; we divide out the factors of two before
1153   // multiplying for calculating K! / 2^T to avoid overflow.
1154   // Other overflow doesn't matter because we only care about the bottom
1155   // W bits of the result.
1156   APInt OddFactorial(W, 1);
1157   unsigned T = 1;
1158   for (unsigned i = 3; i <= K; ++i) {
1159     APInt Mult(W, i);
1160     unsigned TwoFactors = Mult.countTrailingZeros();
1161     T += TwoFactors;
1162     Mult.lshrInPlace(TwoFactors);
1163     OddFactorial *= Mult;
1164   }
1165 
1166   // We need at least W + T bits for the multiplication step
1167   unsigned CalculationBits = W + T;
1168 
1169   // Calculate 2^T, at width T+W.
1170   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1171 
1172   // Calculate the multiplicative inverse of K! / 2^T;
1173   // this multiplication factor will perform the exact division by
1174   // K! / 2^T.
1175   APInt Mod = APInt::getSignedMinValue(W+1);
1176   APInt MultiplyFactor = OddFactorial.zext(W+1);
1177   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1178   MultiplyFactor = MultiplyFactor.trunc(W);
1179 
1180   // Calculate the product, at width T+W
1181   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1182                                                       CalculationBits);
1183   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1184   for (unsigned i = 1; i != K; ++i) {
1185     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1186     Dividend = SE.getMulExpr(Dividend,
1187                              SE.getTruncateOrZeroExtend(S, CalculationTy));
1188   }
1189 
1190   // Divide by 2^T
1191   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1192 
1193   // Truncate the result, and divide by K! / 2^T.
1194 
1195   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1196                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1197 }
1198 
1199 /// Return the value of this chain of recurrences at the specified iteration
1200 /// number.  We can evaluate this recurrence by multiplying each element in the
1201 /// chain by the binomial coefficient corresponding to it.  In other words, we
1202 /// can evaluate {A,+,B,+,C,+,D} as:
1203 ///
1204 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1205 ///
1206 /// where BC(It, k) stands for binomial coefficient.
1207 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1208                                                 ScalarEvolution &SE) const {
1209   const SCEV *Result = getStart();
1210   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1211     // The computation is correct in the face of overflow provided that the
1212     // multiplication is performed _after_ the evaluation of the binomial
1213     // coefficient.
1214     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1215     if (isa<SCEVCouldNotCompute>(Coeff))
1216       return Coeff;
1217 
1218     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1219   }
1220   return Result;
1221 }
1222 
1223 //===----------------------------------------------------------------------===//
1224 //                    SCEV Expression folder implementations
1225 //===----------------------------------------------------------------------===//
1226 
1227 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1228                                              Type *Ty) {
1229   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1230          "This is not a truncating conversion!");
1231   assert(isSCEVable(Ty) &&
1232          "This is not a conversion to a SCEVable type!");
1233   Ty = getEffectiveSCEVType(Ty);
1234 
1235   FoldingSetNodeID ID;
1236   ID.AddInteger(scTruncate);
1237   ID.AddPointer(Op);
1238   ID.AddPointer(Ty);
1239   void *IP = nullptr;
1240   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1241 
1242   // Fold if the operand is constant.
1243   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1244     return getConstant(
1245       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1246 
1247   // trunc(trunc(x)) --> trunc(x)
1248   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1249     return getTruncateExpr(ST->getOperand(), Ty);
1250 
1251   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1252   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1253     return getTruncateOrSignExtend(SS->getOperand(), Ty);
1254 
1255   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1256   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1257     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1258 
1259   // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1260   // eliminate all the truncates, or we replace other casts with truncates.
1261   if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1262     SmallVector<const SCEV *, 4> Operands;
1263     bool hasTrunc = false;
1264     for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1265       const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1266       if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1267         hasTrunc = isa<SCEVTruncateExpr>(S);
1268       Operands.push_back(S);
1269     }
1270     if (!hasTrunc)
1271       return getAddExpr(Operands);
1272     // In spite we checked in the beginning that ID is not in the cache,
1273     // it is possible that during recursion and different modification
1274     // ID came to cache, so if we found it, just return it.
1275     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1276       return S;
1277   }
1278 
1279   // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1280   // eliminate all the truncates, or we replace other casts with truncates.
1281   if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1282     SmallVector<const SCEV *, 4> Operands;
1283     bool hasTrunc = false;
1284     for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1285       const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1286       if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1287         hasTrunc = isa<SCEVTruncateExpr>(S);
1288       Operands.push_back(S);
1289     }
1290     if (!hasTrunc)
1291       return getMulExpr(Operands);
1292     // In spite we checked in the beginning that ID is not in the cache,
1293     // it is possible that during recursion and different modification
1294     // ID came to cache, so if we found it, just return it.
1295     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1296       return S;
1297   }
1298 
1299   // If the input value is a chrec scev, truncate the chrec's operands.
1300   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1301     SmallVector<const SCEV *, 4> Operands;
1302     for (const SCEV *Op : AddRec->operands())
1303       Operands.push_back(getTruncateExpr(Op, Ty));
1304     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1305   }
1306 
1307   // The cast wasn't folded; create an explicit cast node. We can reuse
1308   // the existing insert position since if we get here, we won't have
1309   // made any changes which would invalidate it.
1310   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1311                                                  Op, Ty);
1312   UniqueSCEVs.InsertNode(S, IP);
1313   addToLoopUseLists(S);
1314   return S;
1315 }
1316 
1317 // Get the limit of a recurrence such that incrementing by Step cannot cause
1318 // signed overflow as long as the value of the recurrence within the
1319 // loop does not exceed this limit before incrementing.
1320 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1321                                                  ICmpInst::Predicate *Pred,
1322                                                  ScalarEvolution *SE) {
1323   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1324   if (SE->isKnownPositive(Step)) {
1325     *Pred = ICmpInst::ICMP_SLT;
1326     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1327                            SE->getSignedRangeMax(Step));
1328   }
1329   if (SE->isKnownNegative(Step)) {
1330     *Pred = ICmpInst::ICMP_SGT;
1331     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1332                            SE->getSignedRangeMin(Step));
1333   }
1334   return nullptr;
1335 }
1336 
1337 // Get the limit of a recurrence such that incrementing by Step cannot cause
1338 // unsigned overflow as long as the value of the recurrence within the loop does
1339 // not exceed this limit before incrementing.
1340 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1341                                                    ICmpInst::Predicate *Pred,
1342                                                    ScalarEvolution *SE) {
1343   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1344   *Pred = ICmpInst::ICMP_ULT;
1345 
1346   return SE->getConstant(APInt::getMinValue(BitWidth) -
1347                          SE->getUnsignedRangeMax(Step));
1348 }
1349 
1350 namespace {
1351 
1352 struct ExtendOpTraitsBase {
1353   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1354                                                           unsigned);
1355 };
1356 
1357 // Used to make code generic over signed and unsigned overflow.
1358 template <typename ExtendOp> struct ExtendOpTraits {
1359   // Members present:
1360   //
1361   // static const SCEV::NoWrapFlags WrapType;
1362   //
1363   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1364   //
1365   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1366   //                                           ICmpInst::Predicate *Pred,
1367   //                                           ScalarEvolution *SE);
1368 };
1369 
1370 template <>
1371 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1372   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1373 
1374   static const GetExtendExprTy GetExtendExpr;
1375 
1376   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1377                                              ICmpInst::Predicate *Pred,
1378                                              ScalarEvolution *SE) {
1379     return getSignedOverflowLimitForStep(Step, Pred, SE);
1380   }
1381 };
1382 
1383 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1384     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1385 
1386 template <>
1387 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1388   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1389 
1390   static const GetExtendExprTy GetExtendExpr;
1391 
1392   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1393                                              ICmpInst::Predicate *Pred,
1394                                              ScalarEvolution *SE) {
1395     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1396   }
1397 };
1398 
1399 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1400     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1401 
1402 } // end anonymous namespace
1403 
1404 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1405 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1406 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1407 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1408 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1409 // expression "Step + sext/zext(PreIncAR)" is congruent with
1410 // "sext/zext(PostIncAR)"
1411 template <typename ExtendOpTy>
1412 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1413                                         ScalarEvolution *SE, unsigned Depth) {
1414   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1415   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1416 
1417   const Loop *L = AR->getLoop();
1418   const SCEV *Start = AR->getStart();
1419   const SCEV *Step = AR->getStepRecurrence(*SE);
1420 
1421   // Check for a simple looking step prior to loop entry.
1422   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1423   if (!SA)
1424     return nullptr;
1425 
1426   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1427   // subtraction is expensive. For this purpose, perform a quick and dirty
1428   // difference, by checking for Step in the operand list.
1429   SmallVector<const SCEV *, 4> DiffOps;
1430   for (const SCEV *Op : SA->operands())
1431     if (Op != Step)
1432       DiffOps.push_back(Op);
1433 
1434   if (DiffOps.size() == SA->getNumOperands())
1435     return nullptr;
1436 
1437   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1438   // `Step`:
1439 
1440   // 1. NSW/NUW flags on the step increment.
1441   auto PreStartFlags =
1442     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1443   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1444   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1445       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1446 
1447   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1448   // "S+X does not sign/unsign-overflow".
1449   //
1450 
1451   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1452   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1453       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1454     return PreStart;
1455 
1456   // 2. Direct overflow check on the step operation's expression.
1457   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1458   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1459   const SCEV *OperandExtendedStart =
1460       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1461                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1462   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1463     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1464       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1465       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1466       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1467       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1468     }
1469     return PreStart;
1470   }
1471 
1472   // 3. Loop precondition.
1473   ICmpInst::Predicate Pred;
1474   const SCEV *OverflowLimit =
1475       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1476 
1477   if (OverflowLimit &&
1478       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1479     return PreStart;
1480 
1481   return nullptr;
1482 }
1483 
1484 // Get the normalized zero or sign extended expression for this AddRec's Start.
1485 template <typename ExtendOpTy>
1486 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1487                                         ScalarEvolution *SE,
1488                                         unsigned Depth) {
1489   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1490 
1491   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1492   if (!PreStart)
1493     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1494 
1495   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1496                                              Depth),
1497                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1498 }
1499 
1500 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1501 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1502 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1503 //
1504 // Formally:
1505 //
1506 //     {S,+,X} == {S-T,+,X} + T
1507 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1508 //
1509 // If ({S-T,+,X} + T) does not overflow  ... (1)
1510 //
1511 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1512 //
1513 // If {S-T,+,X} does not overflow  ... (2)
1514 //
1515 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1516 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1517 //
1518 // If (S-T)+T does not overflow  ... (3)
1519 //
1520 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1521 //      == {Ext(S),+,Ext(X)} == LHS
1522 //
1523 // Thus, if (1), (2) and (3) are true for some T, then
1524 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1525 //
1526 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1527 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1528 // to check for (1) and (2).
1529 //
1530 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1531 // is `Delta` (defined below).
1532 template <typename ExtendOpTy>
1533 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1534                                                 const SCEV *Step,
1535                                                 const Loop *L) {
1536   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1537 
1538   // We restrict `Start` to a constant to prevent SCEV from spending too much
1539   // time here.  It is correct (but more expensive) to continue with a
1540   // non-constant `Start` and do a general SCEV subtraction to compute
1541   // `PreStart` below.
1542   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1543   if (!StartC)
1544     return false;
1545 
1546   APInt StartAI = StartC->getAPInt();
1547 
1548   for (unsigned Delta : {-2, -1, 1, 2}) {
1549     const SCEV *PreStart = getConstant(StartAI - Delta);
1550 
1551     FoldingSetNodeID ID;
1552     ID.AddInteger(scAddRecExpr);
1553     ID.AddPointer(PreStart);
1554     ID.AddPointer(Step);
1555     ID.AddPointer(L);
1556     void *IP = nullptr;
1557     const auto *PreAR =
1558       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1559 
1560     // Give up if we don't already have the add recurrence we need because
1561     // actually constructing an add recurrence is relatively expensive.
1562     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1563       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1564       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1565       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1566           DeltaS, &Pred, this);
1567       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1568         return true;
1569     }
1570   }
1571 
1572   return false;
1573 }
1574 
1575 const SCEV *
1576 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1577   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1578          "This is not an extending conversion!");
1579   assert(isSCEVable(Ty) &&
1580          "This is not a conversion to a SCEVable type!");
1581   Ty = getEffectiveSCEVType(Ty);
1582 
1583   // Fold if the operand is constant.
1584   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1585     return getConstant(
1586       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1587 
1588   // zext(zext(x)) --> zext(x)
1589   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1590     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1591 
1592   // Before doing any expensive analysis, check to see if we've already
1593   // computed a SCEV for this Op and Ty.
1594   FoldingSetNodeID ID;
1595   ID.AddInteger(scZeroExtend);
1596   ID.AddPointer(Op);
1597   ID.AddPointer(Ty);
1598   void *IP = nullptr;
1599   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1600   if (Depth > MaxExtDepth) {
1601     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1602                                                      Op, Ty);
1603     UniqueSCEVs.InsertNode(S, IP);
1604     addToLoopUseLists(S);
1605     return S;
1606   }
1607 
1608   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1609   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1610     // It's possible the bits taken off by the truncate were all zero bits. If
1611     // so, we should be able to simplify this further.
1612     const SCEV *X = ST->getOperand();
1613     ConstantRange CR = getUnsignedRange(X);
1614     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1615     unsigned NewBits = getTypeSizeInBits(Ty);
1616     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1617             CR.zextOrTrunc(NewBits)))
1618       return getTruncateOrZeroExtend(X, Ty);
1619   }
1620 
1621   // If the input value is a chrec scev, and we can prove that the value
1622   // did not overflow the old, smaller, value, we can zero extend all of the
1623   // operands (often constants).  This allows analysis of something like
1624   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1625   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1626     if (AR->isAffine()) {
1627       const SCEV *Start = AR->getStart();
1628       const SCEV *Step = AR->getStepRecurrence(*this);
1629       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1630       const Loop *L = AR->getLoop();
1631 
1632       if (!AR->hasNoUnsignedWrap()) {
1633         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1634         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1635       }
1636 
1637       // If we have special knowledge that this addrec won't overflow,
1638       // we don't need to do any further analysis.
1639       if (AR->hasNoUnsignedWrap())
1640         return getAddRecExpr(
1641             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1642             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1643 
1644       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1645       // Note that this serves two purposes: It filters out loops that are
1646       // simply not analyzable, and it covers the case where this code is
1647       // being called from within backedge-taken count analysis, such that
1648       // attempting to ask for the backedge-taken count would likely result
1649       // in infinite recursion. In the later case, the analysis code will
1650       // cope with a conservative value, and it will take care to purge
1651       // that value once it has finished.
1652       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1653       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1654         // Manually compute the final value for AR, checking for
1655         // overflow.
1656 
1657         // Check whether the backedge-taken count can be losslessly casted to
1658         // the addrec's type. The count is always unsigned.
1659         const SCEV *CastedMaxBECount =
1660           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1661         const SCEV *RecastedMaxBECount =
1662           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1663         if (MaxBECount == RecastedMaxBECount) {
1664           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1665           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1666           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1667                                         SCEV::FlagAnyWrap, Depth + 1);
1668           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1669                                                           SCEV::FlagAnyWrap,
1670                                                           Depth + 1),
1671                                                WideTy, Depth + 1);
1672           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1673           const SCEV *WideMaxBECount =
1674             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1675           const SCEV *OperandExtendedAdd =
1676             getAddExpr(WideStart,
1677                        getMulExpr(WideMaxBECount,
1678                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1679                                   SCEV::FlagAnyWrap, Depth + 1),
1680                        SCEV::FlagAnyWrap, Depth + 1);
1681           if (ZAdd == OperandExtendedAdd) {
1682             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1683             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1684             // Return the expression with the addrec on the outside.
1685             return getAddRecExpr(
1686                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1687                                                          Depth + 1),
1688                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1689                 AR->getNoWrapFlags());
1690           }
1691           // Similar to above, only this time treat the step value as signed.
1692           // This covers loops that count down.
1693           OperandExtendedAdd =
1694             getAddExpr(WideStart,
1695                        getMulExpr(WideMaxBECount,
1696                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1697                                   SCEV::FlagAnyWrap, Depth + 1),
1698                        SCEV::FlagAnyWrap, Depth + 1);
1699           if (ZAdd == OperandExtendedAdd) {
1700             // Cache knowledge of AR NW, which is propagated to this AddRec.
1701             // Negative step causes unsigned wrap, but it still can't self-wrap.
1702             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1703             // Return the expression with the addrec on the outside.
1704             return getAddRecExpr(
1705                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1706                                                          Depth + 1),
1707                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1708                 AR->getNoWrapFlags());
1709           }
1710         }
1711       }
1712 
1713       // Normally, in the cases we can prove no-overflow via a
1714       // backedge guarding condition, we can also compute a backedge
1715       // taken count for the loop.  The exceptions are assumptions and
1716       // guards present in the loop -- SCEV is not great at exploiting
1717       // these to compute max backedge taken counts, but can still use
1718       // these to prove lack of overflow.  Use this fact to avoid
1719       // doing extra work that may not pay off.
1720       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1721           !AC.assumptions().empty()) {
1722         // If the backedge is guarded by a comparison with the pre-inc
1723         // value the addrec is safe. Also, if the entry is guarded by
1724         // a comparison with the start value and the backedge is
1725         // guarded by a comparison with the post-inc value, the addrec
1726         // is safe.
1727         if (isKnownPositive(Step)) {
1728           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1729                                       getUnsignedRangeMax(Step));
1730           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1731               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1732             // Cache knowledge of AR NUW, which is propagated to this
1733             // AddRec.
1734             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1735             // Return the expression with the addrec on the outside.
1736             return getAddRecExpr(
1737                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1738                                                          Depth + 1),
1739                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1740                 AR->getNoWrapFlags());
1741           }
1742         } else if (isKnownNegative(Step)) {
1743           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1744                                       getSignedRangeMin(Step));
1745           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1746               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1747             // Cache knowledge of AR NW, which is propagated to this
1748             // AddRec.  Negative step causes unsigned wrap, but it
1749             // still can't self-wrap.
1750             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1751             // Return the expression with the addrec on the outside.
1752             return getAddRecExpr(
1753                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1754                                                          Depth + 1),
1755                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1756                 AR->getNoWrapFlags());
1757           }
1758         }
1759       }
1760 
1761       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1762         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1763         return getAddRecExpr(
1764             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1765             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1766       }
1767     }
1768 
1769   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1770     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1771     if (SA->hasNoUnsignedWrap()) {
1772       // If the addition does not unsign overflow then we can, by definition,
1773       // commute the zero extension with the addition operation.
1774       SmallVector<const SCEV *, 4> Ops;
1775       for (const auto *Op : SA->operands())
1776         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1777       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1778     }
1779   }
1780 
1781   // The cast wasn't folded; create an explicit cast node.
1782   // Recompute the insert position, as it may have been invalidated.
1783   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1784   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1785                                                    Op, Ty);
1786   UniqueSCEVs.InsertNode(S, IP);
1787   addToLoopUseLists(S);
1788   return S;
1789 }
1790 
1791 const SCEV *
1792 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1793   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1794          "This is not an extending conversion!");
1795   assert(isSCEVable(Ty) &&
1796          "This is not a conversion to a SCEVable type!");
1797   Ty = getEffectiveSCEVType(Ty);
1798 
1799   // Fold if the operand is constant.
1800   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1801     return getConstant(
1802       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1803 
1804   // sext(sext(x)) --> sext(x)
1805   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1806     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1807 
1808   // sext(zext(x)) --> zext(x)
1809   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1810     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1811 
1812   // Before doing any expensive analysis, check to see if we've already
1813   // computed a SCEV for this Op and Ty.
1814   FoldingSetNodeID ID;
1815   ID.AddInteger(scSignExtend);
1816   ID.AddPointer(Op);
1817   ID.AddPointer(Ty);
1818   void *IP = nullptr;
1819   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1820   // Limit recursion depth.
1821   if (Depth > MaxExtDepth) {
1822     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1823                                                      Op, Ty);
1824     UniqueSCEVs.InsertNode(S, IP);
1825     addToLoopUseLists(S);
1826     return S;
1827   }
1828 
1829   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1830   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1831     // It's possible the bits taken off by the truncate were all sign bits. If
1832     // so, we should be able to simplify this further.
1833     const SCEV *X = ST->getOperand();
1834     ConstantRange CR = getSignedRange(X);
1835     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1836     unsigned NewBits = getTypeSizeInBits(Ty);
1837     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1838             CR.sextOrTrunc(NewBits)))
1839       return getTruncateOrSignExtend(X, Ty);
1840   }
1841 
1842   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1843   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1844     if (SA->getNumOperands() == 2) {
1845       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1846       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1847       if (SMul && SC1) {
1848         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
1849           const APInt &C1 = SC1->getAPInt();
1850           const APInt &C2 = SC2->getAPInt();
1851           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
1852               C2.ugt(C1) && C2.isPowerOf2())
1853             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
1854                               getSignExtendExpr(SMul, Ty, Depth + 1),
1855                               SCEV::FlagAnyWrap, Depth + 1);
1856         }
1857       }
1858     }
1859 
1860     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1861     if (SA->hasNoSignedWrap()) {
1862       // If the addition does not sign overflow then we can, by definition,
1863       // commute the sign extension with the addition operation.
1864       SmallVector<const SCEV *, 4> Ops;
1865       for (const auto *Op : SA->operands())
1866         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1867       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1868     }
1869   }
1870   // If the input value is a chrec scev, and we can prove that the value
1871   // did not overflow the old, smaller, value, we can sign extend all of the
1872   // operands (often constants).  This allows analysis of something like
1873   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1874   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1875     if (AR->isAffine()) {
1876       const SCEV *Start = AR->getStart();
1877       const SCEV *Step = AR->getStepRecurrence(*this);
1878       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1879       const Loop *L = AR->getLoop();
1880 
1881       if (!AR->hasNoSignedWrap()) {
1882         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1883         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1884       }
1885 
1886       // If we have special knowledge that this addrec won't overflow,
1887       // we don't need to do any further analysis.
1888       if (AR->hasNoSignedWrap())
1889         return getAddRecExpr(
1890             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1891             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1892 
1893       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1894       // Note that this serves two purposes: It filters out loops that are
1895       // simply not analyzable, and it covers the case where this code is
1896       // being called from within backedge-taken count analysis, such that
1897       // attempting to ask for the backedge-taken count would likely result
1898       // in infinite recursion. In the later case, the analysis code will
1899       // cope with a conservative value, and it will take care to purge
1900       // that value once it has finished.
1901       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1902       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1903         // Manually compute the final value for AR, checking for
1904         // overflow.
1905 
1906         // Check whether the backedge-taken count can be losslessly casted to
1907         // the addrec's type. The count is always unsigned.
1908         const SCEV *CastedMaxBECount =
1909           getTruncateOrZeroExtend(MaxBECount, Start->getType());
1910         const SCEV *RecastedMaxBECount =
1911           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1912         if (MaxBECount == RecastedMaxBECount) {
1913           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1914           // Check whether Start+Step*MaxBECount has no signed overflow.
1915           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1916                                         SCEV::FlagAnyWrap, Depth + 1);
1917           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1918                                                           SCEV::FlagAnyWrap,
1919                                                           Depth + 1),
1920                                                WideTy, Depth + 1);
1921           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1922           const SCEV *WideMaxBECount =
1923             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1924           const SCEV *OperandExtendedAdd =
1925             getAddExpr(WideStart,
1926                        getMulExpr(WideMaxBECount,
1927                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1928                                   SCEV::FlagAnyWrap, Depth + 1),
1929                        SCEV::FlagAnyWrap, Depth + 1);
1930           if (SAdd == OperandExtendedAdd) {
1931             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1932             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1933             // Return the expression with the addrec on the outside.
1934             return getAddRecExpr(
1935                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1936                                                          Depth + 1),
1937                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1938                 AR->getNoWrapFlags());
1939           }
1940           // Similar to above, only this time treat the step value as unsigned.
1941           // This covers loops that count up with an unsigned step.
1942           OperandExtendedAdd =
1943             getAddExpr(WideStart,
1944                        getMulExpr(WideMaxBECount,
1945                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1946                                   SCEV::FlagAnyWrap, Depth + 1),
1947                        SCEV::FlagAnyWrap, Depth + 1);
1948           if (SAdd == OperandExtendedAdd) {
1949             // If AR wraps around then
1950             //
1951             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1952             // => SAdd != OperandExtendedAdd
1953             //
1954             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1955             // (SAdd == OperandExtendedAdd => AR is NW)
1956 
1957             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1958 
1959             // Return the expression with the addrec on the outside.
1960             return getAddRecExpr(
1961                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1962                                                          Depth + 1),
1963                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1964                 AR->getNoWrapFlags());
1965           }
1966         }
1967       }
1968 
1969       // Normally, in the cases we can prove no-overflow via a
1970       // backedge guarding condition, we can also compute a backedge
1971       // taken count for the loop.  The exceptions are assumptions and
1972       // guards present in the loop -- SCEV is not great at exploiting
1973       // these to compute max backedge taken counts, but can still use
1974       // these to prove lack of overflow.  Use this fact to avoid
1975       // doing extra work that may not pay off.
1976 
1977       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1978           !AC.assumptions().empty()) {
1979         // If the backedge is guarded by a comparison with the pre-inc
1980         // value the addrec is safe. Also, if the entry is guarded by
1981         // a comparison with the start value and the backedge is
1982         // guarded by a comparison with the post-inc value, the addrec
1983         // is safe.
1984         ICmpInst::Predicate Pred;
1985         const SCEV *OverflowLimit =
1986             getSignedOverflowLimitForStep(Step, &Pred, this);
1987         if (OverflowLimit &&
1988             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1989              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
1990           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1991           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1992           return getAddRecExpr(
1993               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1994               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1995         }
1996       }
1997 
1998       // If Start and Step are constants, check if we can apply this
1999       // transformation:
2000       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
2001       auto *SC1 = dyn_cast<SCEVConstant>(Start);
2002       auto *SC2 = dyn_cast<SCEVConstant>(Step);
2003       if (SC1 && SC2) {
2004         const APInt &C1 = SC1->getAPInt();
2005         const APInt &C2 = SC2->getAPInt();
2006         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
2007             C2.isPowerOf2()) {
2008           Start = getSignExtendExpr(Start, Ty, Depth + 1);
2009           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
2010                                             AR->getNoWrapFlags());
2011           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
2012                             SCEV::FlagAnyWrap, Depth + 1);
2013         }
2014       }
2015 
2016       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2017         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2018         return getAddRecExpr(
2019             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2020             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2021       }
2022     }
2023 
2024   // If the input value is provably positive and we could not simplify
2025   // away the sext build a zext instead.
2026   if (isKnownNonNegative(Op))
2027     return getZeroExtendExpr(Op, Ty, Depth + 1);
2028 
2029   // The cast wasn't folded; create an explicit cast node.
2030   // Recompute the insert position, as it may have been invalidated.
2031   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2032   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2033                                                    Op, Ty);
2034   UniqueSCEVs.InsertNode(S, IP);
2035   addToLoopUseLists(S);
2036   return S;
2037 }
2038 
2039 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2040 /// unspecified bits out to the given type.
2041 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2042                                               Type *Ty) {
2043   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2044          "This is not an extending conversion!");
2045   assert(isSCEVable(Ty) &&
2046          "This is not a conversion to a SCEVable type!");
2047   Ty = getEffectiveSCEVType(Ty);
2048 
2049   // Sign-extend negative constants.
2050   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2051     if (SC->getAPInt().isNegative())
2052       return getSignExtendExpr(Op, Ty);
2053 
2054   // Peel off a truncate cast.
2055   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2056     const SCEV *NewOp = T->getOperand();
2057     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2058       return getAnyExtendExpr(NewOp, Ty);
2059     return getTruncateOrNoop(NewOp, Ty);
2060   }
2061 
2062   // Next try a zext cast. If the cast is folded, use it.
2063   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2064   if (!isa<SCEVZeroExtendExpr>(ZExt))
2065     return ZExt;
2066 
2067   // Next try a sext cast. If the cast is folded, use it.
2068   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2069   if (!isa<SCEVSignExtendExpr>(SExt))
2070     return SExt;
2071 
2072   // Force the cast to be folded into the operands of an addrec.
2073   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2074     SmallVector<const SCEV *, 4> Ops;
2075     for (const SCEV *Op : AR->operands())
2076       Ops.push_back(getAnyExtendExpr(Op, Ty));
2077     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2078   }
2079 
2080   // If the expression is obviously signed, use the sext cast value.
2081   if (isa<SCEVSMaxExpr>(Op))
2082     return SExt;
2083 
2084   // Absent any other information, use the zext cast value.
2085   return ZExt;
2086 }
2087 
2088 /// Process the given Ops list, which is a list of operands to be added under
2089 /// the given scale, update the given map. This is a helper function for
2090 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2091 /// that would form an add expression like this:
2092 ///
2093 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2094 ///
2095 /// where A and B are constants, update the map with these values:
2096 ///
2097 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2098 ///
2099 /// and add 13 + A*B*29 to AccumulatedConstant.
2100 /// This will allow getAddRecExpr to produce this:
2101 ///
2102 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2103 ///
2104 /// This form often exposes folding opportunities that are hidden in
2105 /// the original operand list.
2106 ///
2107 /// Return true iff it appears that any interesting folding opportunities
2108 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2109 /// the common case where no interesting opportunities are present, and
2110 /// is also used as a check to avoid infinite recursion.
2111 static bool
2112 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2113                              SmallVectorImpl<const SCEV *> &NewOps,
2114                              APInt &AccumulatedConstant,
2115                              const SCEV *const *Ops, size_t NumOperands,
2116                              const APInt &Scale,
2117                              ScalarEvolution &SE) {
2118   bool Interesting = false;
2119 
2120   // Iterate over the add operands. They are sorted, with constants first.
2121   unsigned i = 0;
2122   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2123     ++i;
2124     // Pull a buried constant out to the outside.
2125     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2126       Interesting = true;
2127     AccumulatedConstant += Scale * C->getAPInt();
2128   }
2129 
2130   // Next comes everything else. We're especially interested in multiplies
2131   // here, but they're in the middle, so just visit the rest with one loop.
2132   for (; i != NumOperands; ++i) {
2133     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2134     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2135       APInt NewScale =
2136           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2137       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2138         // A multiplication of a constant with another add; recurse.
2139         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2140         Interesting |=
2141           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2142                                        Add->op_begin(), Add->getNumOperands(),
2143                                        NewScale, SE);
2144       } else {
2145         // A multiplication of a constant with some other value. Update
2146         // the map.
2147         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2148         const SCEV *Key = SE.getMulExpr(MulOps);
2149         auto Pair = M.insert({Key, NewScale});
2150         if (Pair.second) {
2151           NewOps.push_back(Pair.first->first);
2152         } else {
2153           Pair.first->second += NewScale;
2154           // The map already had an entry for this value, which may indicate
2155           // a folding opportunity.
2156           Interesting = true;
2157         }
2158       }
2159     } else {
2160       // An ordinary operand. Update the map.
2161       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2162           M.insert({Ops[i], Scale});
2163       if (Pair.second) {
2164         NewOps.push_back(Pair.first->first);
2165       } else {
2166         Pair.first->second += Scale;
2167         // The map already had an entry for this value, which may indicate
2168         // a folding opportunity.
2169         Interesting = true;
2170       }
2171     }
2172   }
2173 
2174   return Interesting;
2175 }
2176 
2177 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2178 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2179 // can't-overflow flags for the operation if possible.
2180 static SCEV::NoWrapFlags
2181 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2182                       const SmallVectorImpl<const SCEV *> &Ops,
2183                       SCEV::NoWrapFlags Flags) {
2184   using namespace std::placeholders;
2185 
2186   using OBO = OverflowingBinaryOperator;
2187 
2188   bool CanAnalyze =
2189       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2190   (void)CanAnalyze;
2191   assert(CanAnalyze && "don't call from other places!");
2192 
2193   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2194   SCEV::NoWrapFlags SignOrUnsignWrap =
2195       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2196 
2197   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2198   auto IsKnownNonNegative = [&](const SCEV *S) {
2199     return SE->isKnownNonNegative(S);
2200   };
2201 
2202   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2203     Flags =
2204         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2205 
2206   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2207 
2208   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
2209       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
2210 
2211     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
2212     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
2213 
2214     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2215     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2216       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2217           Instruction::Add, C, OBO::NoSignedWrap);
2218       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2219         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2220     }
2221     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2222       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2223           Instruction::Add, C, OBO::NoUnsignedWrap);
2224       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2225         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2226     }
2227   }
2228 
2229   return Flags;
2230 }
2231 
2232 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2233   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2234 }
2235 
2236 /// Get a canonical add expression, or something simpler if possible.
2237 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2238                                         SCEV::NoWrapFlags Flags,
2239                                         unsigned Depth) {
2240   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2241          "only nuw or nsw allowed");
2242   assert(!Ops.empty() && "Cannot get empty add!");
2243   if (Ops.size() == 1) return Ops[0];
2244 #ifndef NDEBUG
2245   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2246   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2247     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2248            "SCEVAddExpr operand types don't match!");
2249 #endif
2250 
2251   // Sort by complexity, this groups all similar expression types together.
2252   GroupByComplexity(Ops, &LI, DT);
2253 
2254   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2255 
2256   // If there are any constants, fold them together.
2257   unsigned Idx = 0;
2258   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2259     ++Idx;
2260     assert(Idx < Ops.size());
2261     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2262       // We found two constants, fold them together!
2263       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2264       if (Ops.size() == 2) return Ops[0];
2265       Ops.erase(Ops.begin()+1);  // Erase the folded element
2266       LHSC = cast<SCEVConstant>(Ops[0]);
2267     }
2268 
2269     // If we are left with a constant zero being added, strip it off.
2270     if (LHSC->getValue()->isZero()) {
2271       Ops.erase(Ops.begin());
2272       --Idx;
2273     }
2274 
2275     if (Ops.size() == 1) return Ops[0];
2276   }
2277 
2278   // Limit recursion calls depth.
2279   if (Depth > MaxArithDepth)
2280     return getOrCreateAddExpr(Ops, Flags);
2281 
2282   // Okay, check to see if the same value occurs in the operand list more than
2283   // once.  If so, merge them together into an multiply expression.  Since we
2284   // sorted the list, these values are required to be adjacent.
2285   Type *Ty = Ops[0]->getType();
2286   bool FoundMatch = false;
2287   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2288     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2289       // Scan ahead to count how many equal operands there are.
2290       unsigned Count = 2;
2291       while (i+Count != e && Ops[i+Count] == Ops[i])
2292         ++Count;
2293       // Merge the values into a multiply.
2294       const SCEV *Scale = getConstant(Ty, Count);
2295       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2296       if (Ops.size() == Count)
2297         return Mul;
2298       Ops[i] = Mul;
2299       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2300       --i; e -= Count - 1;
2301       FoundMatch = true;
2302     }
2303   if (FoundMatch)
2304     return getAddExpr(Ops, Flags, Depth + 1);
2305 
2306   // Check for truncates. If all the operands are truncated from the same
2307   // type, see if factoring out the truncate would permit the result to be
2308   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2309   // if the contents of the resulting outer trunc fold to something simple.
2310   auto FindTruncSrcType = [&]() -> Type * {
2311     // We're ultimately looking to fold an addrec of truncs and muls of only
2312     // constants and truncs, so if we find any other types of SCEV
2313     // as operands of the addrec then we bail and return nullptr here.
2314     // Otherwise, we return the type of the operand of a trunc that we find.
2315     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2316       return T->getOperand()->getType();
2317     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2318       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2319       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2320         return T->getOperand()->getType();
2321     }
2322     return nullptr;
2323   };
2324   if (auto *SrcType = FindTruncSrcType()) {
2325     SmallVector<const SCEV *, 8> LargeOps;
2326     bool Ok = true;
2327     // Check all the operands to see if they can be represented in the
2328     // source type of the truncate.
2329     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2330       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2331         if (T->getOperand()->getType() != SrcType) {
2332           Ok = false;
2333           break;
2334         }
2335         LargeOps.push_back(T->getOperand());
2336       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2337         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2338       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2339         SmallVector<const SCEV *, 8> LargeMulOps;
2340         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2341           if (const SCEVTruncateExpr *T =
2342                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2343             if (T->getOperand()->getType() != SrcType) {
2344               Ok = false;
2345               break;
2346             }
2347             LargeMulOps.push_back(T->getOperand());
2348           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2349             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2350           } else {
2351             Ok = false;
2352             break;
2353           }
2354         }
2355         if (Ok)
2356           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2357       } else {
2358         Ok = false;
2359         break;
2360       }
2361     }
2362     if (Ok) {
2363       // Evaluate the expression in the larger type.
2364       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
2365       // If it folds to something simple, use it. Otherwise, don't.
2366       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2367         return getTruncateExpr(Fold, Ty);
2368     }
2369   }
2370 
2371   // Skip past any other cast SCEVs.
2372   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2373     ++Idx;
2374 
2375   // If there are add operands they would be next.
2376   if (Idx < Ops.size()) {
2377     bool DeletedAdd = false;
2378     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2379       if (Ops.size() > AddOpsInlineThreshold ||
2380           Add->getNumOperands() > AddOpsInlineThreshold)
2381         break;
2382       // If we have an add, expand the add operands onto the end of the operands
2383       // list.
2384       Ops.erase(Ops.begin()+Idx);
2385       Ops.append(Add->op_begin(), Add->op_end());
2386       DeletedAdd = true;
2387     }
2388 
2389     // If we deleted at least one add, we added operands to the end of the list,
2390     // and they are not necessarily sorted.  Recurse to resort and resimplify
2391     // any operands we just acquired.
2392     if (DeletedAdd)
2393       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2394   }
2395 
2396   // Skip over the add expression until we get to a multiply.
2397   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2398     ++Idx;
2399 
2400   // Check to see if there are any folding opportunities present with
2401   // operands multiplied by constant values.
2402   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2403     uint64_t BitWidth = getTypeSizeInBits(Ty);
2404     DenseMap<const SCEV *, APInt> M;
2405     SmallVector<const SCEV *, 8> NewOps;
2406     APInt AccumulatedConstant(BitWidth, 0);
2407     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2408                                      Ops.data(), Ops.size(),
2409                                      APInt(BitWidth, 1), *this)) {
2410       struct APIntCompare {
2411         bool operator()(const APInt &LHS, const APInt &RHS) const {
2412           return LHS.ult(RHS);
2413         }
2414       };
2415 
2416       // Some interesting folding opportunity is present, so its worthwhile to
2417       // re-generate the operands list. Group the operands by constant scale,
2418       // to avoid multiplying by the same constant scale multiple times.
2419       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2420       for (const SCEV *NewOp : NewOps)
2421         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2422       // Re-generate the operands list.
2423       Ops.clear();
2424       if (AccumulatedConstant != 0)
2425         Ops.push_back(getConstant(AccumulatedConstant));
2426       for (auto &MulOp : MulOpLists)
2427         if (MulOp.first != 0)
2428           Ops.push_back(getMulExpr(
2429               getConstant(MulOp.first),
2430               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2431               SCEV::FlagAnyWrap, Depth + 1));
2432       if (Ops.empty())
2433         return getZero(Ty);
2434       if (Ops.size() == 1)
2435         return Ops[0];
2436       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2437     }
2438   }
2439 
2440   // If we are adding something to a multiply expression, make sure the
2441   // something is not already an operand of the multiply.  If so, merge it into
2442   // the multiply.
2443   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2444     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2445     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2446       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2447       if (isa<SCEVConstant>(MulOpSCEV))
2448         continue;
2449       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2450         if (MulOpSCEV == Ops[AddOp]) {
2451           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2452           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2453           if (Mul->getNumOperands() != 2) {
2454             // If the multiply has more than two operands, we must get the
2455             // Y*Z term.
2456             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2457                                                 Mul->op_begin()+MulOp);
2458             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2459             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2460           }
2461           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2462           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2463           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2464                                             SCEV::FlagAnyWrap, Depth + 1);
2465           if (Ops.size() == 2) return OuterMul;
2466           if (AddOp < Idx) {
2467             Ops.erase(Ops.begin()+AddOp);
2468             Ops.erase(Ops.begin()+Idx-1);
2469           } else {
2470             Ops.erase(Ops.begin()+Idx);
2471             Ops.erase(Ops.begin()+AddOp-1);
2472           }
2473           Ops.push_back(OuterMul);
2474           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2475         }
2476 
2477       // Check this multiply against other multiplies being added together.
2478       for (unsigned OtherMulIdx = Idx+1;
2479            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2480            ++OtherMulIdx) {
2481         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2482         // If MulOp occurs in OtherMul, we can fold the two multiplies
2483         // together.
2484         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2485              OMulOp != e; ++OMulOp)
2486           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2487             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2488             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2489             if (Mul->getNumOperands() != 2) {
2490               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2491                                                   Mul->op_begin()+MulOp);
2492               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2493               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2494             }
2495             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2496             if (OtherMul->getNumOperands() != 2) {
2497               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2498                                                   OtherMul->op_begin()+OMulOp);
2499               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2500               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2501             }
2502             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2503             const SCEV *InnerMulSum =
2504                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2505             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2506                                               SCEV::FlagAnyWrap, Depth + 1);
2507             if (Ops.size() == 2) return OuterMul;
2508             Ops.erase(Ops.begin()+Idx);
2509             Ops.erase(Ops.begin()+OtherMulIdx-1);
2510             Ops.push_back(OuterMul);
2511             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2512           }
2513       }
2514     }
2515   }
2516 
2517   // If there are any add recurrences in the operands list, see if any other
2518   // added values are loop invariant.  If so, we can fold them into the
2519   // recurrence.
2520   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2521     ++Idx;
2522 
2523   // Scan over all recurrences, trying to fold loop invariants into them.
2524   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2525     // Scan all of the other operands to this add and add them to the vector if
2526     // they are loop invariant w.r.t. the recurrence.
2527     SmallVector<const SCEV *, 8> LIOps;
2528     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2529     const Loop *AddRecLoop = AddRec->getLoop();
2530     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2531       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2532         LIOps.push_back(Ops[i]);
2533         Ops.erase(Ops.begin()+i);
2534         --i; --e;
2535       }
2536 
2537     // If we found some loop invariants, fold them into the recurrence.
2538     if (!LIOps.empty()) {
2539       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2540       LIOps.push_back(AddRec->getStart());
2541 
2542       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2543                                              AddRec->op_end());
2544       // This follows from the fact that the no-wrap flags on the outer add
2545       // expression are applicable on the 0th iteration, when the add recurrence
2546       // will be equal to its start value.
2547       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2548 
2549       // Build the new addrec. Propagate the NUW and NSW flags if both the
2550       // outer add and the inner addrec are guaranteed to have no overflow.
2551       // Always propagate NW.
2552       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2553       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2554 
2555       // If all of the other operands were loop invariant, we are done.
2556       if (Ops.size() == 1) return NewRec;
2557 
2558       // Otherwise, add the folded AddRec by the non-invariant parts.
2559       for (unsigned i = 0;; ++i)
2560         if (Ops[i] == AddRec) {
2561           Ops[i] = NewRec;
2562           break;
2563         }
2564       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2565     }
2566 
2567     // Okay, if there weren't any loop invariants to be folded, check to see if
2568     // there are multiple AddRec's with the same loop induction variable being
2569     // added together.  If so, we can fold them.
2570     for (unsigned OtherIdx = Idx+1;
2571          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2572          ++OtherIdx) {
2573       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2574       // so that the 1st found AddRecExpr is dominated by all others.
2575       assert(DT.dominates(
2576            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2577            AddRec->getLoop()->getHeader()) &&
2578         "AddRecExprs are not sorted in reverse dominance order?");
2579       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2580         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2581         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2582                                                AddRec->op_end());
2583         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2584              ++OtherIdx) {
2585           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2586           if (OtherAddRec->getLoop() == AddRecLoop) {
2587             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2588                  i != e; ++i) {
2589               if (i >= AddRecOps.size()) {
2590                 AddRecOps.append(OtherAddRec->op_begin()+i,
2591                                  OtherAddRec->op_end());
2592                 break;
2593               }
2594               SmallVector<const SCEV *, 2> TwoOps = {
2595                   AddRecOps[i], OtherAddRec->getOperand(i)};
2596               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2597             }
2598             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2599           }
2600         }
2601         // Step size has changed, so we cannot guarantee no self-wraparound.
2602         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2603         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2604       }
2605     }
2606 
2607     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2608     // next one.
2609   }
2610 
2611   // Okay, it looks like we really DO need an add expr.  Check to see if we
2612   // already have one, otherwise create a new one.
2613   return getOrCreateAddExpr(Ops, Flags);
2614 }
2615 
2616 const SCEV *
2617 ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2618                                     SCEV::NoWrapFlags Flags) {
2619   FoldingSetNodeID ID;
2620   ID.AddInteger(scAddExpr);
2621   for (const SCEV *Op : Ops)
2622     ID.AddPointer(Op);
2623   void *IP = nullptr;
2624   SCEVAddExpr *S =
2625       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2626   if (!S) {
2627     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2628     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2629     S = new (SCEVAllocator)
2630         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2631     UniqueSCEVs.InsertNode(S, IP);
2632     addToLoopUseLists(S);
2633   }
2634   S->setNoWrapFlags(Flags);
2635   return S;
2636 }
2637 
2638 const SCEV *
2639 ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2640                                     SCEV::NoWrapFlags Flags) {
2641   FoldingSetNodeID ID;
2642   ID.AddInteger(scMulExpr);
2643   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2644     ID.AddPointer(Ops[i]);
2645   void *IP = nullptr;
2646   SCEVMulExpr *S =
2647     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2648   if (!S) {
2649     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2650     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2651     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2652                                         O, Ops.size());
2653     UniqueSCEVs.InsertNode(S, IP);
2654     addToLoopUseLists(S);
2655   }
2656   S->setNoWrapFlags(Flags);
2657   return S;
2658 }
2659 
2660 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2661   uint64_t k = i*j;
2662   if (j > 1 && k / j != i) Overflow = true;
2663   return k;
2664 }
2665 
2666 /// Compute the result of "n choose k", the binomial coefficient.  If an
2667 /// intermediate computation overflows, Overflow will be set and the return will
2668 /// be garbage. Overflow is not cleared on absence of overflow.
2669 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2670   // We use the multiplicative formula:
2671   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2672   // At each iteration, we take the n-th term of the numeral and divide by the
2673   // (k-n)th term of the denominator.  This division will always produce an
2674   // integral result, and helps reduce the chance of overflow in the
2675   // intermediate computations. However, we can still overflow even when the
2676   // final result would fit.
2677 
2678   if (n == 0 || n == k) return 1;
2679   if (k > n) return 0;
2680 
2681   if (k > n/2)
2682     k = n-k;
2683 
2684   uint64_t r = 1;
2685   for (uint64_t i = 1; i <= k; ++i) {
2686     r = umul_ov(r, n-(i-1), Overflow);
2687     r /= i;
2688   }
2689   return r;
2690 }
2691 
2692 /// Determine if any of the operands in this SCEV are a constant or if
2693 /// any of the add or multiply expressions in this SCEV contain a constant.
2694 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2695   struct FindConstantInAddMulChain {
2696     bool FoundConstant = false;
2697 
2698     bool follow(const SCEV *S) {
2699       FoundConstant |= isa<SCEVConstant>(S);
2700       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2701     }
2702 
2703     bool isDone() const {
2704       return FoundConstant;
2705     }
2706   };
2707 
2708   FindConstantInAddMulChain F;
2709   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2710   ST.visitAll(StartExpr);
2711   return F.FoundConstant;
2712 }
2713 
2714 /// Get a canonical multiply expression, or something simpler if possible.
2715 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2716                                         SCEV::NoWrapFlags Flags,
2717                                         unsigned Depth) {
2718   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2719          "only nuw or nsw allowed");
2720   assert(!Ops.empty() && "Cannot get empty mul!");
2721   if (Ops.size() == 1) return Ops[0];
2722 #ifndef NDEBUG
2723   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2724   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2725     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2726            "SCEVMulExpr operand types don't match!");
2727 #endif
2728 
2729   // Sort by complexity, this groups all similar expression types together.
2730   GroupByComplexity(Ops, &LI, DT);
2731 
2732   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2733 
2734   // Limit recursion calls depth.
2735   if (Depth > MaxArithDepth)
2736     return getOrCreateMulExpr(Ops, Flags);
2737 
2738   // If there are any constants, fold them together.
2739   unsigned Idx = 0;
2740   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2741 
2742     // C1*(C2+V) -> C1*C2 + C1*V
2743     if (Ops.size() == 2)
2744         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2745           // If any of Add's ops are Adds or Muls with a constant,
2746           // apply this transformation as well.
2747           if (Add->getNumOperands() == 2)
2748             // TODO: There are some cases where this transformation is not
2749             // profitable, for example:
2750             // Add = (C0 + X) * Y + Z.
2751             // Maybe the scope of this transformation should be narrowed down.
2752             if (containsConstantInAddMulChain(Add))
2753               return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2754                                            SCEV::FlagAnyWrap, Depth + 1),
2755                                 getMulExpr(LHSC, Add->getOperand(1),
2756                                            SCEV::FlagAnyWrap, Depth + 1),
2757                                 SCEV::FlagAnyWrap, Depth + 1);
2758 
2759     ++Idx;
2760     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2761       // We found two constants, fold them together!
2762       ConstantInt *Fold =
2763           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2764       Ops[0] = getConstant(Fold);
2765       Ops.erase(Ops.begin()+1);  // Erase the folded element
2766       if (Ops.size() == 1) return Ops[0];
2767       LHSC = cast<SCEVConstant>(Ops[0]);
2768     }
2769 
2770     // If we are left with a constant one being multiplied, strip it off.
2771     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2772       Ops.erase(Ops.begin());
2773       --Idx;
2774     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2775       // If we have a multiply of zero, it will always be zero.
2776       return Ops[0];
2777     } else if (Ops[0]->isAllOnesValue()) {
2778       // If we have a mul by -1 of an add, try distributing the -1 among the
2779       // add operands.
2780       if (Ops.size() == 2) {
2781         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2782           SmallVector<const SCEV *, 4> NewOps;
2783           bool AnyFolded = false;
2784           for (const SCEV *AddOp : Add->operands()) {
2785             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2786                                          Depth + 1);
2787             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2788             NewOps.push_back(Mul);
2789           }
2790           if (AnyFolded)
2791             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2792         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2793           // Negation preserves a recurrence's no self-wrap property.
2794           SmallVector<const SCEV *, 4> Operands;
2795           for (const SCEV *AddRecOp : AddRec->operands())
2796             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2797                                           Depth + 1));
2798 
2799           return getAddRecExpr(Operands, AddRec->getLoop(),
2800                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2801         }
2802       }
2803     }
2804 
2805     if (Ops.size() == 1)
2806       return Ops[0];
2807   }
2808 
2809   // Skip over the add expression until we get to a multiply.
2810   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2811     ++Idx;
2812 
2813   // If there are mul operands inline them all into this expression.
2814   if (Idx < Ops.size()) {
2815     bool DeletedMul = false;
2816     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2817       if (Ops.size() > MulOpsInlineThreshold)
2818         break;
2819       // If we have an mul, expand the mul operands onto the end of the
2820       // operands list.
2821       Ops.erase(Ops.begin()+Idx);
2822       Ops.append(Mul->op_begin(), Mul->op_end());
2823       DeletedMul = true;
2824     }
2825 
2826     // If we deleted at least one mul, we added operands to the end of the
2827     // list, and they are not necessarily sorted.  Recurse to resort and
2828     // resimplify any operands we just acquired.
2829     if (DeletedMul)
2830       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2831   }
2832 
2833   // If there are any add recurrences in the operands list, see if any other
2834   // added values are loop invariant.  If so, we can fold them into the
2835   // recurrence.
2836   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2837     ++Idx;
2838 
2839   // Scan over all recurrences, trying to fold loop invariants into them.
2840   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2841     // Scan all of the other operands to this mul and add them to the vector
2842     // if they are loop invariant w.r.t. the recurrence.
2843     SmallVector<const SCEV *, 8> LIOps;
2844     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2845     const Loop *AddRecLoop = AddRec->getLoop();
2846     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2847       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2848         LIOps.push_back(Ops[i]);
2849         Ops.erase(Ops.begin()+i);
2850         --i; --e;
2851       }
2852 
2853     // If we found some loop invariants, fold them into the recurrence.
2854     if (!LIOps.empty()) {
2855       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2856       SmallVector<const SCEV *, 4> NewOps;
2857       NewOps.reserve(AddRec->getNumOperands());
2858       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2859       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2860         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2861                                     SCEV::FlagAnyWrap, Depth + 1));
2862 
2863       // Build the new addrec. Propagate the NUW and NSW flags if both the
2864       // outer mul and the inner addrec are guaranteed to have no overflow.
2865       //
2866       // No self-wrap cannot be guaranteed after changing the step size, but
2867       // will be inferred if either NUW or NSW is true.
2868       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2869       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
2870 
2871       // If all of the other operands were loop invariant, we are done.
2872       if (Ops.size() == 1) return NewRec;
2873 
2874       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2875       for (unsigned i = 0;; ++i)
2876         if (Ops[i] == AddRec) {
2877           Ops[i] = NewRec;
2878           break;
2879         }
2880       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2881     }
2882 
2883     // Okay, if there weren't any loop invariants to be folded, check to see
2884     // if there are multiple AddRec's with the same loop induction variable
2885     // being multiplied together.  If so, we can fold them.
2886 
2887     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2888     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2889     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2890     //   ]]],+,...up to x=2n}.
2891     // Note that the arguments to choose() are always integers with values
2892     // known at compile time, never SCEV objects.
2893     //
2894     // The implementation avoids pointless extra computations when the two
2895     // addrec's are of different length (mathematically, it's equivalent to
2896     // an infinite stream of zeros on the right).
2897     bool OpsModified = false;
2898     for (unsigned OtherIdx = Idx+1;
2899          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2900          ++OtherIdx) {
2901       const SCEVAddRecExpr *OtherAddRec =
2902         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2903       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2904         continue;
2905 
2906       // Limit max number of arguments to avoid creation of unreasonably big
2907       // SCEVAddRecs with very complex operands.
2908       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
2909           MaxAddRecSize)
2910         continue;
2911 
2912       bool Overflow = false;
2913       Type *Ty = AddRec->getType();
2914       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2915       SmallVector<const SCEV*, 7> AddRecOps;
2916       for (int x = 0, xe = AddRec->getNumOperands() +
2917              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2918         const SCEV *Term = getZero(Ty);
2919         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2920           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2921           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2922                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2923                z < ze && !Overflow; ++z) {
2924             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2925             uint64_t Coeff;
2926             if (LargerThan64Bits)
2927               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2928             else
2929               Coeff = Coeff1*Coeff2;
2930             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2931             const SCEV *Term1 = AddRec->getOperand(y-z);
2932             const SCEV *Term2 = OtherAddRec->getOperand(z);
2933             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
2934                                                SCEV::FlagAnyWrap, Depth + 1),
2935                               SCEV::FlagAnyWrap, Depth + 1);
2936           }
2937         }
2938         AddRecOps.push_back(Term);
2939       }
2940       if (!Overflow) {
2941         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2942                                               SCEV::FlagAnyWrap);
2943         if (Ops.size() == 2) return NewAddRec;
2944         Ops[Idx] = NewAddRec;
2945         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2946         OpsModified = true;
2947         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2948         if (!AddRec)
2949           break;
2950       }
2951     }
2952     if (OpsModified)
2953       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2954 
2955     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2956     // next one.
2957   }
2958 
2959   // Okay, it looks like we really DO need an mul expr.  Check to see if we
2960   // already have one, otherwise create a new one.
2961   return getOrCreateMulExpr(Ops, Flags);
2962 }
2963 
2964 /// Represents an unsigned remainder expression based on unsigned division.
2965 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
2966                                          const SCEV *RHS) {
2967   assert(getEffectiveSCEVType(LHS->getType()) ==
2968          getEffectiveSCEVType(RHS->getType()) &&
2969          "SCEVURemExpr operand types don't match!");
2970 
2971   // Short-circuit easy cases
2972   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
2973     // If constant is one, the result is trivial
2974     if (RHSC->getValue()->isOne())
2975       return getZero(LHS->getType()); // X urem 1 --> 0
2976 
2977     // If constant is a power of two, fold into a zext(trunc(LHS)).
2978     if (RHSC->getAPInt().isPowerOf2()) {
2979       Type *FullTy = LHS->getType();
2980       Type *TruncTy =
2981           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
2982       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
2983     }
2984   }
2985 
2986   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
2987   const SCEV *UDiv = getUDivExpr(LHS, RHS);
2988   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
2989   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
2990 }
2991 
2992 /// Get a canonical unsigned division expression, or something simpler if
2993 /// possible.
2994 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2995                                          const SCEV *RHS) {
2996   assert(getEffectiveSCEVType(LHS->getType()) ==
2997          getEffectiveSCEVType(RHS->getType()) &&
2998          "SCEVUDivExpr operand types don't match!");
2999 
3000   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3001     if (RHSC->getValue()->isOne())
3002       return LHS;                               // X udiv 1 --> x
3003     // If the denominator is zero, the result of the udiv is undefined. Don't
3004     // try to analyze it, because the resolution chosen here may differ from
3005     // the resolution chosen in other parts of the compiler.
3006     if (!RHSC->getValue()->isZero()) {
3007       // Determine if the division can be folded into the operands of
3008       // its operands.
3009       // TODO: Generalize this to non-constants by using known-bits information.
3010       Type *Ty = LHS->getType();
3011       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3012       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3013       // For non-power-of-two values, effectively round the value up to the
3014       // nearest power of two.
3015       if (!RHSC->getAPInt().isPowerOf2())
3016         ++MaxShiftAmt;
3017       IntegerType *ExtTy =
3018         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3019       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3020         if (const SCEVConstant *Step =
3021             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3022           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3023           const APInt &StepInt = Step->getAPInt();
3024           const APInt &DivInt = RHSC->getAPInt();
3025           if (!StepInt.urem(DivInt) &&
3026               getZeroExtendExpr(AR, ExtTy) ==
3027               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3028                             getZeroExtendExpr(Step, ExtTy),
3029                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3030             SmallVector<const SCEV *, 4> Operands;
3031             for (const SCEV *Op : AR->operands())
3032               Operands.push_back(getUDivExpr(Op, RHS));
3033             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3034           }
3035           /// Get a canonical UDivExpr for a recurrence.
3036           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3037           // We can currently only fold X%N if X is constant.
3038           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3039           if (StartC && !DivInt.urem(StepInt) &&
3040               getZeroExtendExpr(AR, ExtTy) ==
3041               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3042                             getZeroExtendExpr(Step, ExtTy),
3043                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3044             const APInt &StartInt = StartC->getAPInt();
3045             const APInt &StartRem = StartInt.urem(StepInt);
3046             if (StartRem != 0)
3047               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3048                                   AR->getLoop(), SCEV::FlagNW);
3049           }
3050         }
3051       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3052       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3053         SmallVector<const SCEV *, 4> Operands;
3054         for (const SCEV *Op : M->operands())
3055           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3056         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3057           // Find an operand that's safely divisible.
3058           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3059             const SCEV *Op = M->getOperand(i);
3060             const SCEV *Div = getUDivExpr(Op, RHSC);
3061             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3062               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3063                                                       M->op_end());
3064               Operands[i] = Div;
3065               return getMulExpr(Operands);
3066             }
3067           }
3068       }
3069       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3070       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3071         SmallVector<const SCEV *, 4> Operands;
3072         for (const SCEV *Op : A->operands())
3073           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3074         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3075           Operands.clear();
3076           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3077             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3078             if (isa<SCEVUDivExpr>(Op) ||
3079                 getMulExpr(Op, RHS) != A->getOperand(i))
3080               break;
3081             Operands.push_back(Op);
3082           }
3083           if (Operands.size() == A->getNumOperands())
3084             return getAddExpr(Operands);
3085         }
3086       }
3087 
3088       // Fold if both operands are constant.
3089       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3090         Constant *LHSCV = LHSC->getValue();
3091         Constant *RHSCV = RHSC->getValue();
3092         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3093                                                                    RHSCV)));
3094       }
3095     }
3096   }
3097 
3098   FoldingSetNodeID ID;
3099   ID.AddInteger(scUDivExpr);
3100   ID.AddPointer(LHS);
3101   ID.AddPointer(RHS);
3102   void *IP = nullptr;
3103   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3104   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3105                                              LHS, RHS);
3106   UniqueSCEVs.InsertNode(S, IP);
3107   addToLoopUseLists(S);
3108   return S;
3109 }
3110 
3111 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3112   APInt A = C1->getAPInt().abs();
3113   APInt B = C2->getAPInt().abs();
3114   uint32_t ABW = A.getBitWidth();
3115   uint32_t BBW = B.getBitWidth();
3116 
3117   if (ABW > BBW)
3118     B = B.zext(ABW);
3119   else if (ABW < BBW)
3120     A = A.zext(BBW);
3121 
3122   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3123 }
3124 
3125 /// Get a canonical unsigned division expression, or something simpler if
3126 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3127 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3128 /// it's not exact because the udiv may be clearing bits.
3129 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3130                                               const SCEV *RHS) {
3131   // TODO: we could try to find factors in all sorts of things, but for now we
3132   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3133   // end of this file for inspiration.
3134 
3135   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3136   if (!Mul || !Mul->hasNoUnsignedWrap())
3137     return getUDivExpr(LHS, RHS);
3138 
3139   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3140     // If the mulexpr multiplies by a constant, then that constant must be the
3141     // first element of the mulexpr.
3142     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3143       if (LHSCst == RHSCst) {
3144         SmallVector<const SCEV *, 2> Operands;
3145         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3146         return getMulExpr(Operands);
3147       }
3148 
3149       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3150       // that there's a factor provided by one of the other terms. We need to
3151       // check.
3152       APInt Factor = gcd(LHSCst, RHSCst);
3153       if (!Factor.isIntN(1)) {
3154         LHSCst =
3155             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3156         RHSCst =
3157             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3158         SmallVector<const SCEV *, 2> Operands;
3159         Operands.push_back(LHSCst);
3160         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3161         LHS = getMulExpr(Operands);
3162         RHS = RHSCst;
3163         Mul = dyn_cast<SCEVMulExpr>(LHS);
3164         if (!Mul)
3165           return getUDivExactExpr(LHS, RHS);
3166       }
3167     }
3168   }
3169 
3170   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3171     if (Mul->getOperand(i) == RHS) {
3172       SmallVector<const SCEV *, 2> Operands;
3173       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3174       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3175       return getMulExpr(Operands);
3176     }
3177   }
3178 
3179   return getUDivExpr(LHS, RHS);
3180 }
3181 
3182 /// Get an add recurrence expression for the specified loop.  Simplify the
3183 /// expression as much as possible.
3184 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3185                                            const Loop *L,
3186                                            SCEV::NoWrapFlags Flags) {
3187   SmallVector<const SCEV *, 4> Operands;
3188   Operands.push_back(Start);
3189   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3190     if (StepChrec->getLoop() == L) {
3191       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3192       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3193     }
3194 
3195   Operands.push_back(Step);
3196   return getAddRecExpr(Operands, L, Flags);
3197 }
3198 
3199 /// Get an add recurrence expression for the specified loop.  Simplify the
3200 /// expression as much as possible.
3201 const SCEV *
3202 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3203                                const Loop *L, SCEV::NoWrapFlags Flags) {
3204   if (Operands.size() == 1) return Operands[0];
3205 #ifndef NDEBUG
3206   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3207   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3208     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3209            "SCEVAddRecExpr operand types don't match!");
3210   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3211     assert(isLoopInvariant(Operands[i], L) &&
3212            "SCEVAddRecExpr operand is not loop-invariant!");
3213 #endif
3214 
3215   if (Operands.back()->isZero()) {
3216     Operands.pop_back();
3217     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3218   }
3219 
3220   // It's tempting to want to call getMaxBackedgeTakenCount count here and
3221   // use that information to infer NUW and NSW flags. However, computing a
3222   // BE count requires calling getAddRecExpr, so we may not yet have a
3223   // meaningful BE count at this point (and if we don't, we'd be stuck
3224   // with a SCEVCouldNotCompute as the cached BE count).
3225 
3226   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3227 
3228   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3229   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3230     const Loop *NestedLoop = NestedAR->getLoop();
3231     if (L->contains(NestedLoop)
3232             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3233             : (!NestedLoop->contains(L) &&
3234                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3235       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3236                                                   NestedAR->op_end());
3237       Operands[0] = NestedAR->getStart();
3238       // AddRecs require their operands be loop-invariant with respect to their
3239       // loops. Don't perform this transformation if it would break this
3240       // requirement.
3241       bool AllInvariant = all_of(
3242           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3243 
3244       if (AllInvariant) {
3245         // Create a recurrence for the outer loop with the same step size.
3246         //
3247         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3248         // inner recurrence has the same property.
3249         SCEV::NoWrapFlags OuterFlags =
3250           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3251 
3252         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3253         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3254           return isLoopInvariant(Op, NestedLoop);
3255         });
3256 
3257         if (AllInvariant) {
3258           // Ok, both add recurrences are valid after the transformation.
3259           //
3260           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3261           // the outer recurrence has the same property.
3262           SCEV::NoWrapFlags InnerFlags =
3263             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3264           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3265         }
3266       }
3267       // Reset Operands to its original state.
3268       Operands[0] = NestedAR;
3269     }
3270   }
3271 
3272   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3273   // already have one, otherwise create a new one.
3274   FoldingSetNodeID ID;
3275   ID.AddInteger(scAddRecExpr);
3276   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3277     ID.AddPointer(Operands[i]);
3278   ID.AddPointer(L);
3279   void *IP = nullptr;
3280   SCEVAddRecExpr *S =
3281     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3282   if (!S) {
3283     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
3284     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
3285     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
3286                                            O, Operands.size(), L);
3287     UniqueSCEVs.InsertNode(S, IP);
3288     addToLoopUseLists(S);
3289   }
3290   S->setNoWrapFlags(Flags);
3291   return S;
3292 }
3293 
3294 const SCEV *
3295 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3296                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3297   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3298   // getSCEV(Base)->getType() has the same address space as Base->getType()
3299   // because SCEV::getType() preserves the address space.
3300   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3301   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3302   // instruction to its SCEV, because the Instruction may be guarded by control
3303   // flow and the no-overflow bits may not be valid for the expression in any
3304   // context. This can be fixed similarly to how these flags are handled for
3305   // adds.
3306   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3307                                              : SCEV::FlagAnyWrap;
3308 
3309   const SCEV *TotalOffset = getZero(IntPtrTy);
3310   // The array size is unimportant. The first thing we do on CurTy is getting
3311   // its element type.
3312   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3313   for (const SCEV *IndexExpr : IndexExprs) {
3314     // Compute the (potentially symbolic) offset in bytes for this index.
3315     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3316       // For a struct, add the member offset.
3317       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3318       unsigned FieldNo = Index->getZExtValue();
3319       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3320 
3321       // Add the field offset to the running total offset.
3322       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3323 
3324       // Update CurTy to the type of the field at Index.
3325       CurTy = STy->getTypeAtIndex(Index);
3326     } else {
3327       // Update CurTy to its element type.
3328       CurTy = cast<SequentialType>(CurTy)->getElementType();
3329       // For an array, add the element offset, explicitly scaled.
3330       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3331       // Getelementptr indices are signed.
3332       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3333 
3334       // Multiply the index by the element size to compute the element offset.
3335       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3336 
3337       // Add the element offset to the running total offset.
3338       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3339     }
3340   }
3341 
3342   // Add the total offset from all the GEP indices to the base.
3343   return getAddExpr(BaseExpr, TotalOffset, Wrap);
3344 }
3345 
3346 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3347                                          const SCEV *RHS) {
3348   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3349   return getSMaxExpr(Ops);
3350 }
3351 
3352 const SCEV *
3353 ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3354   assert(!Ops.empty() && "Cannot get empty smax!");
3355   if (Ops.size() == 1) return Ops[0];
3356 #ifndef NDEBUG
3357   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3358   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3359     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3360            "SCEVSMaxExpr operand types don't match!");
3361 #endif
3362 
3363   // Sort by complexity, this groups all similar expression types together.
3364   GroupByComplexity(Ops, &LI, DT);
3365 
3366   // If there are any constants, fold them together.
3367   unsigned Idx = 0;
3368   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3369     ++Idx;
3370     assert(Idx < Ops.size());
3371     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3372       // We found two constants, fold them together!
3373       ConstantInt *Fold = ConstantInt::get(
3374           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3375       Ops[0] = getConstant(Fold);
3376       Ops.erase(Ops.begin()+1);  // Erase the folded element
3377       if (Ops.size() == 1) return Ops[0];
3378       LHSC = cast<SCEVConstant>(Ops[0]);
3379     }
3380 
3381     // If we are left with a constant minimum-int, strip it off.
3382     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3383       Ops.erase(Ops.begin());
3384       --Idx;
3385     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3386       // If we have an smax with a constant maximum-int, it will always be
3387       // maximum-int.
3388       return Ops[0];
3389     }
3390 
3391     if (Ops.size() == 1) return Ops[0];
3392   }
3393 
3394   // Find the first SMax
3395   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3396     ++Idx;
3397 
3398   // Check to see if one of the operands is an SMax. If so, expand its operands
3399   // onto our operand list, and recurse to simplify.
3400   if (Idx < Ops.size()) {
3401     bool DeletedSMax = false;
3402     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3403       Ops.erase(Ops.begin()+Idx);
3404       Ops.append(SMax->op_begin(), SMax->op_end());
3405       DeletedSMax = true;
3406     }
3407 
3408     if (DeletedSMax)
3409       return getSMaxExpr(Ops);
3410   }
3411 
3412   // Okay, check to see if the same value occurs in the operand list twice.  If
3413   // so, delete one.  Since we sorted the list, these values are required to
3414   // be adjacent.
3415   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3416     //  X smax Y smax Y  -->  X smax Y
3417     //  X smax Y         -->  X, if X is always greater than Y
3418     if (Ops[i] == Ops[i+1] ||
3419         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3420       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3421       --i; --e;
3422     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3423       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3424       --i; --e;
3425     }
3426 
3427   if (Ops.size() == 1) return Ops[0];
3428 
3429   assert(!Ops.empty() && "Reduced smax down to nothing!");
3430 
3431   // Okay, it looks like we really DO need an smax expr.  Check to see if we
3432   // already have one, otherwise create a new one.
3433   FoldingSetNodeID ID;
3434   ID.AddInteger(scSMaxExpr);
3435   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3436     ID.AddPointer(Ops[i]);
3437   void *IP = nullptr;
3438   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3439   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3440   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3441   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3442                                              O, Ops.size());
3443   UniqueSCEVs.InsertNode(S, IP);
3444   addToLoopUseLists(S);
3445   return S;
3446 }
3447 
3448 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3449                                          const SCEV *RHS) {
3450   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3451   return getUMaxExpr(Ops);
3452 }
3453 
3454 const SCEV *
3455 ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3456   assert(!Ops.empty() && "Cannot get empty umax!");
3457   if (Ops.size() == 1) return Ops[0];
3458 #ifndef NDEBUG
3459   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3460   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3461     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3462            "SCEVUMaxExpr operand types don't match!");
3463 #endif
3464 
3465   // Sort by complexity, this groups all similar expression types together.
3466   GroupByComplexity(Ops, &LI, DT);
3467 
3468   // If there are any constants, fold them together.
3469   unsigned Idx = 0;
3470   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3471     ++Idx;
3472     assert(Idx < Ops.size());
3473     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3474       // We found two constants, fold them together!
3475       ConstantInt *Fold = ConstantInt::get(
3476           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3477       Ops[0] = getConstant(Fold);
3478       Ops.erase(Ops.begin()+1);  // Erase the folded element
3479       if (Ops.size() == 1) return Ops[0];
3480       LHSC = cast<SCEVConstant>(Ops[0]);
3481     }
3482 
3483     // If we are left with a constant minimum-int, strip it off.
3484     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3485       Ops.erase(Ops.begin());
3486       --Idx;
3487     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3488       // If we have an umax with a constant maximum-int, it will always be
3489       // maximum-int.
3490       return Ops[0];
3491     }
3492 
3493     if (Ops.size() == 1) return Ops[0];
3494   }
3495 
3496   // Find the first UMax
3497   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3498     ++Idx;
3499 
3500   // Check to see if one of the operands is a UMax. If so, expand its operands
3501   // onto our operand list, and recurse to simplify.
3502   if (Idx < Ops.size()) {
3503     bool DeletedUMax = false;
3504     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3505       Ops.erase(Ops.begin()+Idx);
3506       Ops.append(UMax->op_begin(), UMax->op_end());
3507       DeletedUMax = true;
3508     }
3509 
3510     if (DeletedUMax)
3511       return getUMaxExpr(Ops);
3512   }
3513 
3514   // Okay, check to see if the same value occurs in the operand list twice.  If
3515   // so, delete one.  Since we sorted the list, these values are required to
3516   // be adjacent.
3517   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3518     //  X umax Y umax Y  -->  X umax Y
3519     //  X umax Y         -->  X, if X is always greater than Y
3520     if (Ops[i] == Ops[i+1] ||
3521         isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3522       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3523       --i; --e;
3524     } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
3525       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3526       --i; --e;
3527     }
3528 
3529   if (Ops.size() == 1) return Ops[0];
3530 
3531   assert(!Ops.empty() && "Reduced umax down to nothing!");
3532 
3533   // Okay, it looks like we really DO need a umax expr.  Check to see if we
3534   // already have one, otherwise create a new one.
3535   FoldingSetNodeID ID;
3536   ID.AddInteger(scUMaxExpr);
3537   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3538     ID.AddPointer(Ops[i]);
3539   void *IP = nullptr;
3540   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3541   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3542   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3543   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3544                                              O, Ops.size());
3545   UniqueSCEVs.InsertNode(S, IP);
3546   addToLoopUseLists(S);
3547   return S;
3548 }
3549 
3550 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3551                                          const SCEV *RHS) {
3552   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3553   return getSMinExpr(Ops);
3554 }
3555 
3556 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3557   // ~smax(~x, ~y, ~z) == smin(x, y, z).
3558   SmallVector<const SCEV *, 2> NotOps;
3559   for (auto *S : Ops)
3560     NotOps.push_back(getNotSCEV(S));
3561   return getNotSCEV(getSMaxExpr(NotOps));
3562 }
3563 
3564 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3565                                          const SCEV *RHS) {
3566   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3567   return getUMinExpr(Ops);
3568 }
3569 
3570 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3571   assert(!Ops.empty() && "At least one operand must be!");
3572   // Trivial case.
3573   if (Ops.size() == 1)
3574     return Ops[0];
3575 
3576   // ~umax(~x, ~y, ~z) == umin(x, y, z).
3577   SmallVector<const SCEV *, 2> NotOps;
3578   for (auto *S : Ops)
3579     NotOps.push_back(getNotSCEV(S));
3580   return getNotSCEV(getUMaxExpr(NotOps));
3581 }
3582 
3583 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3584   // We can bypass creating a target-independent
3585   // constant expression and then folding it back into a ConstantInt.
3586   // This is just a compile-time optimization.
3587   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3588 }
3589 
3590 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3591                                              StructType *STy,
3592                                              unsigned FieldNo) {
3593   // We can bypass creating a target-independent
3594   // constant expression and then folding it back into a ConstantInt.
3595   // This is just a compile-time optimization.
3596   return getConstant(
3597       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3598 }
3599 
3600 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3601   // Don't attempt to do anything other than create a SCEVUnknown object
3602   // here.  createSCEV only calls getUnknown after checking for all other
3603   // interesting possibilities, and any other code that calls getUnknown
3604   // is doing so in order to hide a value from SCEV canonicalization.
3605 
3606   FoldingSetNodeID ID;
3607   ID.AddInteger(scUnknown);
3608   ID.AddPointer(V);
3609   void *IP = nullptr;
3610   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3611     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3612            "Stale SCEVUnknown in uniquing map!");
3613     return S;
3614   }
3615   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3616                                             FirstUnknown);
3617   FirstUnknown = cast<SCEVUnknown>(S);
3618   UniqueSCEVs.InsertNode(S, IP);
3619   return S;
3620 }
3621 
3622 //===----------------------------------------------------------------------===//
3623 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3624 //
3625 
3626 /// Test if values of the given type are analyzable within the SCEV
3627 /// framework. This primarily includes integer types, and it can optionally
3628 /// include pointer types if the ScalarEvolution class has access to
3629 /// target-specific information.
3630 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3631   // Integers and pointers are always SCEVable.
3632   return Ty->isIntegerTy() || Ty->isPointerTy();
3633 }
3634 
3635 /// Return the size in bits of the specified type, for which isSCEVable must
3636 /// return true.
3637 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3638   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3639   if (Ty->isPointerTy())
3640     return getDataLayout().getIndexTypeSizeInBits(Ty);
3641   return getDataLayout().getTypeSizeInBits(Ty);
3642 }
3643 
3644 /// Return a type with the same bitwidth as the given type and which represents
3645 /// how SCEV will treat the given type, for which isSCEVable must return
3646 /// true. For pointer types, this is the pointer-sized integer type.
3647 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3648   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3649 
3650   if (Ty->isIntegerTy())
3651     return Ty;
3652 
3653   // The only other support type is pointer.
3654   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3655   return getDataLayout().getIntPtrType(Ty);
3656 }
3657 
3658 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3659   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3660 }
3661 
3662 const SCEV *ScalarEvolution::getCouldNotCompute() {
3663   return CouldNotCompute.get();
3664 }
3665 
3666 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3667   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3668     auto *SU = dyn_cast<SCEVUnknown>(S);
3669     return SU && SU->getValue() == nullptr;
3670   });
3671 
3672   return !ContainsNulls;
3673 }
3674 
3675 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3676   HasRecMapType::iterator I = HasRecMap.find(S);
3677   if (I != HasRecMap.end())
3678     return I->second;
3679 
3680   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3681   HasRecMap.insert({S, FoundAddRec});
3682   return FoundAddRec;
3683 }
3684 
3685 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3686 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3687 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3688 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3689   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3690   if (!Add)
3691     return {S, nullptr};
3692 
3693   if (Add->getNumOperands() != 2)
3694     return {S, nullptr};
3695 
3696   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3697   if (!ConstOp)
3698     return {S, nullptr};
3699 
3700   return {Add->getOperand(1), ConstOp->getValue()};
3701 }
3702 
3703 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3704 /// by the value and offset from any ValueOffsetPair in the set.
3705 SetVector<ScalarEvolution::ValueOffsetPair> *
3706 ScalarEvolution::getSCEVValues(const SCEV *S) {
3707   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3708   if (SI == ExprValueMap.end())
3709     return nullptr;
3710 #ifndef NDEBUG
3711   if (VerifySCEVMap) {
3712     // Check there is no dangling Value in the set returned.
3713     for (const auto &VE : SI->second)
3714       assert(ValueExprMap.count(VE.first));
3715   }
3716 #endif
3717   return &SI->second;
3718 }
3719 
3720 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3721 /// cannot be used separately. eraseValueFromMap should be used to remove
3722 /// V from ValueExprMap and ExprValueMap at the same time.
3723 void ScalarEvolution::eraseValueFromMap(Value *V) {
3724   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3725   if (I != ValueExprMap.end()) {
3726     const SCEV *S = I->second;
3727     // Remove {V, 0} from the set of ExprValueMap[S]
3728     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3729       SV->remove({V, nullptr});
3730 
3731     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3732     const SCEV *Stripped;
3733     ConstantInt *Offset;
3734     std::tie(Stripped, Offset) = splitAddExpr(S);
3735     if (Offset != nullptr) {
3736       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3737         SV->remove({V, Offset});
3738     }
3739     ValueExprMap.erase(V);
3740   }
3741 }
3742 
3743 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3744 /// TODO: In reality it is better to check the poison recursevely
3745 /// but this is better than nothing.
3746 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3747   if (auto *I = dyn_cast<Instruction>(V)) {
3748     if (isa<OverflowingBinaryOperator>(I)) {
3749       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3750         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3751           return true;
3752         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3753           return true;
3754       }
3755     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3756       return true;
3757   }
3758   return false;
3759 }
3760 
3761 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3762 /// create a new one.
3763 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3764   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3765 
3766   const SCEV *S = getExistingSCEV(V);
3767   if (S == nullptr) {
3768     S = createSCEV(V);
3769     // During PHI resolution, it is possible to create two SCEVs for the same
3770     // V, so it is needed to double check whether V->S is inserted into
3771     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3772     std::pair<ValueExprMapType::iterator, bool> Pair =
3773         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3774     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3775       ExprValueMap[S].insert({V, nullptr});
3776 
3777       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3778       // ExprValueMap.
3779       const SCEV *Stripped = S;
3780       ConstantInt *Offset = nullptr;
3781       std::tie(Stripped, Offset) = splitAddExpr(S);
3782       // If stripped is SCEVUnknown, don't bother to save
3783       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3784       // increase the complexity of the expansion code.
3785       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3786       // because it may generate add/sub instead of GEP in SCEV expansion.
3787       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3788           !isa<GetElementPtrInst>(V))
3789         ExprValueMap[Stripped].insert({V, Offset});
3790     }
3791   }
3792   return S;
3793 }
3794 
3795 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3796   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3797 
3798   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3799   if (I != ValueExprMap.end()) {
3800     const SCEV *S = I->second;
3801     if (checkValidity(S))
3802       return S;
3803     eraseValueFromMap(V);
3804     forgetMemoizedResults(S);
3805   }
3806   return nullptr;
3807 }
3808 
3809 /// Return a SCEV corresponding to -V = -1*V
3810 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3811                                              SCEV::NoWrapFlags Flags) {
3812   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3813     return getConstant(
3814                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3815 
3816   Type *Ty = V->getType();
3817   Ty = getEffectiveSCEVType(Ty);
3818   return getMulExpr(
3819       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3820 }
3821 
3822 /// Return a SCEV corresponding to ~V = -1-V
3823 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3824   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3825     return getConstant(
3826                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3827 
3828   Type *Ty = V->getType();
3829   Ty = getEffectiveSCEVType(Ty);
3830   const SCEV *AllOnes =
3831                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3832   return getMinusSCEV(AllOnes, V);
3833 }
3834 
3835 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3836                                           SCEV::NoWrapFlags Flags,
3837                                           unsigned Depth) {
3838   // Fast path: X - X --> 0.
3839   if (LHS == RHS)
3840     return getZero(LHS->getType());
3841 
3842   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3843   // makes it so that we cannot make much use of NUW.
3844   auto AddFlags = SCEV::FlagAnyWrap;
3845   const bool RHSIsNotMinSigned =
3846       !getSignedRangeMin(RHS).isMinSignedValue();
3847   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3848     // Let M be the minimum representable signed value. Then (-1)*RHS
3849     // signed-wraps if and only if RHS is M. That can happen even for
3850     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3851     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3852     // (-1)*RHS, we need to prove that RHS != M.
3853     //
3854     // If LHS is non-negative and we know that LHS - RHS does not
3855     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3856     // either by proving that RHS > M or that LHS >= 0.
3857     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3858       AddFlags = SCEV::FlagNSW;
3859     }
3860   }
3861 
3862   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3863   // RHS is NSW and LHS >= 0.
3864   //
3865   // The difficulty here is that the NSW flag may have been proven
3866   // relative to a loop that is to be found in a recurrence in LHS and
3867   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3868   // larger scope than intended.
3869   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3870 
3871   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3872 }
3873 
3874 const SCEV *
3875 ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3876   Type *SrcTy = V->getType();
3877   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3878          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3879          "Cannot truncate or zero extend with non-integer arguments!");
3880   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3881     return V;  // No conversion
3882   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3883     return getTruncateExpr(V, Ty);
3884   return getZeroExtendExpr(V, Ty);
3885 }
3886 
3887 const SCEV *
3888 ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
3889                                          Type *Ty) {
3890   Type *SrcTy = V->getType();
3891   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3892          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3893          "Cannot truncate or zero extend with non-integer arguments!");
3894   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3895     return V;  // No conversion
3896   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
3897     return getTruncateExpr(V, Ty);
3898   return getSignExtendExpr(V, Ty);
3899 }
3900 
3901 const SCEV *
3902 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3903   Type *SrcTy = V->getType();
3904   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3905          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3906          "Cannot noop or zero extend with non-integer arguments!");
3907   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3908          "getNoopOrZeroExtend cannot truncate!");
3909   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3910     return V;  // No conversion
3911   return getZeroExtendExpr(V, Ty);
3912 }
3913 
3914 const SCEV *
3915 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3916   Type *SrcTy = V->getType();
3917   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3918          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3919          "Cannot noop or sign extend with non-integer arguments!");
3920   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3921          "getNoopOrSignExtend cannot truncate!");
3922   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3923     return V;  // No conversion
3924   return getSignExtendExpr(V, Ty);
3925 }
3926 
3927 const SCEV *
3928 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3929   Type *SrcTy = V->getType();
3930   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3931          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3932          "Cannot noop or any extend with non-integer arguments!");
3933   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3934          "getNoopOrAnyExtend cannot truncate!");
3935   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3936     return V;  // No conversion
3937   return getAnyExtendExpr(V, Ty);
3938 }
3939 
3940 const SCEV *
3941 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3942   Type *SrcTy = V->getType();
3943   assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3944          (Ty->isIntegerTy() || Ty->isPointerTy()) &&
3945          "Cannot truncate or noop with non-integer arguments!");
3946   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3947          "getTruncateOrNoop cannot extend!");
3948   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3949     return V;  // No conversion
3950   return getTruncateExpr(V, Ty);
3951 }
3952 
3953 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3954                                                         const SCEV *RHS) {
3955   const SCEV *PromotedLHS = LHS;
3956   const SCEV *PromotedRHS = RHS;
3957 
3958   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3959     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3960   else
3961     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3962 
3963   return getUMaxExpr(PromotedLHS, PromotedRHS);
3964 }
3965 
3966 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3967                                                         const SCEV *RHS) {
3968   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3969   return getUMinFromMismatchedTypes(Ops);
3970 }
3971 
3972 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
3973     SmallVectorImpl<const SCEV *> &Ops) {
3974   assert(!Ops.empty() && "At least one operand must be!");
3975   // Trivial case.
3976   if (Ops.size() == 1)
3977     return Ops[0];
3978 
3979   // Find the max type first.
3980   Type *MaxType = nullptr;
3981   for (auto *S : Ops)
3982     if (MaxType)
3983       MaxType = getWiderType(MaxType, S->getType());
3984     else
3985       MaxType = S->getType();
3986 
3987   // Extend all ops to max type.
3988   SmallVector<const SCEV *, 2> PromotedOps;
3989   for (auto *S : Ops)
3990     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
3991 
3992   // Generate umin.
3993   return getUMinExpr(PromotedOps);
3994 }
3995 
3996 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3997   // A pointer operand may evaluate to a nonpointer expression, such as null.
3998   if (!V->getType()->isPointerTy())
3999     return V;
4000 
4001   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4002     return getPointerBase(Cast->getOperand());
4003   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4004     const SCEV *PtrOp = nullptr;
4005     for (const SCEV *NAryOp : NAry->operands()) {
4006       if (NAryOp->getType()->isPointerTy()) {
4007         // Cannot find the base of an expression with multiple pointer operands.
4008         if (PtrOp)
4009           return V;
4010         PtrOp = NAryOp;
4011       }
4012     }
4013     if (!PtrOp)
4014       return V;
4015     return getPointerBase(PtrOp);
4016   }
4017   return V;
4018 }
4019 
4020 /// Push users of the given Instruction onto the given Worklist.
4021 static void
4022 PushDefUseChildren(Instruction *I,
4023                    SmallVectorImpl<Instruction *> &Worklist) {
4024   // Push the def-use children onto the Worklist stack.
4025   for (User *U : I->users())
4026     Worklist.push_back(cast<Instruction>(U));
4027 }
4028 
4029 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4030   SmallVector<Instruction *, 16> Worklist;
4031   PushDefUseChildren(PN, Worklist);
4032 
4033   SmallPtrSet<Instruction *, 8> Visited;
4034   Visited.insert(PN);
4035   while (!Worklist.empty()) {
4036     Instruction *I = Worklist.pop_back_val();
4037     if (!Visited.insert(I).second)
4038       continue;
4039 
4040     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4041     if (It != ValueExprMap.end()) {
4042       const SCEV *Old = It->second;
4043 
4044       // Short-circuit the def-use traversal if the symbolic name
4045       // ceases to appear in expressions.
4046       if (Old != SymName && !hasOperand(Old, SymName))
4047         continue;
4048 
4049       // SCEVUnknown for a PHI either means that it has an unrecognized
4050       // structure, it's a PHI that's in the progress of being computed
4051       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4052       // additional loop trip count information isn't going to change anything.
4053       // In the second case, createNodeForPHI will perform the necessary
4054       // updates on its own when it gets to that point. In the third, we do
4055       // want to forget the SCEVUnknown.
4056       if (!isa<PHINode>(I) ||
4057           !isa<SCEVUnknown>(Old) ||
4058           (I != PN && Old == SymName)) {
4059         eraseValueFromMap(It->first);
4060         forgetMemoizedResults(Old);
4061       }
4062     }
4063 
4064     PushDefUseChildren(I, Worklist);
4065   }
4066 }
4067 
4068 namespace {
4069 
4070 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4071 /// expression in case its Loop is L. If it is not L then
4072 /// if IgnoreOtherLoops is true then use AddRec itself
4073 /// otherwise rewrite cannot be done.
4074 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4075 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4076 public:
4077   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4078                              bool IgnoreOtherLoops = true) {
4079     SCEVInitRewriter Rewriter(L, SE);
4080     const SCEV *Result = Rewriter.visit(S);
4081     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4082       return SE.getCouldNotCompute();
4083     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4084                ? SE.getCouldNotCompute()
4085                : Result;
4086   }
4087 
4088   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4089     if (!SE.isLoopInvariant(Expr, L))
4090       SeenLoopVariantSCEVUnknown = true;
4091     return Expr;
4092   }
4093 
4094   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4095     // Only re-write AddRecExprs for this loop.
4096     if (Expr->getLoop() == L)
4097       return Expr->getStart();
4098     SeenOtherLoops = true;
4099     return Expr;
4100   }
4101 
4102   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4103 
4104   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4105 
4106 private:
4107   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4108       : SCEVRewriteVisitor(SE), L(L) {}
4109 
4110   const Loop *L;
4111   bool SeenLoopVariantSCEVUnknown = false;
4112   bool SeenOtherLoops = false;
4113 };
4114 
4115 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4116 /// increment expression in case its Loop is L. If it is not L then
4117 /// use AddRec itself.
4118 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4119 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4120 public:
4121   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4122     SCEVPostIncRewriter Rewriter(L, SE);
4123     const SCEV *Result = Rewriter.visit(S);
4124     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4125         ? SE.getCouldNotCompute()
4126         : Result;
4127   }
4128 
4129   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4130     if (!SE.isLoopInvariant(Expr, L))
4131       SeenLoopVariantSCEVUnknown = true;
4132     return Expr;
4133   }
4134 
4135   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4136     // Only re-write AddRecExprs for this loop.
4137     if (Expr->getLoop() == L)
4138       return Expr->getPostIncExpr(SE);
4139     SeenOtherLoops = true;
4140     return Expr;
4141   }
4142 
4143   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4144 
4145   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4146 
4147 private:
4148   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4149       : SCEVRewriteVisitor(SE), L(L) {}
4150 
4151   const Loop *L;
4152   bool SeenLoopVariantSCEVUnknown = false;
4153   bool SeenOtherLoops = false;
4154 };
4155 
4156 /// This class evaluates the compare condition by matching it against the
4157 /// condition of loop latch. If there is a match we assume a true value
4158 /// for the condition while building SCEV nodes.
4159 class SCEVBackedgeConditionFolder
4160     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4161 public:
4162   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4163                              ScalarEvolution &SE) {
4164     bool IsPosBECond = false;
4165     Value *BECond = nullptr;
4166     if (BasicBlock *Latch = L->getLoopLatch()) {
4167       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4168       if (BI && BI->isConditional()) {
4169         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4170                "Both outgoing branches should not target same header!");
4171         BECond = BI->getCondition();
4172         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4173       } else {
4174         return S;
4175       }
4176     }
4177     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4178     return Rewriter.visit(S);
4179   }
4180 
4181   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4182     const SCEV *Result = Expr;
4183     bool InvariantF = SE.isLoopInvariant(Expr, L);
4184 
4185     if (!InvariantF) {
4186       Instruction *I = cast<Instruction>(Expr->getValue());
4187       switch (I->getOpcode()) {
4188       case Instruction::Select: {
4189         SelectInst *SI = cast<SelectInst>(I);
4190         Optional<const SCEV *> Res =
4191             compareWithBackedgeCondition(SI->getCondition());
4192         if (Res.hasValue()) {
4193           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4194           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4195         }
4196         break;
4197       }
4198       default: {
4199         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4200         if (Res.hasValue())
4201           Result = Res.getValue();
4202         break;
4203       }
4204       }
4205     }
4206     return Result;
4207   }
4208 
4209 private:
4210   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4211                                        bool IsPosBECond, ScalarEvolution &SE)
4212       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4213         IsPositiveBECond(IsPosBECond) {}
4214 
4215   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4216 
4217   const Loop *L;
4218   /// Loop back condition.
4219   Value *BackedgeCond = nullptr;
4220   /// Set to true if loop back is on positive branch condition.
4221   bool IsPositiveBECond;
4222 };
4223 
4224 Optional<const SCEV *>
4225 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4226 
4227   // If value matches the backedge condition for loop latch,
4228   // then return a constant evolution node based on loopback
4229   // branch taken.
4230   if (BackedgeCond == IC)
4231     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4232                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4233   return None;
4234 }
4235 
4236 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4237 public:
4238   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4239                              ScalarEvolution &SE) {
4240     SCEVShiftRewriter Rewriter(L, SE);
4241     const SCEV *Result = Rewriter.visit(S);
4242     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4243   }
4244 
4245   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4246     // Only allow AddRecExprs for this loop.
4247     if (!SE.isLoopInvariant(Expr, L))
4248       Valid = false;
4249     return Expr;
4250   }
4251 
4252   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4253     if (Expr->getLoop() == L && Expr->isAffine())
4254       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4255     Valid = false;
4256     return Expr;
4257   }
4258 
4259   bool isValid() { return Valid; }
4260 
4261 private:
4262   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4263       : SCEVRewriteVisitor(SE), L(L) {}
4264 
4265   const Loop *L;
4266   bool Valid = true;
4267 };
4268 
4269 } // end anonymous namespace
4270 
4271 SCEV::NoWrapFlags
4272 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4273   if (!AR->isAffine())
4274     return SCEV::FlagAnyWrap;
4275 
4276   using OBO = OverflowingBinaryOperator;
4277 
4278   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4279 
4280   if (!AR->hasNoSignedWrap()) {
4281     ConstantRange AddRecRange = getSignedRange(AR);
4282     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4283 
4284     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4285         Instruction::Add, IncRange, OBO::NoSignedWrap);
4286     if (NSWRegion.contains(AddRecRange))
4287       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4288   }
4289 
4290   if (!AR->hasNoUnsignedWrap()) {
4291     ConstantRange AddRecRange = getUnsignedRange(AR);
4292     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4293 
4294     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4295         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4296     if (NUWRegion.contains(AddRecRange))
4297       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4298   }
4299 
4300   return Result;
4301 }
4302 
4303 namespace {
4304 
4305 /// Represents an abstract binary operation.  This may exist as a
4306 /// normal instruction or constant expression, or may have been
4307 /// derived from an expression tree.
4308 struct BinaryOp {
4309   unsigned Opcode;
4310   Value *LHS;
4311   Value *RHS;
4312   bool IsNSW = false;
4313   bool IsNUW = false;
4314 
4315   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4316   /// constant expression.
4317   Operator *Op = nullptr;
4318 
4319   explicit BinaryOp(Operator *Op)
4320       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4321         Op(Op) {
4322     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4323       IsNSW = OBO->hasNoSignedWrap();
4324       IsNUW = OBO->hasNoUnsignedWrap();
4325     }
4326   }
4327 
4328   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4329                     bool IsNUW = false)
4330       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4331 };
4332 
4333 } // end anonymous namespace
4334 
4335 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4336 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4337   auto *Op = dyn_cast<Operator>(V);
4338   if (!Op)
4339     return None;
4340 
4341   // Implementation detail: all the cleverness here should happen without
4342   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4343   // SCEV expressions when possible, and we should not break that.
4344 
4345   switch (Op->getOpcode()) {
4346   case Instruction::Add:
4347   case Instruction::Sub:
4348   case Instruction::Mul:
4349   case Instruction::UDiv:
4350   case Instruction::URem:
4351   case Instruction::And:
4352   case Instruction::Or:
4353   case Instruction::AShr:
4354   case Instruction::Shl:
4355     return BinaryOp(Op);
4356 
4357   case Instruction::Xor:
4358     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4359       // If the RHS of the xor is a signmask, then this is just an add.
4360       // Instcombine turns add of signmask into xor as a strength reduction step.
4361       if (RHSC->getValue().isSignMask())
4362         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4363     return BinaryOp(Op);
4364 
4365   case Instruction::LShr:
4366     // Turn logical shift right of a constant into a unsigned divide.
4367     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4368       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4369 
4370       // If the shift count is not less than the bitwidth, the result of
4371       // the shift is undefined. Don't try to analyze it, because the
4372       // resolution chosen here may differ from the resolution chosen in
4373       // other parts of the compiler.
4374       if (SA->getValue().ult(BitWidth)) {
4375         Constant *X =
4376             ConstantInt::get(SA->getContext(),
4377                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4378         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4379       }
4380     }
4381     return BinaryOp(Op);
4382 
4383   case Instruction::ExtractValue: {
4384     auto *EVI = cast<ExtractValueInst>(Op);
4385     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4386       break;
4387 
4388     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4389     if (!CI)
4390       break;
4391 
4392     if (auto *F = CI->getCalledFunction())
4393       switch (F->getIntrinsicID()) {
4394       case Intrinsic::sadd_with_overflow:
4395       case Intrinsic::uadd_with_overflow:
4396         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4397           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4398                           CI->getArgOperand(1));
4399 
4400         // Now that we know that all uses of the arithmetic-result component of
4401         // CI are guarded by the overflow check, we can go ahead and pretend
4402         // that the arithmetic is non-overflowing.
4403         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4404           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4405                           CI->getArgOperand(1), /* IsNSW = */ true,
4406                           /* IsNUW = */ false);
4407         else
4408           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4409                           CI->getArgOperand(1), /* IsNSW = */ false,
4410                           /* IsNUW*/ true);
4411       case Intrinsic::ssub_with_overflow:
4412       case Intrinsic::usub_with_overflow:
4413         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4414           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4415                           CI->getArgOperand(1));
4416 
4417         // The same reasoning as sadd/uadd above.
4418         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4419           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4420                           CI->getArgOperand(1), /* IsNSW = */ true,
4421                           /* IsNUW = */ false);
4422         else
4423           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4424                           CI->getArgOperand(1), /* IsNSW = */ false,
4425                           /* IsNUW = */ true);
4426       case Intrinsic::smul_with_overflow:
4427       case Intrinsic::umul_with_overflow:
4428         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4429                         CI->getArgOperand(1));
4430       default:
4431         break;
4432       }
4433     break;
4434   }
4435 
4436   default:
4437     break;
4438   }
4439 
4440   return None;
4441 }
4442 
4443 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4444 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4445 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4446 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4447 /// follows one of the following patterns:
4448 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4449 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4450 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4451 /// we return the type of the truncation operation, and indicate whether the
4452 /// truncated type should be treated as signed/unsigned by setting
4453 /// \p Signed to true/false, respectively.
4454 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4455                                bool &Signed, ScalarEvolution &SE) {
4456   // The case where Op == SymbolicPHI (that is, with no type conversions on
4457   // the way) is handled by the regular add recurrence creating logic and
4458   // would have already been triggered in createAddRecForPHI. Reaching it here
4459   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4460   // because one of the other operands of the SCEVAddExpr updating this PHI is
4461   // not invariant).
4462   //
4463   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4464   // this case predicates that allow us to prove that Op == SymbolicPHI will
4465   // be added.
4466   if (Op == SymbolicPHI)
4467     return nullptr;
4468 
4469   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4470   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4471   if (SourceBits != NewBits)
4472     return nullptr;
4473 
4474   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4475   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4476   if (!SExt && !ZExt)
4477     return nullptr;
4478   const SCEVTruncateExpr *Trunc =
4479       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4480            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4481   if (!Trunc)
4482     return nullptr;
4483   const SCEV *X = Trunc->getOperand();
4484   if (X != SymbolicPHI)
4485     return nullptr;
4486   Signed = SExt != nullptr;
4487   return Trunc->getType();
4488 }
4489 
4490 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4491   if (!PN->getType()->isIntegerTy())
4492     return nullptr;
4493   const Loop *L = LI.getLoopFor(PN->getParent());
4494   if (!L || L->getHeader() != PN->getParent())
4495     return nullptr;
4496   return L;
4497 }
4498 
4499 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4500 // computation that updates the phi follows the following pattern:
4501 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4502 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4503 // If so, try to see if it can be rewritten as an AddRecExpr under some
4504 // Predicates. If successful, return them as a pair. Also cache the results
4505 // of the analysis.
4506 //
4507 // Example usage scenario:
4508 //    Say the Rewriter is called for the following SCEV:
4509 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4510 //    where:
4511 //         %X = phi i64 (%Start, %BEValue)
4512 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4513 //    and call this function with %SymbolicPHI = %X.
4514 //
4515 //    The analysis will find that the value coming around the backedge has
4516 //    the following SCEV:
4517 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4518 //    Upon concluding that this matches the desired pattern, the function
4519 //    will return the pair {NewAddRec, SmallPredsVec} where:
4520 //         NewAddRec = {%Start,+,%Step}
4521 //         SmallPredsVec = {P1, P2, P3} as follows:
4522 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4523 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4524 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4525 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4526 //    under the predicates {P1,P2,P3}.
4527 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4528 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4529 //
4530 // TODO's:
4531 //
4532 // 1) Extend the Induction descriptor to also support inductions that involve
4533 //    casts: When needed (namely, when we are called in the context of the
4534 //    vectorizer induction analysis), a Set of cast instructions will be
4535 //    populated by this method, and provided back to isInductionPHI. This is
4536 //    needed to allow the vectorizer to properly record them to be ignored by
4537 //    the cost model and to avoid vectorizing them (otherwise these casts,
4538 //    which are redundant under the runtime overflow checks, will be
4539 //    vectorized, which can be costly).
4540 //
4541 // 2) Support additional induction/PHISCEV patterns: We also want to support
4542 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4543 //    after the induction update operation (the induction increment):
4544 //
4545 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4546 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4547 //
4548 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4549 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4550 //
4551 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4552 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4553 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4554   SmallVector<const SCEVPredicate *, 3> Predicates;
4555 
4556   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4557   // return an AddRec expression under some predicate.
4558 
4559   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4560   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4561   assert(L && "Expecting an integer loop header phi");
4562 
4563   // The loop may have multiple entrances or multiple exits; we can analyze
4564   // this phi as an addrec if it has a unique entry value and a unique
4565   // backedge value.
4566   Value *BEValueV = nullptr, *StartValueV = nullptr;
4567   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4568     Value *V = PN->getIncomingValue(i);
4569     if (L->contains(PN->getIncomingBlock(i))) {
4570       if (!BEValueV) {
4571         BEValueV = V;
4572       } else if (BEValueV != V) {
4573         BEValueV = nullptr;
4574         break;
4575       }
4576     } else if (!StartValueV) {
4577       StartValueV = V;
4578     } else if (StartValueV != V) {
4579       StartValueV = nullptr;
4580       break;
4581     }
4582   }
4583   if (!BEValueV || !StartValueV)
4584     return None;
4585 
4586   const SCEV *BEValue = getSCEV(BEValueV);
4587 
4588   // If the value coming around the backedge is an add with the symbolic
4589   // value we just inserted, possibly with casts that we can ignore under
4590   // an appropriate runtime guard, then we found a simple induction variable!
4591   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4592   if (!Add)
4593     return None;
4594 
4595   // If there is a single occurrence of the symbolic value, possibly
4596   // casted, replace it with a recurrence.
4597   unsigned FoundIndex = Add->getNumOperands();
4598   Type *TruncTy = nullptr;
4599   bool Signed;
4600   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4601     if ((TruncTy =
4602              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4603       if (FoundIndex == e) {
4604         FoundIndex = i;
4605         break;
4606       }
4607 
4608   if (FoundIndex == Add->getNumOperands())
4609     return None;
4610 
4611   // Create an add with everything but the specified operand.
4612   SmallVector<const SCEV *, 8> Ops;
4613   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4614     if (i != FoundIndex)
4615       Ops.push_back(Add->getOperand(i));
4616   const SCEV *Accum = getAddExpr(Ops);
4617 
4618   // The runtime checks will not be valid if the step amount is
4619   // varying inside the loop.
4620   if (!isLoopInvariant(Accum, L))
4621     return None;
4622 
4623   // *** Part2: Create the predicates
4624 
4625   // Analysis was successful: we have a phi-with-cast pattern for which we
4626   // can return an AddRec expression under the following predicates:
4627   //
4628   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4629   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4630   // P2: An Equal predicate that guarantees that
4631   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4632   // P3: An Equal predicate that guarantees that
4633   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4634   //
4635   // As we next prove, the above predicates guarantee that:
4636   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4637   //
4638   //
4639   // More formally, we want to prove that:
4640   //     Expr(i+1) = Start + (i+1) * Accum
4641   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4642   //
4643   // Given that:
4644   // 1) Expr(0) = Start
4645   // 2) Expr(1) = Start + Accum
4646   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4647   // 3) Induction hypothesis (step i):
4648   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4649   //
4650   // Proof:
4651   //  Expr(i+1) =
4652   //   = Start + (i+1)*Accum
4653   //   = (Start + i*Accum) + Accum
4654   //   = Expr(i) + Accum
4655   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4656   //                                                             :: from step i
4657   //
4658   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4659   //
4660   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4661   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4662   //     + Accum                                                     :: from P3
4663   //
4664   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4665   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4666   //
4667   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4668   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4669   //
4670   // By induction, the same applies to all iterations 1<=i<n:
4671   //
4672 
4673   // Create a truncated addrec for which we will add a no overflow check (P1).
4674   const SCEV *StartVal = getSCEV(StartValueV);
4675   const SCEV *PHISCEV =
4676       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4677                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4678 
4679   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4680   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4681   // will be constant.
4682   //
4683   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4684   // add P1.
4685   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4686     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4687         Signed ? SCEVWrapPredicate::IncrementNSSW
4688                : SCEVWrapPredicate::IncrementNUSW;
4689     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4690     Predicates.push_back(AddRecPred);
4691   }
4692 
4693   // Create the Equal Predicates P2,P3:
4694 
4695   // It is possible that the predicates P2 and/or P3 are computable at
4696   // compile time due to StartVal and/or Accum being constants.
4697   // If either one is, then we can check that now and escape if either P2
4698   // or P3 is false.
4699 
4700   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4701   // for each of StartVal and Accum
4702   auto getExtendedExpr = [&](const SCEV *Expr,
4703                              bool CreateSignExtend) -> const SCEV * {
4704     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4705     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4706     const SCEV *ExtendedExpr =
4707         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4708                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4709     return ExtendedExpr;
4710   };
4711 
4712   // Given:
4713   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4714   //               = getExtendedExpr(Expr)
4715   // Determine whether the predicate P: Expr == ExtendedExpr
4716   // is known to be false at compile time
4717   auto PredIsKnownFalse = [&](const SCEV *Expr,
4718                               const SCEV *ExtendedExpr) -> bool {
4719     return Expr != ExtendedExpr &&
4720            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4721   };
4722 
4723   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4724   if (PredIsKnownFalse(StartVal, StartExtended)) {
4725     DEBUG(dbgs() << "P2 is compile-time false\n";);
4726     return None;
4727   }
4728 
4729   // The Step is always Signed (because the overflow checks are either
4730   // NSSW or NUSW)
4731   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4732   if (PredIsKnownFalse(Accum, AccumExtended)) {
4733     DEBUG(dbgs() << "P3 is compile-time false\n";);
4734     return None;
4735   }
4736 
4737   auto AppendPredicate = [&](const SCEV *Expr,
4738                              const SCEV *ExtendedExpr) -> void {
4739     if (Expr != ExtendedExpr &&
4740         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4741       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4742       DEBUG (dbgs() << "Added Predicate: " << *Pred);
4743       Predicates.push_back(Pred);
4744     }
4745   };
4746 
4747   AppendPredicate(StartVal, StartExtended);
4748   AppendPredicate(Accum, AccumExtended);
4749 
4750   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4751   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4752   // into NewAR if it will also add the runtime overflow checks specified in
4753   // Predicates.
4754   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4755 
4756   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4757       std::make_pair(NewAR, Predicates);
4758   // Remember the result of the analysis for this SCEV at this locayyytion.
4759   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4760   return PredRewrite;
4761 }
4762 
4763 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4764 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4765   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4766   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4767   if (!L)
4768     return None;
4769 
4770   // Check to see if we already analyzed this PHI.
4771   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4772   if (I != PredicatedSCEVRewrites.end()) {
4773     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4774         I->second;
4775     // Analysis was done before and failed to create an AddRec:
4776     if (Rewrite.first == SymbolicPHI)
4777       return None;
4778     // Analysis was done before and succeeded to create an AddRec under
4779     // a predicate:
4780     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4781     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4782     return Rewrite;
4783   }
4784 
4785   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4786     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4787 
4788   // Record in the cache that the analysis failed
4789   if (!Rewrite) {
4790     SmallVector<const SCEVPredicate *, 3> Predicates;
4791     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4792     return None;
4793   }
4794 
4795   return Rewrite;
4796 }
4797 
4798 // FIXME: This utility is currently required because the Rewriter currently
4799 // does not rewrite this expression:
4800 // {0, +, (sext ix (trunc iy to ix) to iy)}
4801 // into {0, +, %step},
4802 // even when the following Equal predicate exists:
4803 // "%step == (sext ix (trunc iy to ix) to iy)".
4804 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4805     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4806   if (AR1 == AR2)
4807     return true;
4808 
4809   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4810     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4811         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4812       return false;
4813     return true;
4814   };
4815 
4816   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4817       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4818     return false;
4819   return true;
4820 }
4821 
4822 /// A helper function for createAddRecFromPHI to handle simple cases.
4823 ///
4824 /// This function tries to find an AddRec expression for the simplest (yet most
4825 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4826 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4827 /// technique for finding the AddRec expression.
4828 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4829                                                       Value *BEValueV,
4830                                                       Value *StartValueV) {
4831   const Loop *L = LI.getLoopFor(PN->getParent());
4832   assert(L && L->getHeader() == PN->getParent());
4833   assert(BEValueV && StartValueV);
4834 
4835   auto BO = MatchBinaryOp(BEValueV, DT);
4836   if (!BO)
4837     return nullptr;
4838 
4839   if (BO->Opcode != Instruction::Add)
4840     return nullptr;
4841 
4842   const SCEV *Accum = nullptr;
4843   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4844     Accum = getSCEV(BO->RHS);
4845   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4846     Accum = getSCEV(BO->LHS);
4847 
4848   if (!Accum)
4849     return nullptr;
4850 
4851   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4852   if (BO->IsNUW)
4853     Flags = setFlags(Flags, SCEV::FlagNUW);
4854   if (BO->IsNSW)
4855     Flags = setFlags(Flags, SCEV::FlagNSW);
4856 
4857   const SCEV *StartVal = getSCEV(StartValueV);
4858   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4859 
4860   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4861 
4862   // We can add Flags to the post-inc expression only if we
4863   // know that it is *undefined behavior* for BEValueV to
4864   // overflow.
4865   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4866     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4867       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4868 
4869   return PHISCEV;
4870 }
4871 
4872 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
4873   const Loop *L = LI.getLoopFor(PN->getParent());
4874   if (!L || L->getHeader() != PN->getParent())
4875     return nullptr;
4876 
4877   // The loop may have multiple entrances or multiple exits; we can analyze
4878   // this phi as an addrec if it has a unique entry value and a unique
4879   // backedge value.
4880   Value *BEValueV = nullptr, *StartValueV = nullptr;
4881   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4882     Value *V = PN->getIncomingValue(i);
4883     if (L->contains(PN->getIncomingBlock(i))) {
4884       if (!BEValueV) {
4885         BEValueV = V;
4886       } else if (BEValueV != V) {
4887         BEValueV = nullptr;
4888         break;
4889       }
4890     } else if (!StartValueV) {
4891       StartValueV = V;
4892     } else if (StartValueV != V) {
4893       StartValueV = nullptr;
4894       break;
4895     }
4896   }
4897   if (!BEValueV || !StartValueV)
4898     return nullptr;
4899 
4900   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
4901          "PHI node already processed?");
4902 
4903   // First, try to find AddRec expression without creating a fictituos symbolic
4904   // value for PN.
4905   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
4906     return S;
4907 
4908   // Handle PHI node value symbolically.
4909   const SCEV *SymbolicName = getUnknown(PN);
4910   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
4911 
4912   // Using this symbolic name for the PHI, analyze the value coming around
4913   // the back-edge.
4914   const SCEV *BEValue = getSCEV(BEValueV);
4915 
4916   // NOTE: If BEValue is loop invariant, we know that the PHI node just
4917   // has a special value for the first iteration of the loop.
4918 
4919   // If the value coming around the backedge is an add with the symbolic
4920   // value we just inserted, then we found a simple induction variable!
4921   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
4922     // If there is a single occurrence of the symbolic value, replace it
4923     // with a recurrence.
4924     unsigned FoundIndex = Add->getNumOperands();
4925     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4926       if (Add->getOperand(i) == SymbolicName)
4927         if (FoundIndex == e) {
4928           FoundIndex = i;
4929           break;
4930         }
4931 
4932     if (FoundIndex != Add->getNumOperands()) {
4933       // Create an add with everything but the specified operand.
4934       SmallVector<const SCEV *, 8> Ops;
4935       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4936         if (i != FoundIndex)
4937           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
4938                                                              L, *this));
4939       const SCEV *Accum = getAddExpr(Ops);
4940 
4941       // This is not a valid addrec if the step amount is varying each
4942       // loop iteration, but is not itself an addrec in this loop.
4943       if (isLoopInvariant(Accum, L) ||
4944           (isa<SCEVAddRecExpr>(Accum) &&
4945            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
4946         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4947 
4948         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
4949           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4950             if (BO->IsNUW)
4951               Flags = setFlags(Flags, SCEV::FlagNUW);
4952             if (BO->IsNSW)
4953               Flags = setFlags(Flags, SCEV::FlagNSW);
4954           }
4955         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4956           // If the increment is an inbounds GEP, then we know the address
4957           // space cannot be wrapped around. We cannot make any guarantee
4958           // about signed or unsigned overflow because pointers are
4959           // unsigned but we may have a negative index from the base
4960           // pointer. We can guarantee that no unsigned wrap occurs if the
4961           // indices form a positive value.
4962           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4963             Flags = setFlags(Flags, SCEV::FlagNW);
4964 
4965             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4966             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4967               Flags = setFlags(Flags, SCEV::FlagNUW);
4968           }
4969 
4970           // We cannot transfer nuw and nsw flags from subtraction
4971           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4972           // for instance.
4973         }
4974 
4975         const SCEV *StartVal = getSCEV(StartValueV);
4976         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4977 
4978         // Okay, for the entire analysis of this edge we assumed the PHI
4979         // to be symbolic.  We now need to go back and purge all of the
4980         // entries for the scalars that use the symbolic expression.
4981         forgetSymbolicName(PN, SymbolicName);
4982         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4983 
4984         // We can add Flags to the post-inc expression only if we
4985         // know that it is *undefined behavior* for BEValueV to
4986         // overflow.
4987         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4988           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4989             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4990 
4991         return PHISCEV;
4992       }
4993     }
4994   } else {
4995     // Otherwise, this could be a loop like this:
4996     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
4997     // In this case, j = {1,+,1}  and BEValue is j.
4998     // Because the other in-value of i (0) fits the evolution of BEValue
4999     // i really is an addrec evolution.
5000     //
5001     // We can generalize this saying that i is the shifted value of BEValue
5002     // by one iteration:
5003     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5004     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5005     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5006     if (Shifted != getCouldNotCompute() &&
5007         Start != getCouldNotCompute()) {
5008       const SCEV *StartVal = getSCEV(StartValueV);
5009       if (Start == StartVal) {
5010         // Okay, for the entire analysis of this edge we assumed the PHI
5011         // to be symbolic.  We now need to go back and purge all of the
5012         // entries for the scalars that use the symbolic expression.
5013         forgetSymbolicName(PN, SymbolicName);
5014         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5015         return Shifted;
5016       }
5017     }
5018   }
5019 
5020   // Remove the temporary PHI node SCEV that has been inserted while intending
5021   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5022   // as it will prevent later (possibly simpler) SCEV expressions to be added
5023   // to the ValueExprMap.
5024   eraseValueFromMap(PN);
5025 
5026   return nullptr;
5027 }
5028 
5029 // Checks if the SCEV S is available at BB.  S is considered available at BB
5030 // if S can be materialized at BB without introducing a fault.
5031 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5032                                BasicBlock *BB) {
5033   struct CheckAvailable {
5034     bool TraversalDone = false;
5035     bool Available = true;
5036 
5037     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5038     BasicBlock *BB = nullptr;
5039     DominatorTree &DT;
5040 
5041     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5042       : L(L), BB(BB), DT(DT) {}
5043 
5044     bool setUnavailable() {
5045       TraversalDone = true;
5046       Available = false;
5047       return false;
5048     }
5049 
5050     bool follow(const SCEV *S) {
5051       switch (S->getSCEVType()) {
5052       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5053       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5054         // These expressions are available if their operand(s) is/are.
5055         return true;
5056 
5057       case scAddRecExpr: {
5058         // We allow add recurrences that are on the loop BB is in, or some
5059         // outer loop.  This guarantees availability because the value of the
5060         // add recurrence at BB is simply the "current" value of the induction
5061         // variable.  We can relax this in the future; for instance an add
5062         // recurrence on a sibling dominating loop is also available at BB.
5063         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5064         if (L && (ARLoop == L || ARLoop->contains(L)))
5065           return true;
5066 
5067         return setUnavailable();
5068       }
5069 
5070       case scUnknown: {
5071         // For SCEVUnknown, we check for simple dominance.
5072         const auto *SU = cast<SCEVUnknown>(S);
5073         Value *V = SU->getValue();
5074 
5075         if (isa<Argument>(V))
5076           return false;
5077 
5078         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5079           return false;
5080 
5081         return setUnavailable();
5082       }
5083 
5084       case scUDivExpr:
5085       case scCouldNotCompute:
5086         // We do not try to smart about these at all.
5087         return setUnavailable();
5088       }
5089       llvm_unreachable("switch should be fully covered!");
5090     }
5091 
5092     bool isDone() { return TraversalDone; }
5093   };
5094 
5095   CheckAvailable CA(L, BB, DT);
5096   SCEVTraversal<CheckAvailable> ST(CA);
5097 
5098   ST.visitAll(S);
5099   return CA.Available;
5100 }
5101 
5102 // Try to match a control flow sequence that branches out at BI and merges back
5103 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5104 // match.
5105 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5106                           Value *&C, Value *&LHS, Value *&RHS) {
5107   C = BI->getCondition();
5108 
5109   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5110   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5111 
5112   if (!LeftEdge.isSingleEdge())
5113     return false;
5114 
5115   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5116 
5117   Use &LeftUse = Merge->getOperandUse(0);
5118   Use &RightUse = Merge->getOperandUse(1);
5119 
5120   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5121     LHS = LeftUse;
5122     RHS = RightUse;
5123     return true;
5124   }
5125 
5126   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5127     LHS = RightUse;
5128     RHS = LeftUse;
5129     return true;
5130   }
5131 
5132   return false;
5133 }
5134 
5135 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5136   auto IsReachable =
5137       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5138   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5139     const Loop *L = LI.getLoopFor(PN->getParent());
5140 
5141     // We don't want to break LCSSA, even in a SCEV expression tree.
5142     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5143       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5144         return nullptr;
5145 
5146     // Try to match
5147     //
5148     //  br %cond, label %left, label %right
5149     // left:
5150     //  br label %merge
5151     // right:
5152     //  br label %merge
5153     // merge:
5154     //  V = phi [ %x, %left ], [ %y, %right ]
5155     //
5156     // as "select %cond, %x, %y"
5157 
5158     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5159     assert(IDom && "At least the entry block should dominate PN");
5160 
5161     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5162     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5163 
5164     if (BI && BI->isConditional() &&
5165         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5166         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5167         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5168       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5169   }
5170 
5171   return nullptr;
5172 }
5173 
5174 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5175   if (const SCEV *S = createAddRecFromPHI(PN))
5176     return S;
5177 
5178   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5179     return S;
5180 
5181   // If the PHI has a single incoming value, follow that value, unless the
5182   // PHI's incoming blocks are in a different loop, in which case doing so
5183   // risks breaking LCSSA form. Instcombine would normally zap these, but
5184   // it doesn't have DominatorTree information, so it may miss cases.
5185   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5186     if (LI.replacementPreservesLCSSAForm(PN, V))
5187       return getSCEV(V);
5188 
5189   // If it's not a loop phi, we can't handle it yet.
5190   return getUnknown(PN);
5191 }
5192 
5193 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5194                                                       Value *Cond,
5195                                                       Value *TrueVal,
5196                                                       Value *FalseVal) {
5197   // Handle "constant" branch or select. This can occur for instance when a
5198   // loop pass transforms an inner loop and moves on to process the outer loop.
5199   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5200     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5201 
5202   // Try to match some simple smax or umax patterns.
5203   auto *ICI = dyn_cast<ICmpInst>(Cond);
5204   if (!ICI)
5205     return getUnknown(I);
5206 
5207   Value *LHS = ICI->getOperand(0);
5208   Value *RHS = ICI->getOperand(1);
5209 
5210   switch (ICI->getPredicate()) {
5211   case ICmpInst::ICMP_SLT:
5212   case ICmpInst::ICMP_SLE:
5213     std::swap(LHS, RHS);
5214     LLVM_FALLTHROUGH;
5215   case ICmpInst::ICMP_SGT:
5216   case ICmpInst::ICMP_SGE:
5217     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5218     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5219     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5220       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5221       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5222       const SCEV *LA = getSCEV(TrueVal);
5223       const SCEV *RA = getSCEV(FalseVal);
5224       const SCEV *LDiff = getMinusSCEV(LA, LS);
5225       const SCEV *RDiff = getMinusSCEV(RA, RS);
5226       if (LDiff == RDiff)
5227         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5228       LDiff = getMinusSCEV(LA, RS);
5229       RDiff = getMinusSCEV(RA, LS);
5230       if (LDiff == RDiff)
5231         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5232     }
5233     break;
5234   case ICmpInst::ICMP_ULT:
5235   case ICmpInst::ICMP_ULE:
5236     std::swap(LHS, RHS);
5237     LLVM_FALLTHROUGH;
5238   case ICmpInst::ICMP_UGT:
5239   case ICmpInst::ICMP_UGE:
5240     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5241     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5242     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5243       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5244       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5245       const SCEV *LA = getSCEV(TrueVal);
5246       const SCEV *RA = getSCEV(FalseVal);
5247       const SCEV *LDiff = getMinusSCEV(LA, LS);
5248       const SCEV *RDiff = getMinusSCEV(RA, RS);
5249       if (LDiff == RDiff)
5250         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5251       LDiff = getMinusSCEV(LA, RS);
5252       RDiff = getMinusSCEV(RA, LS);
5253       if (LDiff == RDiff)
5254         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5255     }
5256     break;
5257   case ICmpInst::ICMP_NE:
5258     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5259     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5260         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5261       const SCEV *One = getOne(I->getType());
5262       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5263       const SCEV *LA = getSCEV(TrueVal);
5264       const SCEV *RA = getSCEV(FalseVal);
5265       const SCEV *LDiff = getMinusSCEV(LA, LS);
5266       const SCEV *RDiff = getMinusSCEV(RA, One);
5267       if (LDiff == RDiff)
5268         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5269     }
5270     break;
5271   case ICmpInst::ICMP_EQ:
5272     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5273     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5274         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5275       const SCEV *One = getOne(I->getType());
5276       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5277       const SCEV *LA = getSCEV(TrueVal);
5278       const SCEV *RA = getSCEV(FalseVal);
5279       const SCEV *LDiff = getMinusSCEV(LA, One);
5280       const SCEV *RDiff = getMinusSCEV(RA, LS);
5281       if (LDiff == RDiff)
5282         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5283     }
5284     break;
5285   default:
5286     break;
5287   }
5288 
5289   return getUnknown(I);
5290 }
5291 
5292 /// Expand GEP instructions into add and multiply operations. This allows them
5293 /// to be analyzed by regular SCEV code.
5294 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5295   // Don't attempt to analyze GEPs over unsized objects.
5296   if (!GEP->getSourceElementType()->isSized())
5297     return getUnknown(GEP);
5298 
5299   SmallVector<const SCEV *, 4> IndexExprs;
5300   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5301     IndexExprs.push_back(getSCEV(*Index));
5302   return getGEPExpr(GEP, IndexExprs);
5303 }
5304 
5305 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5306   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5307     return C->getAPInt().countTrailingZeros();
5308 
5309   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5310     return std::min(GetMinTrailingZeros(T->getOperand()),
5311                     (uint32_t)getTypeSizeInBits(T->getType()));
5312 
5313   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5314     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5315     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5316                ? getTypeSizeInBits(E->getType())
5317                : OpRes;
5318   }
5319 
5320   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5321     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5322     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5323                ? getTypeSizeInBits(E->getType())
5324                : OpRes;
5325   }
5326 
5327   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5328     // The result is the min of all operands results.
5329     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5330     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5331       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5332     return MinOpRes;
5333   }
5334 
5335   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5336     // The result is the sum of all operands results.
5337     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5338     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5339     for (unsigned i = 1, e = M->getNumOperands();
5340          SumOpRes != BitWidth && i != e; ++i)
5341       SumOpRes =
5342           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5343     return SumOpRes;
5344   }
5345 
5346   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5347     // The result is the min of all operands results.
5348     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5349     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5350       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5351     return MinOpRes;
5352   }
5353 
5354   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5355     // The result is the min of all operands results.
5356     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5357     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5358       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5359     return MinOpRes;
5360   }
5361 
5362   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5363     // The result is the min of all operands results.
5364     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5365     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5366       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5367     return MinOpRes;
5368   }
5369 
5370   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5371     // For a SCEVUnknown, ask ValueTracking.
5372     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5373     return Known.countMinTrailingZeros();
5374   }
5375 
5376   // SCEVUDivExpr
5377   return 0;
5378 }
5379 
5380 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5381   auto I = MinTrailingZerosCache.find(S);
5382   if (I != MinTrailingZerosCache.end())
5383     return I->second;
5384 
5385   uint32_t Result = GetMinTrailingZerosImpl(S);
5386   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5387   assert(InsertPair.second && "Should insert a new key");
5388   return InsertPair.first->second;
5389 }
5390 
5391 /// Helper method to assign a range to V from metadata present in the IR.
5392 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5393   if (Instruction *I = dyn_cast<Instruction>(V))
5394     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5395       return getConstantRangeFromMetadata(*MD);
5396 
5397   return None;
5398 }
5399 
5400 /// Determine the range for a particular SCEV.  If SignHint is
5401 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5402 /// with a "cleaner" unsigned (resp. signed) representation.
5403 const ConstantRange &
5404 ScalarEvolution::getRangeRef(const SCEV *S,
5405                              ScalarEvolution::RangeSignHint SignHint) {
5406   DenseMap<const SCEV *, ConstantRange> &Cache =
5407       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5408                                                        : SignedRanges;
5409 
5410   // See if we've computed this range already.
5411   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5412   if (I != Cache.end())
5413     return I->second;
5414 
5415   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5416     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5417 
5418   unsigned BitWidth = getTypeSizeInBits(S->getType());
5419   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5420 
5421   // If the value has known zeros, the maximum value will have those known zeros
5422   // as well.
5423   uint32_t TZ = GetMinTrailingZeros(S);
5424   if (TZ != 0) {
5425     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5426       ConservativeResult =
5427           ConstantRange(APInt::getMinValue(BitWidth),
5428                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5429     else
5430       ConservativeResult = ConstantRange(
5431           APInt::getSignedMinValue(BitWidth),
5432           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5433   }
5434 
5435   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5436     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5437     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5438       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5439     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5440   }
5441 
5442   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5443     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5444     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5445       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5446     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5447   }
5448 
5449   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5450     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5451     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5452       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5453     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5454   }
5455 
5456   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5457     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5458     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5459       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5460     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5461   }
5462 
5463   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5464     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5465     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5466     return setRange(UDiv, SignHint,
5467                     ConservativeResult.intersectWith(X.udiv(Y)));
5468   }
5469 
5470   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5471     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5472     return setRange(ZExt, SignHint,
5473                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5474   }
5475 
5476   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5477     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5478     return setRange(SExt, SignHint,
5479                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5480   }
5481 
5482   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5483     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5484     return setRange(Trunc, SignHint,
5485                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
5486   }
5487 
5488   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5489     // If there's no unsigned wrap, the value will never be less than its
5490     // initial value.
5491     if (AddRec->hasNoUnsignedWrap())
5492       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5493         if (!C->getValue()->isZero())
5494           ConservativeResult = ConservativeResult.intersectWith(
5495               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5496 
5497     // If there's no signed wrap, and all the operands have the same sign or
5498     // zero, the value won't ever change sign.
5499     if (AddRec->hasNoSignedWrap()) {
5500       bool AllNonNeg = true;
5501       bool AllNonPos = true;
5502       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5503         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5504         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5505       }
5506       if (AllNonNeg)
5507         ConservativeResult = ConservativeResult.intersectWith(
5508           ConstantRange(APInt(BitWidth, 0),
5509                         APInt::getSignedMinValue(BitWidth)));
5510       else if (AllNonPos)
5511         ConservativeResult = ConservativeResult.intersectWith(
5512           ConstantRange(APInt::getSignedMinValue(BitWidth),
5513                         APInt(BitWidth, 1)));
5514     }
5515 
5516     // TODO: non-affine addrec
5517     if (AddRec->isAffine()) {
5518       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5519       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5520           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5521         auto RangeFromAffine = getRangeForAffineAR(
5522             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5523             BitWidth);
5524         if (!RangeFromAffine.isFullSet())
5525           ConservativeResult =
5526               ConservativeResult.intersectWith(RangeFromAffine);
5527 
5528         auto RangeFromFactoring = getRangeViaFactoring(
5529             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5530             BitWidth);
5531         if (!RangeFromFactoring.isFullSet())
5532           ConservativeResult =
5533               ConservativeResult.intersectWith(RangeFromFactoring);
5534       }
5535     }
5536 
5537     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5538   }
5539 
5540   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5541     // Check if the IR explicitly contains !range metadata.
5542     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5543     if (MDRange.hasValue())
5544       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5545 
5546     // Split here to avoid paying the compile-time cost of calling both
5547     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5548     // if needed.
5549     const DataLayout &DL = getDataLayout();
5550     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5551       // For a SCEVUnknown, ask ValueTracking.
5552       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5553       if (Known.One != ~Known.Zero + 1)
5554         ConservativeResult =
5555             ConservativeResult.intersectWith(ConstantRange(Known.One,
5556                                                            ~Known.Zero + 1));
5557     } else {
5558       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5559              "generalize as needed!");
5560       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5561       if (NS > 1)
5562         ConservativeResult = ConservativeResult.intersectWith(
5563             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5564                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5565     }
5566 
5567     // A range of Phi is a subset of union of all ranges of its input.
5568     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5569       // Make sure that we do not run over cycled Phis.
5570       if (PendingPhiRanges.insert(Phi).second) {
5571         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5572         for (auto &Op : Phi->operands()) {
5573           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5574           RangeFromOps = RangeFromOps.unionWith(OpRange);
5575           // No point to continue if we already have a full set.
5576           if (RangeFromOps.isFullSet())
5577             break;
5578         }
5579         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5580         bool Erased = PendingPhiRanges.erase(Phi);
5581         assert(Erased && "Failed to erase Phi properly?");
5582         (void) Erased;
5583       }
5584     }
5585 
5586     return setRange(U, SignHint, std::move(ConservativeResult));
5587   }
5588 
5589   return setRange(S, SignHint, std::move(ConservativeResult));
5590 }
5591 
5592 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5593 // values that the expression can take. Initially, the expression has a value
5594 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5595 // argument defines if we treat Step as signed or unsigned.
5596 static ConstantRange getRangeForAffineARHelper(APInt Step,
5597                                                const ConstantRange &StartRange,
5598                                                const APInt &MaxBECount,
5599                                                unsigned BitWidth, bool Signed) {
5600   // If either Step or MaxBECount is 0, then the expression won't change, and we
5601   // just need to return the initial range.
5602   if (Step == 0 || MaxBECount == 0)
5603     return StartRange;
5604 
5605   // If we don't know anything about the initial value (i.e. StartRange is
5606   // FullRange), then we don't know anything about the final range either.
5607   // Return FullRange.
5608   if (StartRange.isFullSet())
5609     return ConstantRange(BitWidth, /* isFullSet = */ true);
5610 
5611   // If Step is signed and negative, then we use its absolute value, but we also
5612   // note that we're moving in the opposite direction.
5613   bool Descending = Signed && Step.isNegative();
5614 
5615   if (Signed)
5616     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5617     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5618     // This equations hold true due to the well-defined wrap-around behavior of
5619     // APInt.
5620     Step = Step.abs();
5621 
5622   // Check if Offset is more than full span of BitWidth. If it is, the
5623   // expression is guaranteed to overflow.
5624   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5625     return ConstantRange(BitWidth, /* isFullSet = */ true);
5626 
5627   // Offset is by how much the expression can change. Checks above guarantee no
5628   // overflow here.
5629   APInt Offset = Step * MaxBECount;
5630 
5631   // Minimum value of the final range will match the minimal value of StartRange
5632   // if the expression is increasing and will be decreased by Offset otherwise.
5633   // Maximum value of the final range will match the maximal value of StartRange
5634   // if the expression is decreasing and will be increased by Offset otherwise.
5635   APInt StartLower = StartRange.getLower();
5636   APInt StartUpper = StartRange.getUpper() - 1;
5637   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5638                                    : (StartUpper + std::move(Offset));
5639 
5640   // It's possible that the new minimum/maximum value will fall into the initial
5641   // range (due to wrap around). This means that the expression can take any
5642   // value in this bitwidth, and we have to return full range.
5643   if (StartRange.contains(MovedBoundary))
5644     return ConstantRange(BitWidth, /* isFullSet = */ true);
5645 
5646   APInt NewLower =
5647       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5648   APInt NewUpper =
5649       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5650   NewUpper += 1;
5651 
5652   // If we end up with full range, return a proper full range.
5653   if (NewLower == NewUpper)
5654     return ConstantRange(BitWidth, /* isFullSet = */ true);
5655 
5656   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5657   return ConstantRange(std::move(NewLower), std::move(NewUpper));
5658 }
5659 
5660 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5661                                                    const SCEV *Step,
5662                                                    const SCEV *MaxBECount,
5663                                                    unsigned BitWidth) {
5664   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5665          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5666          "Precondition!");
5667 
5668   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5669   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5670 
5671   // First, consider step signed.
5672   ConstantRange StartSRange = getSignedRange(Start);
5673   ConstantRange StepSRange = getSignedRange(Step);
5674 
5675   // If Step can be both positive and negative, we need to find ranges for the
5676   // maximum absolute step values in both directions and union them.
5677   ConstantRange SR =
5678       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5679                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5680   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5681                                               StartSRange, MaxBECountValue,
5682                                               BitWidth, /* Signed = */ true));
5683 
5684   // Next, consider step unsigned.
5685   ConstantRange UR = getRangeForAffineARHelper(
5686       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5687       MaxBECountValue, BitWidth, /* Signed = */ false);
5688 
5689   // Finally, intersect signed and unsigned ranges.
5690   return SR.intersectWith(UR);
5691 }
5692 
5693 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5694                                                     const SCEV *Step,
5695                                                     const SCEV *MaxBECount,
5696                                                     unsigned BitWidth) {
5697   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5698   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5699 
5700   struct SelectPattern {
5701     Value *Condition = nullptr;
5702     APInt TrueValue;
5703     APInt FalseValue;
5704 
5705     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5706                            const SCEV *S) {
5707       Optional<unsigned> CastOp;
5708       APInt Offset(BitWidth, 0);
5709 
5710       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5711              "Should be!");
5712 
5713       // Peel off a constant offset:
5714       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5715         // In the future we could consider being smarter here and handle
5716         // {Start+Step,+,Step} too.
5717         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5718           return;
5719 
5720         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5721         S = SA->getOperand(1);
5722       }
5723 
5724       // Peel off a cast operation
5725       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5726         CastOp = SCast->getSCEVType();
5727         S = SCast->getOperand();
5728       }
5729 
5730       using namespace llvm::PatternMatch;
5731 
5732       auto *SU = dyn_cast<SCEVUnknown>(S);
5733       const APInt *TrueVal, *FalseVal;
5734       if (!SU ||
5735           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5736                                           m_APInt(FalseVal)))) {
5737         Condition = nullptr;
5738         return;
5739       }
5740 
5741       TrueValue = *TrueVal;
5742       FalseValue = *FalseVal;
5743 
5744       // Re-apply the cast we peeled off earlier
5745       if (CastOp.hasValue())
5746         switch (*CastOp) {
5747         default:
5748           llvm_unreachable("Unknown SCEV cast type!");
5749 
5750         case scTruncate:
5751           TrueValue = TrueValue.trunc(BitWidth);
5752           FalseValue = FalseValue.trunc(BitWidth);
5753           break;
5754         case scZeroExtend:
5755           TrueValue = TrueValue.zext(BitWidth);
5756           FalseValue = FalseValue.zext(BitWidth);
5757           break;
5758         case scSignExtend:
5759           TrueValue = TrueValue.sext(BitWidth);
5760           FalseValue = FalseValue.sext(BitWidth);
5761           break;
5762         }
5763 
5764       // Re-apply the constant offset we peeled off earlier
5765       TrueValue += Offset;
5766       FalseValue += Offset;
5767     }
5768 
5769     bool isRecognized() { return Condition != nullptr; }
5770   };
5771 
5772   SelectPattern StartPattern(*this, BitWidth, Start);
5773   if (!StartPattern.isRecognized())
5774     return ConstantRange(BitWidth, /* isFullSet = */ true);
5775 
5776   SelectPattern StepPattern(*this, BitWidth, Step);
5777   if (!StepPattern.isRecognized())
5778     return ConstantRange(BitWidth, /* isFullSet = */ true);
5779 
5780   if (StartPattern.Condition != StepPattern.Condition) {
5781     // We don't handle this case today; but we could, by considering four
5782     // possibilities below instead of two. I'm not sure if there are cases where
5783     // that will help over what getRange already does, though.
5784     return ConstantRange(BitWidth, /* isFullSet = */ true);
5785   }
5786 
5787   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5788   // construct arbitrary general SCEV expressions here.  This function is called
5789   // from deep in the call stack, and calling getSCEV (on a sext instruction,
5790   // say) can end up caching a suboptimal value.
5791 
5792   // FIXME: without the explicit `this` receiver below, MSVC errors out with
5793   // C2352 and C2512 (otherwise it isn't needed).
5794 
5795   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5796   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5797   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5798   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5799 
5800   ConstantRange TrueRange =
5801       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5802   ConstantRange FalseRange =
5803       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5804 
5805   return TrueRange.unionWith(FalseRange);
5806 }
5807 
5808 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5809   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5810   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5811 
5812   // Return early if there are no flags to propagate to the SCEV.
5813   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5814   if (BinOp->hasNoUnsignedWrap())
5815     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5816   if (BinOp->hasNoSignedWrap())
5817     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5818   if (Flags == SCEV::FlagAnyWrap)
5819     return SCEV::FlagAnyWrap;
5820 
5821   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5822 }
5823 
5824 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5825   // Here we check that I is in the header of the innermost loop containing I,
5826   // since we only deal with instructions in the loop header. The actual loop we
5827   // need to check later will come from an add recurrence, but getting that
5828   // requires computing the SCEV of the operands, which can be expensive. This
5829   // check we can do cheaply to rule out some cases early.
5830   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5831   if (InnermostContainingLoop == nullptr ||
5832       InnermostContainingLoop->getHeader() != I->getParent())
5833     return false;
5834 
5835   // Only proceed if we can prove that I does not yield poison.
5836   if (!programUndefinedIfFullPoison(I))
5837     return false;
5838 
5839   // At this point we know that if I is executed, then it does not wrap
5840   // according to at least one of NSW or NUW. If I is not executed, then we do
5841   // not know if the calculation that I represents would wrap. Multiple
5842   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5843   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5844   // derived from other instructions that map to the same SCEV. We cannot make
5845   // that guarantee for cases where I is not executed. So we need to find the
5846   // loop that I is considered in relation to and prove that I is executed for
5847   // every iteration of that loop. That implies that the value that I
5848   // calculates does not wrap anywhere in the loop, so then we can apply the
5849   // flags to the SCEV.
5850   //
5851   // We check isLoopInvariant to disambiguate in case we are adding recurrences
5852   // from different loops, so that we know which loop to prove that I is
5853   // executed in.
5854   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5855     // I could be an extractvalue from a call to an overflow intrinsic.
5856     // TODO: We can do better here in some cases.
5857     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5858       return false;
5859     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5860     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5861       bool AllOtherOpsLoopInvariant = true;
5862       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
5863            ++OtherOpIndex) {
5864         if (OtherOpIndex != OpIndex) {
5865           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
5866           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
5867             AllOtherOpsLoopInvariant = false;
5868             break;
5869           }
5870         }
5871       }
5872       if (AllOtherOpsLoopInvariant &&
5873           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
5874         return true;
5875     }
5876   }
5877   return false;
5878 }
5879 
5880 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
5881   // If we know that \c I can never be poison period, then that's enough.
5882   if (isSCEVExprNeverPoison(I))
5883     return true;
5884 
5885   // For an add recurrence specifically, we assume that infinite loops without
5886   // side effects are undefined behavior, and then reason as follows:
5887   //
5888   // If the add recurrence is poison in any iteration, it is poison on all
5889   // future iterations (since incrementing poison yields poison). If the result
5890   // of the add recurrence is fed into the loop latch condition and the loop
5891   // does not contain any throws or exiting blocks other than the latch, we now
5892   // have the ability to "choose" whether the backedge is taken or not (by
5893   // choosing a sufficiently evil value for the poison feeding into the branch)
5894   // for every iteration including and after the one in which \p I first became
5895   // poison.  There are two possibilities (let's call the iteration in which \p
5896   // I first became poison as K):
5897   //
5898   //  1. In the set of iterations including and after K, the loop body executes
5899   //     no side effects.  In this case executing the backege an infinte number
5900   //     of times will yield undefined behavior.
5901   //
5902   //  2. In the set of iterations including and after K, the loop body executes
5903   //     at least one side effect.  In this case, that specific instance of side
5904   //     effect is control dependent on poison, which also yields undefined
5905   //     behavior.
5906 
5907   auto *ExitingBB = L->getExitingBlock();
5908   auto *LatchBB = L->getLoopLatch();
5909   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
5910     return false;
5911 
5912   SmallPtrSet<const Instruction *, 16> Pushed;
5913   SmallVector<const Instruction *, 8> PoisonStack;
5914 
5915   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
5916   // things that are known to be fully poison under that assumption go on the
5917   // PoisonStack.
5918   Pushed.insert(I);
5919   PoisonStack.push_back(I);
5920 
5921   bool LatchControlDependentOnPoison = false;
5922   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
5923     const Instruction *Poison = PoisonStack.pop_back_val();
5924 
5925     for (auto *PoisonUser : Poison->users()) {
5926       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
5927         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
5928           PoisonStack.push_back(cast<Instruction>(PoisonUser));
5929       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
5930         assert(BI->isConditional() && "Only possibility!");
5931         if (BI->getParent() == LatchBB) {
5932           LatchControlDependentOnPoison = true;
5933           break;
5934         }
5935       }
5936     }
5937   }
5938 
5939   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
5940 }
5941 
5942 ScalarEvolution::LoopProperties
5943 ScalarEvolution::getLoopProperties(const Loop *L) {
5944   using LoopProperties = ScalarEvolution::LoopProperties;
5945 
5946   auto Itr = LoopPropertiesCache.find(L);
5947   if (Itr == LoopPropertiesCache.end()) {
5948     auto HasSideEffects = [](Instruction *I) {
5949       if (auto *SI = dyn_cast<StoreInst>(I))
5950         return !SI->isSimple();
5951 
5952       return I->mayHaveSideEffects();
5953     };
5954 
5955     LoopProperties LP = {/* HasNoAbnormalExits */ true,
5956                          /*HasNoSideEffects*/ true};
5957 
5958     for (auto *BB : L->getBlocks())
5959       for (auto &I : *BB) {
5960         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5961           LP.HasNoAbnormalExits = false;
5962         if (HasSideEffects(&I))
5963           LP.HasNoSideEffects = false;
5964         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
5965           break; // We're already as pessimistic as we can get.
5966       }
5967 
5968     auto InsertPair = LoopPropertiesCache.insert({L, LP});
5969     assert(InsertPair.second && "We just checked!");
5970     Itr = InsertPair.first;
5971   }
5972 
5973   return Itr->second;
5974 }
5975 
5976 const SCEV *ScalarEvolution::createSCEV(Value *V) {
5977   if (!isSCEVable(V->getType()))
5978     return getUnknown(V);
5979 
5980   if (Instruction *I = dyn_cast<Instruction>(V)) {
5981     // Don't attempt to analyze instructions in blocks that aren't
5982     // reachable. Such instructions don't matter, and they aren't required
5983     // to obey basic rules for definitions dominating uses which this
5984     // analysis depends on.
5985     if (!DT.isReachableFromEntry(I->getParent()))
5986       return getUnknown(V);
5987   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
5988     return getConstant(CI);
5989   else if (isa<ConstantPointerNull>(V))
5990     return getZero(V->getType());
5991   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
5992     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
5993   else if (!isa<ConstantExpr>(V))
5994     return getUnknown(V);
5995 
5996   Operator *U = cast<Operator>(V);
5997   if (auto BO = MatchBinaryOp(U, DT)) {
5998     switch (BO->Opcode) {
5999     case Instruction::Add: {
6000       // The simple thing to do would be to just call getSCEV on both operands
6001       // and call getAddExpr with the result. However if we're looking at a
6002       // bunch of things all added together, this can be quite inefficient,
6003       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6004       // Instead, gather up all the operands and make a single getAddExpr call.
6005       // LLVM IR canonical form means we need only traverse the left operands.
6006       SmallVector<const SCEV *, 4> AddOps;
6007       do {
6008         if (BO->Op) {
6009           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6010             AddOps.push_back(OpSCEV);
6011             break;
6012           }
6013 
6014           // If a NUW or NSW flag can be applied to the SCEV for this
6015           // addition, then compute the SCEV for this addition by itself
6016           // with a separate call to getAddExpr. We need to do that
6017           // instead of pushing the operands of the addition onto AddOps,
6018           // since the flags are only known to apply to this particular
6019           // addition - they may not apply to other additions that can be
6020           // formed with operands from AddOps.
6021           const SCEV *RHS = getSCEV(BO->RHS);
6022           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6023           if (Flags != SCEV::FlagAnyWrap) {
6024             const SCEV *LHS = getSCEV(BO->LHS);
6025             if (BO->Opcode == Instruction::Sub)
6026               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6027             else
6028               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6029             break;
6030           }
6031         }
6032 
6033         if (BO->Opcode == Instruction::Sub)
6034           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6035         else
6036           AddOps.push_back(getSCEV(BO->RHS));
6037 
6038         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6039         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6040                        NewBO->Opcode != Instruction::Sub)) {
6041           AddOps.push_back(getSCEV(BO->LHS));
6042           break;
6043         }
6044         BO = NewBO;
6045       } while (true);
6046 
6047       return getAddExpr(AddOps);
6048     }
6049 
6050     case Instruction::Mul: {
6051       SmallVector<const SCEV *, 4> MulOps;
6052       do {
6053         if (BO->Op) {
6054           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6055             MulOps.push_back(OpSCEV);
6056             break;
6057           }
6058 
6059           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6060           if (Flags != SCEV::FlagAnyWrap) {
6061             MulOps.push_back(
6062                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6063             break;
6064           }
6065         }
6066 
6067         MulOps.push_back(getSCEV(BO->RHS));
6068         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6069         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6070           MulOps.push_back(getSCEV(BO->LHS));
6071           break;
6072         }
6073         BO = NewBO;
6074       } while (true);
6075 
6076       return getMulExpr(MulOps);
6077     }
6078     case Instruction::UDiv:
6079       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6080     case Instruction::URem:
6081       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6082     case Instruction::Sub: {
6083       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6084       if (BO->Op)
6085         Flags = getNoWrapFlagsFromUB(BO->Op);
6086       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6087     }
6088     case Instruction::And:
6089       // For an expression like x&255 that merely masks off the high bits,
6090       // use zext(trunc(x)) as the SCEV expression.
6091       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6092         if (CI->isZero())
6093           return getSCEV(BO->RHS);
6094         if (CI->isMinusOne())
6095           return getSCEV(BO->LHS);
6096         const APInt &A = CI->getValue();
6097 
6098         // Instcombine's ShrinkDemandedConstant may strip bits out of
6099         // constants, obscuring what would otherwise be a low-bits mask.
6100         // Use computeKnownBits to compute what ShrinkDemandedConstant
6101         // knew about to reconstruct a low-bits mask value.
6102         unsigned LZ = A.countLeadingZeros();
6103         unsigned TZ = A.countTrailingZeros();
6104         unsigned BitWidth = A.getBitWidth();
6105         KnownBits Known(BitWidth);
6106         computeKnownBits(BO->LHS, Known, getDataLayout(),
6107                          0, &AC, nullptr, &DT);
6108 
6109         APInt EffectiveMask =
6110             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6111         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6112           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6113           const SCEV *LHS = getSCEV(BO->LHS);
6114           const SCEV *ShiftedLHS = nullptr;
6115           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6116             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6117               // For an expression like (x * 8) & 8, simplify the multiply.
6118               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6119               unsigned GCD = std::min(MulZeros, TZ);
6120               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6121               SmallVector<const SCEV*, 4> MulOps;
6122               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6123               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6124               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6125               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6126             }
6127           }
6128           if (!ShiftedLHS)
6129             ShiftedLHS = getUDivExpr(LHS, MulCount);
6130           return getMulExpr(
6131               getZeroExtendExpr(
6132                   getTruncateExpr(ShiftedLHS,
6133                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6134                   BO->LHS->getType()),
6135               MulCount);
6136         }
6137       }
6138       break;
6139 
6140     case Instruction::Or:
6141       // If the RHS of the Or is a constant, we may have something like:
6142       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6143       // optimizations will transparently handle this case.
6144       //
6145       // In order for this transformation to be safe, the LHS must be of the
6146       // form X*(2^n) and the Or constant must be less than 2^n.
6147       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6148         const SCEV *LHS = getSCEV(BO->LHS);
6149         const APInt &CIVal = CI->getValue();
6150         if (GetMinTrailingZeros(LHS) >=
6151             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6152           // Build a plain add SCEV.
6153           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6154           // If the LHS of the add was an addrec and it has no-wrap flags,
6155           // transfer the no-wrap flags, since an or won't introduce a wrap.
6156           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6157             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6158             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6159                 OldAR->getNoWrapFlags());
6160           }
6161           return S;
6162         }
6163       }
6164       break;
6165 
6166     case Instruction::Xor:
6167       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6168         // If the RHS of xor is -1, then this is a not operation.
6169         if (CI->isMinusOne())
6170           return getNotSCEV(getSCEV(BO->LHS));
6171 
6172         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6173         // This is a variant of the check for xor with -1, and it handles
6174         // the case where instcombine has trimmed non-demanded bits out
6175         // of an xor with -1.
6176         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6177           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6178             if (LBO->getOpcode() == Instruction::And &&
6179                 LCI->getValue() == CI->getValue())
6180               if (const SCEVZeroExtendExpr *Z =
6181                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6182                 Type *UTy = BO->LHS->getType();
6183                 const SCEV *Z0 = Z->getOperand();
6184                 Type *Z0Ty = Z0->getType();
6185                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6186 
6187                 // If C is a low-bits mask, the zero extend is serving to
6188                 // mask off the high bits. Complement the operand and
6189                 // re-apply the zext.
6190                 if (CI->getValue().isMask(Z0TySize))
6191                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6192 
6193                 // If C is a single bit, it may be in the sign-bit position
6194                 // before the zero-extend. In this case, represent the xor
6195                 // using an add, which is equivalent, and re-apply the zext.
6196                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6197                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6198                     Trunc.isSignMask())
6199                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6200                                            UTy);
6201               }
6202       }
6203       break;
6204 
6205   case Instruction::Shl:
6206     // Turn shift left of a constant amount into a multiply.
6207     if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6208       uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6209 
6210       // If the shift count is not less than the bitwidth, the result of
6211       // the shift is undefined. Don't try to analyze it, because the
6212       // resolution chosen here may differ from the resolution chosen in
6213       // other parts of the compiler.
6214       if (SA->getValue().uge(BitWidth))
6215         break;
6216 
6217       // It is currently not resolved how to interpret NSW for left
6218       // shift by BitWidth - 1, so we avoid applying flags in that
6219       // case. Remove this check (or this comment) once the situation
6220       // is resolved. See
6221       // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6222       // and http://reviews.llvm.org/D8890 .
6223       auto Flags = SCEV::FlagAnyWrap;
6224       if (BO->Op && SA->getValue().ult(BitWidth - 1))
6225         Flags = getNoWrapFlagsFromUB(BO->Op);
6226 
6227       Constant *X = ConstantInt::get(getContext(),
6228         APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6229       return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6230     }
6231     break;
6232 
6233     case Instruction::AShr: {
6234       // AShr X, C, where C is a constant.
6235       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6236       if (!CI)
6237         break;
6238 
6239       Type *OuterTy = BO->LHS->getType();
6240       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6241       // If the shift count is not less than the bitwidth, the result of
6242       // the shift is undefined. Don't try to analyze it, because the
6243       // resolution chosen here may differ from the resolution chosen in
6244       // other parts of the compiler.
6245       if (CI->getValue().uge(BitWidth))
6246         break;
6247 
6248       if (CI->isZero())
6249         return getSCEV(BO->LHS); // shift by zero --> noop
6250 
6251       uint64_t AShrAmt = CI->getZExtValue();
6252       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6253 
6254       Operator *L = dyn_cast<Operator>(BO->LHS);
6255       if (L && L->getOpcode() == Instruction::Shl) {
6256         // X = Shl A, n
6257         // Y = AShr X, m
6258         // Both n and m are constant.
6259 
6260         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6261         if (L->getOperand(1) == BO->RHS)
6262           // For a two-shift sext-inreg, i.e. n = m,
6263           // use sext(trunc(x)) as the SCEV expression.
6264           return getSignExtendExpr(
6265               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6266 
6267         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6268         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6269           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6270           if (ShlAmt > AShrAmt) {
6271             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6272             // expression. We already checked that ShlAmt < BitWidth, so
6273             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6274             // ShlAmt - AShrAmt < Amt.
6275             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6276                                             ShlAmt - AShrAmt);
6277             return getSignExtendExpr(
6278                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6279                 getConstant(Mul)), OuterTy);
6280           }
6281         }
6282       }
6283       break;
6284     }
6285     }
6286   }
6287 
6288   switch (U->getOpcode()) {
6289   case Instruction::Trunc:
6290     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6291 
6292   case Instruction::ZExt:
6293     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6294 
6295   case Instruction::SExt:
6296     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6297       // The NSW flag of a subtract does not always survive the conversion to
6298       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6299       // more likely to preserve NSW and allow later AddRec optimisations.
6300       //
6301       // NOTE: This is effectively duplicating this logic from getSignExtend:
6302       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6303       // but by that point the NSW information has potentially been lost.
6304       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6305         Type *Ty = U->getType();
6306         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6307         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6308         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6309       }
6310     }
6311     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6312 
6313   case Instruction::BitCast:
6314     // BitCasts are no-op casts so we just eliminate the cast.
6315     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6316       return getSCEV(U->getOperand(0));
6317     break;
6318 
6319   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6320   // lead to pointer expressions which cannot safely be expanded to GEPs,
6321   // because ScalarEvolution doesn't respect the GEP aliasing rules when
6322   // simplifying integer expressions.
6323 
6324   case Instruction::GetElementPtr:
6325     return createNodeForGEP(cast<GEPOperator>(U));
6326 
6327   case Instruction::PHI:
6328     return createNodeForPHI(cast<PHINode>(U));
6329 
6330   case Instruction::Select:
6331     // U can also be a select constant expr, which let fall through.  Since
6332     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6333     // constant expressions cannot have instructions as operands, we'd have
6334     // returned getUnknown for a select constant expressions anyway.
6335     if (isa<Instruction>(U))
6336       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6337                                       U->getOperand(1), U->getOperand(2));
6338     break;
6339 
6340   case Instruction::Call:
6341   case Instruction::Invoke:
6342     if (Value *RV = CallSite(U).getReturnedArgOperand())
6343       return getSCEV(RV);
6344     break;
6345   }
6346 
6347   return getUnknown(V);
6348 }
6349 
6350 //===----------------------------------------------------------------------===//
6351 //                   Iteration Count Computation Code
6352 //
6353 
6354 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6355   if (!ExitCount)
6356     return 0;
6357 
6358   ConstantInt *ExitConst = ExitCount->getValue();
6359 
6360   // Guard against huge trip counts.
6361   if (ExitConst->getValue().getActiveBits() > 32)
6362     return 0;
6363 
6364   // In case of integer overflow, this returns 0, which is correct.
6365   return ((unsigned)ExitConst->getZExtValue()) + 1;
6366 }
6367 
6368 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6369   if (BasicBlock *ExitingBB = L->getExitingBlock())
6370     return getSmallConstantTripCount(L, ExitingBB);
6371 
6372   // No trip count information for multiple exits.
6373   return 0;
6374 }
6375 
6376 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6377                                                     BasicBlock *ExitingBlock) {
6378   assert(ExitingBlock && "Must pass a non-null exiting block!");
6379   assert(L->isLoopExiting(ExitingBlock) &&
6380          "Exiting block must actually branch out of the loop!");
6381   const SCEVConstant *ExitCount =
6382       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6383   return getConstantTripCount(ExitCount);
6384 }
6385 
6386 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6387   const auto *MaxExitCount =
6388       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6389   return getConstantTripCount(MaxExitCount);
6390 }
6391 
6392 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6393   if (BasicBlock *ExitingBB = L->getExitingBlock())
6394     return getSmallConstantTripMultiple(L, ExitingBB);
6395 
6396   // No trip multiple information for multiple exits.
6397   return 0;
6398 }
6399 
6400 /// Returns the largest constant divisor of the trip count of this loop as a
6401 /// normal unsigned value, if possible. This means that the actual trip count is
6402 /// always a multiple of the returned value (don't forget the trip count could
6403 /// very well be zero as well!).
6404 ///
6405 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6406 /// multiple of a constant (which is also the case if the trip count is simply
6407 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6408 /// if the trip count is very large (>= 2^32).
6409 ///
6410 /// As explained in the comments for getSmallConstantTripCount, this assumes
6411 /// that control exits the loop via ExitingBlock.
6412 unsigned
6413 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6414                                               BasicBlock *ExitingBlock) {
6415   assert(ExitingBlock && "Must pass a non-null exiting block!");
6416   assert(L->isLoopExiting(ExitingBlock) &&
6417          "Exiting block must actually branch out of the loop!");
6418   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6419   if (ExitCount == getCouldNotCompute())
6420     return 1;
6421 
6422   // Get the trip count from the BE count by adding 1.
6423   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6424 
6425   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6426   if (!TC)
6427     // Attempt to factor more general cases. Returns the greatest power of
6428     // two divisor. If overflow happens, the trip count expression is still
6429     // divisible by the greatest power of 2 divisor returned.
6430     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6431 
6432   ConstantInt *Result = TC->getValue();
6433 
6434   // Guard against huge trip counts (this requires checking
6435   // for zero to handle the case where the trip count == -1 and the
6436   // addition wraps).
6437   if (!Result || Result->getValue().getActiveBits() > 32 ||
6438       Result->getValue().getActiveBits() == 0)
6439     return 1;
6440 
6441   return (unsigned)Result->getZExtValue();
6442 }
6443 
6444 /// Get the expression for the number of loop iterations for which this loop is
6445 /// guaranteed not to exit via ExitingBlock. Otherwise return
6446 /// SCEVCouldNotCompute.
6447 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6448                                           BasicBlock *ExitingBlock) {
6449   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6450 }
6451 
6452 const SCEV *
6453 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6454                                                  SCEVUnionPredicate &Preds) {
6455   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6456 }
6457 
6458 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6459   return getBackedgeTakenInfo(L).getExact(L, this);
6460 }
6461 
6462 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6463 /// known never to be less than the actual backedge taken count.
6464 const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6465   return getBackedgeTakenInfo(L).getMax(this);
6466 }
6467 
6468 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6469   return getBackedgeTakenInfo(L).isMaxOrZero(this);
6470 }
6471 
6472 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6473 static void
6474 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6475   BasicBlock *Header = L->getHeader();
6476 
6477   // Push all Loop-header PHIs onto the Worklist stack.
6478   for (PHINode &PN : Header->phis())
6479     Worklist.push_back(&PN);
6480 }
6481 
6482 const ScalarEvolution::BackedgeTakenInfo &
6483 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6484   auto &BTI = getBackedgeTakenInfo(L);
6485   if (BTI.hasFullInfo())
6486     return BTI;
6487 
6488   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6489 
6490   if (!Pair.second)
6491     return Pair.first->second;
6492 
6493   BackedgeTakenInfo Result =
6494       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6495 
6496   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6497 }
6498 
6499 const ScalarEvolution::BackedgeTakenInfo &
6500 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6501   // Initially insert an invalid entry for this loop. If the insertion
6502   // succeeds, proceed to actually compute a backedge-taken count and
6503   // update the value. The temporary CouldNotCompute value tells SCEV
6504   // code elsewhere that it shouldn't attempt to request a new
6505   // backedge-taken count, which could result in infinite recursion.
6506   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6507       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6508   if (!Pair.second)
6509     return Pair.first->second;
6510 
6511   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6512   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6513   // must be cleared in this scope.
6514   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6515 
6516   // In product build, there are no usage of statistic.
6517   (void)NumTripCountsComputed;
6518   (void)NumTripCountsNotComputed;
6519 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6520   const SCEV *BEExact = Result.getExact(L, this);
6521   if (BEExact != getCouldNotCompute()) {
6522     assert(isLoopInvariant(BEExact, L) &&
6523            isLoopInvariant(Result.getMax(this), L) &&
6524            "Computed backedge-taken count isn't loop invariant for loop!");
6525     ++NumTripCountsComputed;
6526   }
6527   else if (Result.getMax(this) == getCouldNotCompute() &&
6528            isa<PHINode>(L->getHeader()->begin())) {
6529     // Only count loops that have phi nodes as not being computable.
6530     ++NumTripCountsNotComputed;
6531   }
6532 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6533 
6534   // Now that we know more about the trip count for this loop, forget any
6535   // existing SCEV values for PHI nodes in this loop since they are only
6536   // conservative estimates made without the benefit of trip count
6537   // information. This is similar to the code in forgetLoop, except that
6538   // it handles SCEVUnknown PHI nodes specially.
6539   if (Result.hasAnyInfo()) {
6540     SmallVector<Instruction *, 16> Worklist;
6541     PushLoopPHIs(L, Worklist);
6542 
6543     SmallPtrSet<Instruction *, 8> Discovered;
6544     while (!Worklist.empty()) {
6545       Instruction *I = Worklist.pop_back_val();
6546 
6547       ValueExprMapType::iterator It =
6548         ValueExprMap.find_as(static_cast<Value *>(I));
6549       if (It != ValueExprMap.end()) {
6550         const SCEV *Old = It->second;
6551 
6552         // SCEVUnknown for a PHI either means that it has an unrecognized
6553         // structure, or it's a PHI that's in the progress of being computed
6554         // by createNodeForPHI.  In the former case, additional loop trip
6555         // count information isn't going to change anything. In the later
6556         // case, createNodeForPHI will perform the necessary updates on its
6557         // own when it gets to that point.
6558         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6559           eraseValueFromMap(It->first);
6560           forgetMemoizedResults(Old);
6561         }
6562         if (PHINode *PN = dyn_cast<PHINode>(I))
6563           ConstantEvolutionLoopExitValue.erase(PN);
6564       }
6565 
6566       // Since we don't need to invalidate anything for correctness and we're
6567       // only invalidating to make SCEV's results more precise, we get to stop
6568       // early to avoid invalidating too much.  This is especially important in
6569       // cases like:
6570       //
6571       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6572       // loop0:
6573       //   %pn0 = phi
6574       //   ...
6575       // loop1:
6576       //   %pn1 = phi
6577       //   ...
6578       //
6579       // where both loop0 and loop1's backedge taken count uses the SCEV
6580       // expression for %v.  If we don't have the early stop below then in cases
6581       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6582       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6583       // count for loop1, effectively nullifying SCEV's trip count cache.
6584       for (auto *U : I->users())
6585         if (auto *I = dyn_cast<Instruction>(U)) {
6586           auto *LoopForUser = LI.getLoopFor(I->getParent());
6587           if (LoopForUser && L->contains(LoopForUser) &&
6588               Discovered.insert(I).second)
6589             Worklist.push_back(I);
6590         }
6591     }
6592   }
6593 
6594   // Re-lookup the insert position, since the call to
6595   // computeBackedgeTakenCount above could result in a
6596   // recusive call to getBackedgeTakenInfo (on a different
6597   // loop), which would invalidate the iterator computed
6598   // earlier.
6599   return BackedgeTakenCounts.find(L)->second = std::move(Result);
6600 }
6601 
6602 void ScalarEvolution::forgetLoop(const Loop *L) {
6603   // Drop any stored trip count value.
6604   auto RemoveLoopFromBackedgeMap =
6605       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6606         auto BTCPos = Map.find(L);
6607         if (BTCPos != Map.end()) {
6608           BTCPos->second.clear();
6609           Map.erase(BTCPos);
6610         }
6611       };
6612 
6613   SmallVector<const Loop *, 16> LoopWorklist(1, L);
6614   SmallVector<Instruction *, 32> Worklist;
6615   SmallPtrSet<Instruction *, 16> Visited;
6616 
6617   // Iterate over all the loops and sub-loops to drop SCEV information.
6618   while (!LoopWorklist.empty()) {
6619     auto *CurrL = LoopWorklist.pop_back_val();
6620 
6621     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6622     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6623 
6624     // Drop information about predicated SCEV rewrites for this loop.
6625     for (auto I = PredicatedSCEVRewrites.begin();
6626          I != PredicatedSCEVRewrites.end();) {
6627       std::pair<const SCEV *, const Loop *> Entry = I->first;
6628       if (Entry.second == CurrL)
6629         PredicatedSCEVRewrites.erase(I++);
6630       else
6631         ++I;
6632     }
6633 
6634     auto LoopUsersItr = LoopUsers.find(CurrL);
6635     if (LoopUsersItr != LoopUsers.end()) {
6636       for (auto *S : LoopUsersItr->second)
6637         forgetMemoizedResults(S);
6638       LoopUsers.erase(LoopUsersItr);
6639     }
6640 
6641     // Drop information about expressions based on loop-header PHIs.
6642     PushLoopPHIs(CurrL, Worklist);
6643 
6644     while (!Worklist.empty()) {
6645       Instruction *I = Worklist.pop_back_val();
6646       if (!Visited.insert(I).second)
6647         continue;
6648 
6649       ValueExprMapType::iterator It =
6650           ValueExprMap.find_as(static_cast<Value *>(I));
6651       if (It != ValueExprMap.end()) {
6652         eraseValueFromMap(It->first);
6653         forgetMemoizedResults(It->second);
6654         if (PHINode *PN = dyn_cast<PHINode>(I))
6655           ConstantEvolutionLoopExitValue.erase(PN);
6656       }
6657 
6658       PushDefUseChildren(I, Worklist);
6659     }
6660 
6661     LoopPropertiesCache.erase(CurrL);
6662     // Forget all contained loops too, to avoid dangling entries in the
6663     // ValuesAtScopes map.
6664     LoopWorklist.append(CurrL->begin(), CurrL->end());
6665   }
6666 }
6667 
6668 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6669   while (Loop *Parent = L->getParentLoop())
6670     L = Parent;
6671   forgetLoop(L);
6672 }
6673 
6674 void ScalarEvolution::forgetValue(Value *V) {
6675   Instruction *I = dyn_cast<Instruction>(V);
6676   if (!I) return;
6677 
6678   // Drop information about expressions based on loop-header PHIs.
6679   SmallVector<Instruction *, 16> Worklist;
6680   Worklist.push_back(I);
6681 
6682   SmallPtrSet<Instruction *, 8> Visited;
6683   while (!Worklist.empty()) {
6684     I = Worklist.pop_back_val();
6685     if (!Visited.insert(I).second)
6686       continue;
6687 
6688     ValueExprMapType::iterator It =
6689       ValueExprMap.find_as(static_cast<Value *>(I));
6690     if (It != ValueExprMap.end()) {
6691       eraseValueFromMap(It->first);
6692       forgetMemoizedResults(It->second);
6693       if (PHINode *PN = dyn_cast<PHINode>(I))
6694         ConstantEvolutionLoopExitValue.erase(PN);
6695     }
6696 
6697     PushDefUseChildren(I, Worklist);
6698   }
6699 }
6700 
6701 /// Get the exact loop backedge taken count considering all loop exits. A
6702 /// computable result can only be returned for loops with all exiting blocks
6703 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6704 /// is never skipped. This is a valid assumption as long as the loop exits via
6705 /// that test. For precise results, it is the caller's responsibility to specify
6706 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6707 const SCEV *
6708 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6709                                              SCEVUnionPredicate *Preds) const {
6710   // If any exits were not computable, the loop is not computable.
6711   if (!isComplete() || ExitNotTaken.empty())
6712     return SE->getCouldNotCompute();
6713 
6714   const BasicBlock *Latch = L->getLoopLatch();
6715   // All exiting blocks we have collected must dominate the only backedge.
6716   if (!Latch)
6717     return SE->getCouldNotCompute();
6718 
6719   // All exiting blocks we have gathered dominate loop's latch, so exact trip
6720   // count is simply a minimum out of all these calculated exit counts.
6721   SmallVector<const SCEV *, 2> Ops;
6722   for (auto &ENT : ExitNotTaken) {
6723     const SCEV *BECount = ENT.ExactNotTaken;
6724     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6725     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6726            "We should only have known counts for exiting blocks that dominate "
6727            "latch!");
6728 
6729     Ops.push_back(BECount);
6730 
6731     if (Preds && !ENT.hasAlwaysTruePredicate())
6732       Preds->add(ENT.Predicate.get());
6733 
6734     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6735            "Predicate should be always true!");
6736   }
6737 
6738   return SE->getUMinFromMismatchedTypes(Ops);
6739 }
6740 
6741 /// Get the exact not taken count for this loop exit.
6742 const SCEV *
6743 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6744                                              ScalarEvolution *SE) const {
6745   for (auto &ENT : ExitNotTaken)
6746     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6747       return ENT.ExactNotTaken;
6748 
6749   return SE->getCouldNotCompute();
6750 }
6751 
6752 /// getMax - Get the max backedge taken count for the loop.
6753 const SCEV *
6754 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6755   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6756     return !ENT.hasAlwaysTruePredicate();
6757   };
6758 
6759   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6760     return SE->getCouldNotCompute();
6761 
6762   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6763          "No point in having a non-constant max backedge taken count!");
6764   return getMax();
6765 }
6766 
6767 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6768   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6769     return !ENT.hasAlwaysTruePredicate();
6770   };
6771   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6772 }
6773 
6774 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6775                                                     ScalarEvolution *SE) const {
6776   if (getMax() && getMax() != SE->getCouldNotCompute() &&
6777       SE->hasOperand(getMax(), S))
6778     return true;
6779 
6780   for (auto &ENT : ExitNotTaken)
6781     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6782         SE->hasOperand(ENT.ExactNotTaken, S))
6783       return true;
6784 
6785   return false;
6786 }
6787 
6788 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6789     : ExactNotTaken(E), MaxNotTaken(E) {
6790   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6791           isa<SCEVConstant>(MaxNotTaken)) &&
6792          "No point in having a non-constant max backedge taken count!");
6793 }
6794 
6795 ScalarEvolution::ExitLimit::ExitLimit(
6796     const SCEV *E, const SCEV *M, bool MaxOrZero,
6797     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6798     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6799   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6800           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6801          "Exact is not allowed to be less precise than Max");
6802   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6803           isa<SCEVConstant>(MaxNotTaken)) &&
6804          "No point in having a non-constant max backedge taken count!");
6805   for (auto *PredSet : PredSetList)
6806     for (auto *P : *PredSet)
6807       addPredicate(P);
6808 }
6809 
6810 ScalarEvolution::ExitLimit::ExitLimit(
6811     const SCEV *E, const SCEV *M, bool MaxOrZero,
6812     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6813     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6814   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6815           isa<SCEVConstant>(MaxNotTaken)) &&
6816          "No point in having a non-constant max backedge taken count!");
6817 }
6818 
6819 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6820                                       bool MaxOrZero)
6821     : ExitLimit(E, M, MaxOrZero, None) {
6822   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6823           isa<SCEVConstant>(MaxNotTaken)) &&
6824          "No point in having a non-constant max backedge taken count!");
6825 }
6826 
6827 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6828 /// computable exit into a persistent ExitNotTakenInfo array.
6829 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6830     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6831         &&ExitCounts,
6832     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6833     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6834   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6835 
6836   ExitNotTaken.reserve(ExitCounts.size());
6837   std::transform(
6838       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6839       [&](const EdgeExitInfo &EEI) {
6840         BasicBlock *ExitBB = EEI.first;
6841         const ExitLimit &EL = EEI.second;
6842         if (EL.Predicates.empty())
6843           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6844 
6845         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6846         for (auto *Pred : EL.Predicates)
6847           Predicate->add(Pred);
6848 
6849         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6850       });
6851   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6852          "No point in having a non-constant max backedge taken count!");
6853 }
6854 
6855 /// Invalidate this result and free the ExitNotTakenInfo array.
6856 void ScalarEvolution::BackedgeTakenInfo::clear() {
6857   ExitNotTaken.clear();
6858 }
6859 
6860 /// Compute the number of times the backedge of the specified loop will execute.
6861 ScalarEvolution::BackedgeTakenInfo
6862 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
6863                                            bool AllowPredicates) {
6864   SmallVector<BasicBlock *, 8> ExitingBlocks;
6865   L->getExitingBlocks(ExitingBlocks);
6866 
6867   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6868 
6869   SmallVector<EdgeExitInfo, 4> ExitCounts;
6870   bool CouldComputeBECount = true;
6871   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
6872   const SCEV *MustExitMaxBECount = nullptr;
6873   const SCEV *MayExitMaxBECount = nullptr;
6874   bool MustExitMaxOrZero = false;
6875 
6876   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
6877   // and compute maxBECount.
6878   // Do a union of all the predicates here.
6879   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
6880     BasicBlock *ExitBB = ExitingBlocks[i];
6881     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
6882 
6883     assert((AllowPredicates || EL.Predicates.empty()) &&
6884            "Predicated exit limit when predicates are not allowed!");
6885 
6886     // 1. For each exit that can be computed, add an entry to ExitCounts.
6887     // CouldComputeBECount is true only if all exits can be computed.
6888     if (EL.ExactNotTaken == getCouldNotCompute())
6889       // We couldn't compute an exact value for this exit, so
6890       // we won't be able to compute an exact value for the loop.
6891       CouldComputeBECount = false;
6892     else
6893       ExitCounts.emplace_back(ExitBB, EL);
6894 
6895     // 2. Derive the loop's MaxBECount from each exit's max number of
6896     // non-exiting iterations. Partition the loop exits into two kinds:
6897     // LoopMustExits and LoopMayExits.
6898     //
6899     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
6900     // is a LoopMayExit.  If any computable LoopMustExit is found, then
6901     // MaxBECount is the minimum EL.MaxNotTaken of computable
6902     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
6903     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
6904     // computable EL.MaxNotTaken.
6905     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
6906         DT.dominates(ExitBB, Latch)) {
6907       if (!MustExitMaxBECount) {
6908         MustExitMaxBECount = EL.MaxNotTaken;
6909         MustExitMaxOrZero = EL.MaxOrZero;
6910       } else {
6911         MustExitMaxBECount =
6912             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
6913       }
6914     } else if (MayExitMaxBECount != getCouldNotCompute()) {
6915       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
6916         MayExitMaxBECount = EL.MaxNotTaken;
6917       else {
6918         MayExitMaxBECount =
6919             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
6920       }
6921     }
6922   }
6923   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
6924     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
6925   // The loop backedge will be taken the maximum or zero times if there's
6926   // a single exit that must be taken the maximum or zero times.
6927   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
6928   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
6929                            MaxBECount, MaxOrZero);
6930 }
6931 
6932 ScalarEvolution::ExitLimit
6933 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
6934                                       bool AllowPredicates) {
6935   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
6936   // If our exiting block does not dominate the latch, then its connection with
6937   // loop's exit limit may be far from trivial.
6938   const BasicBlock *Latch = L->getLoopLatch();
6939   if (!Latch || !DT.dominates(ExitingBlock, Latch))
6940     return getCouldNotCompute();
6941 
6942   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
6943   TerminatorInst *Term = ExitingBlock->getTerminator();
6944   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
6945     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
6946     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
6947     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
6948            "It should have one successor in loop and one exit block!");
6949     // Proceed to the next level to examine the exit condition expression.
6950     return computeExitLimitFromCond(
6951         L, BI->getCondition(), ExitIfTrue,
6952         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
6953   }
6954 
6955   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
6956     // For switch, make sure that there is a single exit from the loop.
6957     BasicBlock *Exit = nullptr;
6958     for (auto *SBB : successors(ExitingBlock))
6959       if (!L->contains(SBB)) {
6960         if (Exit) // Multiple exit successors.
6961           return getCouldNotCompute();
6962         Exit = SBB;
6963       }
6964     assert(Exit && "Exiting block must have at least one exit");
6965     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
6966                                                 /*ControlsExit=*/IsOnlyExit);
6967   }
6968 
6969   return getCouldNotCompute();
6970 }
6971 
6972 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
6973     const Loop *L, Value *ExitCond, bool ExitIfTrue,
6974     bool ControlsExit, bool AllowPredicates) {
6975   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
6976   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
6977                                         ControlsExit, AllowPredicates);
6978 }
6979 
6980 Optional<ScalarEvolution::ExitLimit>
6981 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
6982                                       bool ExitIfTrue, bool ControlsExit,
6983                                       bool AllowPredicates) {
6984   (void)this->L;
6985   (void)this->ExitIfTrue;
6986   (void)this->AllowPredicates;
6987 
6988   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
6989          this->AllowPredicates == AllowPredicates &&
6990          "Variance in assumed invariant key components!");
6991   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
6992   if (Itr == TripCountMap.end())
6993     return None;
6994   return Itr->second;
6995 }
6996 
6997 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
6998                                              bool ExitIfTrue,
6999                                              bool ControlsExit,
7000                                              bool AllowPredicates,
7001                                              const ExitLimit &EL) {
7002   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7003          this->AllowPredicates == AllowPredicates &&
7004          "Variance in assumed invariant key components!");
7005 
7006   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7007   assert(InsertResult.second && "Expected successful insertion!");
7008   (void)InsertResult;
7009   (void)ExitIfTrue;
7010 }
7011 
7012 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7013     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7014     bool ControlsExit, bool AllowPredicates) {
7015 
7016   if (auto MaybeEL =
7017           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7018     return *MaybeEL;
7019 
7020   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7021                                               ControlsExit, AllowPredicates);
7022   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7023   return EL;
7024 }
7025 
7026 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7027     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7028     bool ControlsExit, bool AllowPredicates) {
7029   // Check if the controlling expression for this loop is an And or Or.
7030   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7031     if (BO->getOpcode() == Instruction::And) {
7032       // Recurse on the operands of the and.
7033       bool EitherMayExit = !ExitIfTrue;
7034       ExitLimit EL0 = computeExitLimitFromCondCached(
7035           Cache, L, BO->getOperand(0), ExitIfTrue,
7036           ControlsExit && !EitherMayExit, AllowPredicates);
7037       ExitLimit EL1 = computeExitLimitFromCondCached(
7038           Cache, L, BO->getOperand(1), ExitIfTrue,
7039           ControlsExit && !EitherMayExit, AllowPredicates);
7040       const SCEV *BECount = getCouldNotCompute();
7041       const SCEV *MaxBECount = getCouldNotCompute();
7042       if (EitherMayExit) {
7043         // Both conditions must be true for the loop to continue executing.
7044         // Choose the less conservative count.
7045         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7046             EL1.ExactNotTaken == getCouldNotCompute())
7047           BECount = getCouldNotCompute();
7048         else
7049           BECount =
7050               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7051         if (EL0.MaxNotTaken == getCouldNotCompute())
7052           MaxBECount = EL1.MaxNotTaken;
7053         else if (EL1.MaxNotTaken == getCouldNotCompute())
7054           MaxBECount = EL0.MaxNotTaken;
7055         else
7056           MaxBECount =
7057               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7058       } else {
7059         // Both conditions must be true at the same time for the loop to exit.
7060         // For now, be conservative.
7061         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7062           MaxBECount = EL0.MaxNotTaken;
7063         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7064           BECount = EL0.ExactNotTaken;
7065       }
7066 
7067       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7068       // to be more aggressive when computing BECount than when computing
7069       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7070       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7071       // to not.
7072       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7073           !isa<SCEVCouldNotCompute>(BECount))
7074         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7075 
7076       return ExitLimit(BECount, MaxBECount, false,
7077                        {&EL0.Predicates, &EL1.Predicates});
7078     }
7079     if (BO->getOpcode() == Instruction::Or) {
7080       // Recurse on the operands of the or.
7081       bool EitherMayExit = ExitIfTrue;
7082       ExitLimit EL0 = computeExitLimitFromCondCached(
7083           Cache, L, BO->getOperand(0), ExitIfTrue,
7084           ControlsExit && !EitherMayExit, AllowPredicates);
7085       ExitLimit EL1 = computeExitLimitFromCondCached(
7086           Cache, L, BO->getOperand(1), ExitIfTrue,
7087           ControlsExit && !EitherMayExit, AllowPredicates);
7088       const SCEV *BECount = getCouldNotCompute();
7089       const SCEV *MaxBECount = getCouldNotCompute();
7090       if (EitherMayExit) {
7091         // Both conditions must be false for the loop to continue executing.
7092         // Choose the less conservative count.
7093         if (EL0.ExactNotTaken == getCouldNotCompute() ||
7094             EL1.ExactNotTaken == getCouldNotCompute())
7095           BECount = getCouldNotCompute();
7096         else
7097           BECount =
7098               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7099         if (EL0.MaxNotTaken == getCouldNotCompute())
7100           MaxBECount = EL1.MaxNotTaken;
7101         else if (EL1.MaxNotTaken == getCouldNotCompute())
7102           MaxBECount = EL0.MaxNotTaken;
7103         else
7104           MaxBECount =
7105               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7106       } else {
7107         // Both conditions must be false at the same time for the loop to exit.
7108         // For now, be conservative.
7109         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7110           MaxBECount = EL0.MaxNotTaken;
7111         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7112           BECount = EL0.ExactNotTaken;
7113       }
7114 
7115       return ExitLimit(BECount, MaxBECount, false,
7116                        {&EL0.Predicates, &EL1.Predicates});
7117     }
7118   }
7119 
7120   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7121   // Proceed to the next level to examine the icmp.
7122   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7123     ExitLimit EL =
7124         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7125     if (EL.hasFullInfo() || !AllowPredicates)
7126       return EL;
7127 
7128     // Try again, but use SCEV predicates this time.
7129     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7130                                     /*AllowPredicates=*/true);
7131   }
7132 
7133   // Check for a constant condition. These are normally stripped out by
7134   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7135   // preserve the CFG and is temporarily leaving constant conditions
7136   // in place.
7137   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7138     if (ExitIfTrue == !CI->getZExtValue())
7139       // The backedge is always taken.
7140       return getCouldNotCompute();
7141     else
7142       // The backedge is never taken.
7143       return getZero(CI->getType());
7144   }
7145 
7146   // If it's not an integer or pointer comparison then compute it the hard way.
7147   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7148 }
7149 
7150 ScalarEvolution::ExitLimit
7151 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7152                                           ICmpInst *ExitCond,
7153                                           bool ExitIfTrue,
7154                                           bool ControlsExit,
7155                                           bool AllowPredicates) {
7156   // If the condition was exit on true, convert the condition to exit on false
7157   ICmpInst::Predicate Pred;
7158   if (!ExitIfTrue)
7159     Pred = ExitCond->getPredicate();
7160   else
7161     Pred = ExitCond->getInversePredicate();
7162   const ICmpInst::Predicate OriginalPred = Pred;
7163 
7164   // Handle common loops like: for (X = "string"; *X; ++X)
7165   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7166     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7167       ExitLimit ItCnt =
7168         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7169       if (ItCnt.hasAnyInfo())
7170         return ItCnt;
7171     }
7172 
7173   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7174   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7175 
7176   // Try to evaluate any dependencies out of the loop.
7177   LHS = getSCEVAtScope(LHS, L);
7178   RHS = getSCEVAtScope(RHS, L);
7179 
7180   // At this point, we would like to compute how many iterations of the
7181   // loop the predicate will return true for these inputs.
7182   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7183     // If there is a loop-invariant, force it into the RHS.
7184     std::swap(LHS, RHS);
7185     Pred = ICmpInst::getSwappedPredicate(Pred);
7186   }
7187 
7188   // Simplify the operands before analyzing them.
7189   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7190 
7191   // If we have a comparison of a chrec against a constant, try to use value
7192   // ranges to answer this query.
7193   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7194     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7195       if (AddRec->getLoop() == L) {
7196         // Form the constant range.
7197         ConstantRange CompRange =
7198             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7199 
7200         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7201         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7202       }
7203 
7204   switch (Pred) {
7205   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7206     // Convert to: while (X-Y != 0)
7207     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7208                                 AllowPredicates);
7209     if (EL.hasAnyInfo()) return EL;
7210     break;
7211   }
7212   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7213     // Convert to: while (X-Y == 0)
7214     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7215     if (EL.hasAnyInfo()) return EL;
7216     break;
7217   }
7218   case ICmpInst::ICMP_SLT:
7219   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7220     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7221     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7222                                     AllowPredicates);
7223     if (EL.hasAnyInfo()) return EL;
7224     break;
7225   }
7226   case ICmpInst::ICMP_SGT:
7227   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7228     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7229     ExitLimit EL =
7230         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7231                             AllowPredicates);
7232     if (EL.hasAnyInfo()) return EL;
7233     break;
7234   }
7235   default:
7236     break;
7237   }
7238 
7239   auto *ExhaustiveCount =
7240       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7241 
7242   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7243     return ExhaustiveCount;
7244 
7245   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7246                                       ExitCond->getOperand(1), L, OriginalPred);
7247 }
7248 
7249 ScalarEvolution::ExitLimit
7250 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7251                                                       SwitchInst *Switch,
7252                                                       BasicBlock *ExitingBlock,
7253                                                       bool ControlsExit) {
7254   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7255 
7256   // Give up if the exit is the default dest of a switch.
7257   if (Switch->getDefaultDest() == ExitingBlock)
7258     return getCouldNotCompute();
7259 
7260   assert(L->contains(Switch->getDefaultDest()) &&
7261          "Default case must not exit the loop!");
7262   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7263   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7264 
7265   // while (X != Y) --> while (X-Y != 0)
7266   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7267   if (EL.hasAnyInfo())
7268     return EL;
7269 
7270   return getCouldNotCompute();
7271 }
7272 
7273 static ConstantInt *
7274 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7275                                 ScalarEvolution &SE) {
7276   const SCEV *InVal = SE.getConstant(C);
7277   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7278   assert(isa<SCEVConstant>(Val) &&
7279          "Evaluation of SCEV at constant didn't fold correctly?");
7280   return cast<SCEVConstant>(Val)->getValue();
7281 }
7282 
7283 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7284 /// compute the backedge execution count.
7285 ScalarEvolution::ExitLimit
7286 ScalarEvolution::computeLoadConstantCompareExitLimit(
7287   LoadInst *LI,
7288   Constant *RHS,
7289   const Loop *L,
7290   ICmpInst::Predicate predicate) {
7291   if (LI->isVolatile()) return getCouldNotCompute();
7292 
7293   // Check to see if the loaded pointer is a getelementptr of a global.
7294   // TODO: Use SCEV instead of manually grubbing with GEPs.
7295   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7296   if (!GEP) return getCouldNotCompute();
7297 
7298   // Make sure that it is really a constant global we are gepping, with an
7299   // initializer, and make sure the first IDX is really 0.
7300   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7301   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7302       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7303       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7304     return getCouldNotCompute();
7305 
7306   // Okay, we allow one non-constant index into the GEP instruction.
7307   Value *VarIdx = nullptr;
7308   std::vector<Constant*> Indexes;
7309   unsigned VarIdxNum = 0;
7310   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7311     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7312       Indexes.push_back(CI);
7313     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7314       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7315       VarIdx = GEP->getOperand(i);
7316       VarIdxNum = i-2;
7317       Indexes.push_back(nullptr);
7318     }
7319 
7320   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7321   if (!VarIdx)
7322     return getCouldNotCompute();
7323 
7324   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7325   // Check to see if X is a loop variant variable value now.
7326   const SCEV *Idx = getSCEV(VarIdx);
7327   Idx = getSCEVAtScope(Idx, L);
7328 
7329   // We can only recognize very limited forms of loop index expressions, in
7330   // particular, only affine AddRec's like {C1,+,C2}.
7331   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7332   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7333       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7334       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7335     return getCouldNotCompute();
7336 
7337   unsigned MaxSteps = MaxBruteForceIterations;
7338   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7339     ConstantInt *ItCst = ConstantInt::get(
7340                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7341     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7342 
7343     // Form the GEP offset.
7344     Indexes[VarIdxNum] = Val;
7345 
7346     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7347                                                          Indexes);
7348     if (!Result) break;  // Cannot compute!
7349 
7350     // Evaluate the condition for this iteration.
7351     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7352     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7353     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7354       ++NumArrayLenItCounts;
7355       return getConstant(ItCst);   // Found terminating iteration!
7356     }
7357   }
7358   return getCouldNotCompute();
7359 }
7360 
7361 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7362     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7363   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7364   if (!RHS)
7365     return getCouldNotCompute();
7366 
7367   const BasicBlock *Latch = L->getLoopLatch();
7368   if (!Latch)
7369     return getCouldNotCompute();
7370 
7371   const BasicBlock *Predecessor = L->getLoopPredecessor();
7372   if (!Predecessor)
7373     return getCouldNotCompute();
7374 
7375   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7376   // Return LHS in OutLHS and shift_opt in OutOpCode.
7377   auto MatchPositiveShift =
7378       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7379 
7380     using namespace PatternMatch;
7381 
7382     ConstantInt *ShiftAmt;
7383     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7384       OutOpCode = Instruction::LShr;
7385     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7386       OutOpCode = Instruction::AShr;
7387     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7388       OutOpCode = Instruction::Shl;
7389     else
7390       return false;
7391 
7392     return ShiftAmt->getValue().isStrictlyPositive();
7393   };
7394 
7395   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7396   //
7397   // loop:
7398   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7399   //   %iv.shifted = lshr i32 %iv, <positive constant>
7400   //
7401   // Return true on a successful match.  Return the corresponding PHI node (%iv
7402   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7403   auto MatchShiftRecurrence =
7404       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7405     Optional<Instruction::BinaryOps> PostShiftOpCode;
7406 
7407     {
7408       Instruction::BinaryOps OpC;
7409       Value *V;
7410 
7411       // If we encounter a shift instruction, "peel off" the shift operation,
7412       // and remember that we did so.  Later when we inspect %iv's backedge
7413       // value, we will make sure that the backedge value uses the same
7414       // operation.
7415       //
7416       // Note: the peeled shift operation does not have to be the same
7417       // instruction as the one feeding into the PHI's backedge value.  We only
7418       // really care about it being the same *kind* of shift instruction --
7419       // that's all that is required for our later inferences to hold.
7420       if (MatchPositiveShift(LHS, V, OpC)) {
7421         PostShiftOpCode = OpC;
7422         LHS = V;
7423       }
7424     }
7425 
7426     PNOut = dyn_cast<PHINode>(LHS);
7427     if (!PNOut || PNOut->getParent() != L->getHeader())
7428       return false;
7429 
7430     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7431     Value *OpLHS;
7432 
7433     return
7434         // The backedge value for the PHI node must be a shift by a positive
7435         // amount
7436         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7437 
7438         // of the PHI node itself
7439         OpLHS == PNOut &&
7440 
7441         // and the kind of shift should be match the kind of shift we peeled
7442         // off, if any.
7443         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7444   };
7445 
7446   PHINode *PN;
7447   Instruction::BinaryOps OpCode;
7448   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7449     return getCouldNotCompute();
7450 
7451   const DataLayout &DL = getDataLayout();
7452 
7453   // The key rationale for this optimization is that for some kinds of shift
7454   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7455   // within a finite number of iterations.  If the condition guarding the
7456   // backedge (in the sense that the backedge is taken if the condition is true)
7457   // is false for the value the shift recurrence stabilizes to, then we know
7458   // that the backedge is taken only a finite number of times.
7459 
7460   ConstantInt *StableValue = nullptr;
7461   switch (OpCode) {
7462   default:
7463     llvm_unreachable("Impossible case!");
7464 
7465   case Instruction::AShr: {
7466     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7467     // bitwidth(K) iterations.
7468     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7469     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7470                                        Predecessor->getTerminator(), &DT);
7471     auto *Ty = cast<IntegerType>(RHS->getType());
7472     if (Known.isNonNegative())
7473       StableValue = ConstantInt::get(Ty, 0);
7474     else if (Known.isNegative())
7475       StableValue = ConstantInt::get(Ty, -1, true);
7476     else
7477       return getCouldNotCompute();
7478 
7479     break;
7480   }
7481   case Instruction::LShr:
7482   case Instruction::Shl:
7483     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7484     // stabilize to 0 in at most bitwidth(K) iterations.
7485     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7486     break;
7487   }
7488 
7489   auto *Result =
7490       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7491   assert(Result->getType()->isIntegerTy(1) &&
7492          "Otherwise cannot be an operand to a branch instruction");
7493 
7494   if (Result->isZeroValue()) {
7495     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7496     const SCEV *UpperBound =
7497         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7498     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7499   }
7500 
7501   return getCouldNotCompute();
7502 }
7503 
7504 /// Return true if we can constant fold an instruction of the specified type,
7505 /// assuming that all operands were constants.
7506 static bool CanConstantFold(const Instruction *I) {
7507   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7508       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7509       isa<LoadInst>(I))
7510     return true;
7511 
7512   if (const CallInst *CI = dyn_cast<CallInst>(I))
7513     if (const Function *F = CI->getCalledFunction())
7514       return canConstantFoldCallTo(CI, F);
7515   return false;
7516 }
7517 
7518 /// Determine whether this instruction can constant evolve within this loop
7519 /// assuming its operands can all constant evolve.
7520 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7521   // An instruction outside of the loop can't be derived from a loop PHI.
7522   if (!L->contains(I)) return false;
7523 
7524   if (isa<PHINode>(I)) {
7525     // We don't currently keep track of the control flow needed to evaluate
7526     // PHIs, so we cannot handle PHIs inside of loops.
7527     return L->getHeader() == I->getParent();
7528   }
7529 
7530   // If we won't be able to constant fold this expression even if the operands
7531   // are constants, bail early.
7532   return CanConstantFold(I);
7533 }
7534 
7535 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7536 /// recursing through each instruction operand until reaching a loop header phi.
7537 static PHINode *
7538 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7539                                DenseMap<Instruction *, PHINode *> &PHIMap,
7540                                unsigned Depth) {
7541   if (Depth > MaxConstantEvolvingDepth)
7542     return nullptr;
7543 
7544   // Otherwise, we can evaluate this instruction if all of its operands are
7545   // constant or derived from a PHI node themselves.
7546   PHINode *PHI = nullptr;
7547   for (Value *Op : UseInst->operands()) {
7548     if (isa<Constant>(Op)) continue;
7549 
7550     Instruction *OpInst = dyn_cast<Instruction>(Op);
7551     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7552 
7553     PHINode *P = dyn_cast<PHINode>(OpInst);
7554     if (!P)
7555       // If this operand is already visited, reuse the prior result.
7556       // We may have P != PHI if this is the deepest point at which the
7557       // inconsistent paths meet.
7558       P = PHIMap.lookup(OpInst);
7559     if (!P) {
7560       // Recurse and memoize the results, whether a phi is found or not.
7561       // This recursive call invalidates pointers into PHIMap.
7562       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7563       PHIMap[OpInst] = P;
7564     }
7565     if (!P)
7566       return nullptr;  // Not evolving from PHI
7567     if (PHI && PHI != P)
7568       return nullptr;  // Evolving from multiple different PHIs.
7569     PHI = P;
7570   }
7571   // This is a expression evolving from a constant PHI!
7572   return PHI;
7573 }
7574 
7575 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7576 /// in the loop that V is derived from.  We allow arbitrary operations along the
7577 /// way, but the operands of an operation must either be constants or a value
7578 /// derived from a constant PHI.  If this expression does not fit with these
7579 /// constraints, return null.
7580 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7581   Instruction *I = dyn_cast<Instruction>(V);
7582   if (!I || !canConstantEvolve(I, L)) return nullptr;
7583 
7584   if (PHINode *PN = dyn_cast<PHINode>(I))
7585     return PN;
7586 
7587   // Record non-constant instructions contained by the loop.
7588   DenseMap<Instruction *, PHINode *> PHIMap;
7589   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7590 }
7591 
7592 /// EvaluateExpression - Given an expression that passes the
7593 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7594 /// in the loop has the value PHIVal.  If we can't fold this expression for some
7595 /// reason, return null.
7596 static Constant *EvaluateExpression(Value *V, const Loop *L,
7597                                     DenseMap<Instruction *, Constant *> &Vals,
7598                                     const DataLayout &DL,
7599                                     const TargetLibraryInfo *TLI) {
7600   // Convenient constant check, but redundant for recursive calls.
7601   if (Constant *C = dyn_cast<Constant>(V)) return C;
7602   Instruction *I = dyn_cast<Instruction>(V);
7603   if (!I) return nullptr;
7604 
7605   if (Constant *C = Vals.lookup(I)) return C;
7606 
7607   // An instruction inside the loop depends on a value outside the loop that we
7608   // weren't given a mapping for, or a value such as a call inside the loop.
7609   if (!canConstantEvolve(I, L)) return nullptr;
7610 
7611   // An unmapped PHI can be due to a branch or another loop inside this loop,
7612   // or due to this not being the initial iteration through a loop where we
7613   // couldn't compute the evolution of this particular PHI last time.
7614   if (isa<PHINode>(I)) return nullptr;
7615 
7616   std::vector<Constant*> Operands(I->getNumOperands());
7617 
7618   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7619     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7620     if (!Operand) {
7621       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7622       if (!Operands[i]) return nullptr;
7623       continue;
7624     }
7625     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7626     Vals[Operand] = C;
7627     if (!C) return nullptr;
7628     Operands[i] = C;
7629   }
7630 
7631   if (CmpInst *CI = dyn_cast<CmpInst>(I))
7632     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7633                                            Operands[1], DL, TLI);
7634   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7635     if (!LI->isVolatile())
7636       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7637   }
7638   return ConstantFoldInstOperands(I, Operands, DL, TLI);
7639 }
7640 
7641 
7642 // If every incoming value to PN except the one for BB is a specific Constant,
7643 // return that, else return nullptr.
7644 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7645   Constant *IncomingVal = nullptr;
7646 
7647   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7648     if (PN->getIncomingBlock(i) == BB)
7649       continue;
7650 
7651     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7652     if (!CurrentVal)
7653       return nullptr;
7654 
7655     if (IncomingVal != CurrentVal) {
7656       if (IncomingVal)
7657         return nullptr;
7658       IncomingVal = CurrentVal;
7659     }
7660   }
7661 
7662   return IncomingVal;
7663 }
7664 
7665 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7666 /// in the header of its containing loop, we know the loop executes a
7667 /// constant number of times, and the PHI node is just a recurrence
7668 /// involving constants, fold it.
7669 Constant *
7670 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7671                                                    const APInt &BEs,
7672                                                    const Loop *L) {
7673   auto I = ConstantEvolutionLoopExitValue.find(PN);
7674   if (I != ConstantEvolutionLoopExitValue.end())
7675     return I->second;
7676 
7677   if (BEs.ugt(MaxBruteForceIterations))
7678     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
7679 
7680   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7681 
7682   DenseMap<Instruction *, Constant *> CurrentIterVals;
7683   BasicBlock *Header = L->getHeader();
7684   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7685 
7686   BasicBlock *Latch = L->getLoopLatch();
7687   if (!Latch)
7688     return nullptr;
7689 
7690   for (PHINode &PHI : Header->phis()) {
7691     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7692       CurrentIterVals[&PHI] = StartCST;
7693   }
7694   if (!CurrentIterVals.count(PN))
7695     return RetVal = nullptr;
7696 
7697   Value *BEValue = PN->getIncomingValueForBlock(Latch);
7698 
7699   // Execute the loop symbolically to determine the exit value.
7700   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7701          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7702 
7703   unsigned NumIterations = BEs.getZExtValue(); // must be in range
7704   unsigned IterationNum = 0;
7705   const DataLayout &DL = getDataLayout();
7706   for (; ; ++IterationNum) {
7707     if (IterationNum == NumIterations)
7708       return RetVal = CurrentIterVals[PN];  // Got exit value!
7709 
7710     // Compute the value of the PHIs for the next iteration.
7711     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7712     DenseMap<Instruction *, Constant *> NextIterVals;
7713     Constant *NextPHI =
7714         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7715     if (!NextPHI)
7716       return nullptr;        // Couldn't evaluate!
7717     NextIterVals[PN] = NextPHI;
7718 
7719     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7720 
7721     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
7722     // cease to be able to evaluate one of them or if they stop evolving,
7723     // because that doesn't necessarily prevent us from computing PN.
7724     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7725     for (const auto &I : CurrentIterVals) {
7726       PHINode *PHI = dyn_cast<PHINode>(I.first);
7727       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7728       PHIsToCompute.emplace_back(PHI, I.second);
7729     }
7730     // We use two distinct loops because EvaluateExpression may invalidate any
7731     // iterators into CurrentIterVals.
7732     for (const auto &I : PHIsToCompute) {
7733       PHINode *PHI = I.first;
7734       Constant *&NextPHI = NextIterVals[PHI];
7735       if (!NextPHI) {   // Not already computed.
7736         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7737         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7738       }
7739       if (NextPHI != I.second)
7740         StoppedEvolving = false;
7741     }
7742 
7743     // If all entries in CurrentIterVals == NextIterVals then we can stop
7744     // iterating, the loop can't continue to change.
7745     if (StoppedEvolving)
7746       return RetVal = CurrentIterVals[PN];
7747 
7748     CurrentIterVals.swap(NextIterVals);
7749   }
7750 }
7751 
7752 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7753                                                           Value *Cond,
7754                                                           bool ExitWhen) {
7755   PHINode *PN = getConstantEvolvingPHI(Cond, L);
7756   if (!PN) return getCouldNotCompute();
7757 
7758   // If the loop is canonicalized, the PHI will have exactly two entries.
7759   // That's the only form we support here.
7760   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7761 
7762   DenseMap<Instruction *, Constant *> CurrentIterVals;
7763   BasicBlock *Header = L->getHeader();
7764   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7765 
7766   BasicBlock *Latch = L->getLoopLatch();
7767   assert(Latch && "Should follow from NumIncomingValues == 2!");
7768 
7769   for (PHINode &PHI : Header->phis()) {
7770     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7771       CurrentIterVals[&PHI] = StartCST;
7772   }
7773   if (!CurrentIterVals.count(PN))
7774     return getCouldNotCompute();
7775 
7776   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
7777   // the loop symbolically to determine when the condition gets a value of
7778   // "ExitWhen".
7779   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
7780   const DataLayout &DL = getDataLayout();
7781   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7782     auto *CondVal = dyn_cast_or_null<ConstantInt>(
7783         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7784 
7785     // Couldn't symbolically evaluate.
7786     if (!CondVal) return getCouldNotCompute();
7787 
7788     if (CondVal->getValue() == uint64_t(ExitWhen)) {
7789       ++NumBruteForceTripCountsComputed;
7790       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7791     }
7792 
7793     // Update all the PHI nodes for the next iteration.
7794     DenseMap<Instruction *, Constant *> NextIterVals;
7795 
7796     // Create a list of which PHIs we need to compute. We want to do this before
7797     // calling EvaluateExpression on them because that may invalidate iterators
7798     // into CurrentIterVals.
7799     SmallVector<PHINode *, 8> PHIsToCompute;
7800     for (const auto &I : CurrentIterVals) {
7801       PHINode *PHI = dyn_cast<PHINode>(I.first);
7802       if (!PHI || PHI->getParent() != Header) continue;
7803       PHIsToCompute.push_back(PHI);
7804     }
7805     for (PHINode *PHI : PHIsToCompute) {
7806       Constant *&NextPHI = NextIterVals[PHI];
7807       if (NextPHI) continue;    // Already computed!
7808 
7809       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7810       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7811     }
7812     CurrentIterVals.swap(NextIterVals);
7813   }
7814 
7815   // Too many iterations were needed to evaluate.
7816   return getCouldNotCompute();
7817 }
7818 
7819 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7820   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7821       ValuesAtScopes[V];
7822   // Check to see if we've folded this expression at this loop before.
7823   for (auto &LS : Values)
7824     if (LS.first == L)
7825       return LS.second ? LS.second : V;
7826 
7827   Values.emplace_back(L, nullptr);
7828 
7829   // Otherwise compute it.
7830   const SCEV *C = computeSCEVAtScope(V, L);
7831   for (auto &LS : reverse(ValuesAtScopes[V]))
7832     if (LS.first == L) {
7833       LS.second = C;
7834       break;
7835     }
7836   return C;
7837 }
7838 
7839 /// This builds up a Constant using the ConstantExpr interface.  That way, we
7840 /// will return Constants for objects which aren't represented by a
7841 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7842 /// Returns NULL if the SCEV isn't representable as a Constant.
7843 static Constant *BuildConstantFromSCEV(const SCEV *V) {
7844   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7845     case scCouldNotCompute:
7846     case scAddRecExpr:
7847       break;
7848     case scConstant:
7849       return cast<SCEVConstant>(V)->getValue();
7850     case scUnknown:
7851       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7852     case scSignExtend: {
7853       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7854       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7855         return ConstantExpr::getSExt(CastOp, SS->getType());
7856       break;
7857     }
7858     case scZeroExtend: {
7859       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7860       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7861         return ConstantExpr::getZExt(CastOp, SZ->getType());
7862       break;
7863     }
7864     case scTruncate: {
7865       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
7866       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
7867         return ConstantExpr::getTrunc(CastOp, ST->getType());
7868       break;
7869     }
7870     case scAddExpr: {
7871       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
7872       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
7873         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7874           unsigned AS = PTy->getAddressSpace();
7875           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7876           C = ConstantExpr::getBitCast(C, DestPtrTy);
7877         }
7878         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
7879           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
7880           if (!C2) return nullptr;
7881 
7882           // First pointer!
7883           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
7884             unsigned AS = C2->getType()->getPointerAddressSpace();
7885             std::swap(C, C2);
7886             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
7887             // The offsets have been converted to bytes.  We can add bytes to an
7888             // i8* by GEP with the byte count in the first index.
7889             C = ConstantExpr::getBitCast(C, DestPtrTy);
7890           }
7891 
7892           // Don't bother trying to sum two pointers. We probably can't
7893           // statically compute a load that results from it anyway.
7894           if (C2->getType()->isPointerTy())
7895             return nullptr;
7896 
7897           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
7898             if (PTy->getElementType()->isStructTy())
7899               C2 = ConstantExpr::getIntegerCast(
7900                   C2, Type::getInt32Ty(C->getContext()), true);
7901             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
7902           } else
7903             C = ConstantExpr::getAdd(C, C2);
7904         }
7905         return C;
7906       }
7907       break;
7908     }
7909     case scMulExpr: {
7910       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
7911       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
7912         // Don't bother with pointers at all.
7913         if (C->getType()->isPointerTy()) return nullptr;
7914         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
7915           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
7916           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
7917           C = ConstantExpr::getMul(C, C2);
7918         }
7919         return C;
7920       }
7921       break;
7922     }
7923     case scUDivExpr: {
7924       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
7925       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
7926         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
7927           if (LHS->getType() == RHS->getType())
7928             return ConstantExpr::getUDiv(LHS, RHS);
7929       break;
7930     }
7931     case scSMaxExpr:
7932     case scUMaxExpr:
7933       break; // TODO: smax, umax.
7934   }
7935   return nullptr;
7936 }
7937 
7938 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
7939   if (isa<SCEVConstant>(V)) return V;
7940 
7941   // If this instruction is evolved from a constant-evolving PHI, compute the
7942   // exit value from the loop without using SCEVs.
7943   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
7944     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
7945       const Loop *LI = this->LI[I->getParent()];
7946       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
7947         if (PHINode *PN = dyn_cast<PHINode>(I))
7948           if (PN->getParent() == LI->getHeader()) {
7949             // Okay, there is no closed form solution for the PHI node.  Check
7950             // to see if the loop that contains it has a known backedge-taken
7951             // count.  If so, we may be able to force computation of the exit
7952             // value.
7953             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
7954             if (const SCEVConstant *BTCC =
7955                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
7956 
7957               // This trivial case can show up in some degenerate cases where
7958               // the incoming IR has not yet been fully simplified.
7959               if (BTCC->getValue()->isZero()) {
7960                 Value *InitValue = nullptr;
7961                 bool MultipleInitValues = false;
7962                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
7963                   if (!LI->contains(PN->getIncomingBlock(i))) {
7964                     if (!InitValue)
7965                       InitValue = PN->getIncomingValue(i);
7966                     else if (InitValue != PN->getIncomingValue(i)) {
7967                       MultipleInitValues = true;
7968                       break;
7969                     }
7970                   }
7971                   if (!MultipleInitValues && InitValue)
7972                     return getSCEV(InitValue);
7973                 }
7974               }
7975               // Okay, we know how many times the containing loop executes.  If
7976               // this is a constant evolving PHI node, get the final value at
7977               // the specified iteration number.
7978               Constant *RV =
7979                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
7980               if (RV) return getSCEV(RV);
7981             }
7982           }
7983 
7984       // Okay, this is an expression that we cannot symbolically evaluate
7985       // into a SCEV.  Check to see if it's possible to symbolically evaluate
7986       // the arguments into constants, and if so, try to constant propagate the
7987       // result.  This is particularly useful for computing loop exit values.
7988       if (CanConstantFold(I)) {
7989         SmallVector<Constant *, 4> Operands;
7990         bool MadeImprovement = false;
7991         for (Value *Op : I->operands()) {
7992           if (Constant *C = dyn_cast<Constant>(Op)) {
7993             Operands.push_back(C);
7994             continue;
7995           }
7996 
7997           // If any of the operands is non-constant and if they are
7998           // non-integer and non-pointer, don't even try to analyze them
7999           // with scev techniques.
8000           if (!isSCEVable(Op->getType()))
8001             return V;
8002 
8003           const SCEV *OrigV = getSCEV(Op);
8004           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8005           MadeImprovement |= OrigV != OpV;
8006 
8007           Constant *C = BuildConstantFromSCEV(OpV);
8008           if (!C) return V;
8009           if (C->getType() != Op->getType())
8010             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8011                                                               Op->getType(),
8012                                                               false),
8013                                       C, Op->getType());
8014           Operands.push_back(C);
8015         }
8016 
8017         // Check to see if getSCEVAtScope actually made an improvement.
8018         if (MadeImprovement) {
8019           Constant *C = nullptr;
8020           const DataLayout &DL = getDataLayout();
8021           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8022             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8023                                                 Operands[1], DL, &TLI);
8024           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8025             if (!LI->isVolatile())
8026               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8027           } else
8028             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8029           if (!C) return V;
8030           return getSCEV(C);
8031         }
8032       }
8033     }
8034 
8035     // This is some other type of SCEVUnknown, just return it.
8036     return V;
8037   }
8038 
8039   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8040     // Avoid performing the look-up in the common case where the specified
8041     // expression has no loop-variant portions.
8042     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8043       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8044       if (OpAtScope != Comm->getOperand(i)) {
8045         // Okay, at least one of these operands is loop variant but might be
8046         // foldable.  Build a new instance of the folded commutative expression.
8047         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8048                                             Comm->op_begin()+i);
8049         NewOps.push_back(OpAtScope);
8050 
8051         for (++i; i != e; ++i) {
8052           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8053           NewOps.push_back(OpAtScope);
8054         }
8055         if (isa<SCEVAddExpr>(Comm))
8056           return getAddExpr(NewOps);
8057         if (isa<SCEVMulExpr>(Comm))
8058           return getMulExpr(NewOps);
8059         if (isa<SCEVSMaxExpr>(Comm))
8060           return getSMaxExpr(NewOps);
8061         if (isa<SCEVUMaxExpr>(Comm))
8062           return getUMaxExpr(NewOps);
8063         llvm_unreachable("Unknown commutative SCEV type!");
8064       }
8065     }
8066     // If we got here, all operands are loop invariant.
8067     return Comm;
8068   }
8069 
8070   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8071     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8072     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8073     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8074       return Div;   // must be loop invariant
8075     return getUDivExpr(LHS, RHS);
8076   }
8077 
8078   // If this is a loop recurrence for a loop that does not contain L, then we
8079   // are dealing with the final value computed by the loop.
8080   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8081     // First, attempt to evaluate each operand.
8082     // Avoid performing the look-up in the common case where the specified
8083     // expression has no loop-variant portions.
8084     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8085       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8086       if (OpAtScope == AddRec->getOperand(i))
8087         continue;
8088 
8089       // Okay, at least one of these operands is loop variant but might be
8090       // foldable.  Build a new instance of the folded commutative expression.
8091       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8092                                           AddRec->op_begin()+i);
8093       NewOps.push_back(OpAtScope);
8094       for (++i; i != e; ++i)
8095         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8096 
8097       const SCEV *FoldedRec =
8098         getAddRecExpr(NewOps, AddRec->getLoop(),
8099                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8100       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8101       // The addrec may be folded to a nonrecurrence, for example, if the
8102       // induction variable is multiplied by zero after constant folding. Go
8103       // ahead and return the folded value.
8104       if (!AddRec)
8105         return FoldedRec;
8106       break;
8107     }
8108 
8109     // If the scope is outside the addrec's loop, evaluate it by using the
8110     // loop exit value of the addrec.
8111     if (!AddRec->getLoop()->contains(L)) {
8112       // To evaluate this recurrence, we need to know how many times the AddRec
8113       // loop iterates.  Compute this now.
8114       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8115       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8116 
8117       // Then, evaluate the AddRec.
8118       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8119     }
8120 
8121     return AddRec;
8122   }
8123 
8124   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8125     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8126     if (Op == Cast->getOperand())
8127       return Cast;  // must be loop invariant
8128     return getZeroExtendExpr(Op, Cast->getType());
8129   }
8130 
8131   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8132     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8133     if (Op == Cast->getOperand())
8134       return Cast;  // must be loop invariant
8135     return getSignExtendExpr(Op, Cast->getType());
8136   }
8137 
8138   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8139     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8140     if (Op == Cast->getOperand())
8141       return Cast;  // must be loop invariant
8142     return getTruncateExpr(Op, Cast->getType());
8143   }
8144 
8145   llvm_unreachable("Unknown SCEV type!");
8146 }
8147 
8148 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8149   return getSCEVAtScope(getSCEV(V), L);
8150 }
8151 
8152 /// Finds the minimum unsigned root of the following equation:
8153 ///
8154 ///     A * X = B (mod N)
8155 ///
8156 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8157 /// A and B isn't important.
8158 ///
8159 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8160 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8161                                                ScalarEvolution &SE) {
8162   uint32_t BW = A.getBitWidth();
8163   assert(BW == SE.getTypeSizeInBits(B->getType()));
8164   assert(A != 0 && "A must be non-zero.");
8165 
8166   // 1. D = gcd(A, N)
8167   //
8168   // The gcd of A and N may have only one prime factor: 2. The number of
8169   // trailing zeros in A is its multiplicity
8170   uint32_t Mult2 = A.countTrailingZeros();
8171   // D = 2^Mult2
8172 
8173   // 2. Check if B is divisible by D.
8174   //
8175   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8176   // is not less than multiplicity of this prime factor for D.
8177   if (SE.GetMinTrailingZeros(B) < Mult2)
8178     return SE.getCouldNotCompute();
8179 
8180   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8181   // modulo (N / D).
8182   //
8183   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8184   // (N / D) in general. The inverse itself always fits into BW bits, though,
8185   // so we immediately truncate it.
8186   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8187   APInt Mod(BW + 1, 0);
8188   Mod.setBit(BW - Mult2);  // Mod = N / D
8189   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8190 
8191   // 4. Compute the minimum unsigned root of the equation:
8192   // I * (B / D) mod (N / D)
8193   // To simplify the computation, we factor out the divide by D:
8194   // (I * B mod N) / D
8195   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8196   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8197 }
8198 
8199 /// Find the roots of the quadratic equation for the given quadratic chrec
8200 /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
8201 /// two SCEVCouldNotCompute objects.
8202 static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
8203 SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8204   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8205   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8206   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8207   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8208 
8209   // We currently can only solve this if the coefficients are constants.
8210   if (!LC || !MC || !NC)
8211     return None;
8212 
8213   uint32_t BitWidth = LC->getAPInt().getBitWidth();
8214   const APInt &L = LC->getAPInt();
8215   const APInt &M = MC->getAPInt();
8216   const APInt &N = NC->getAPInt();
8217   APInt Two(BitWidth, 2);
8218 
8219   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
8220 
8221   // The A coefficient is N/2
8222   APInt A = N.sdiv(Two);
8223 
8224   // The B coefficient is M-N/2
8225   APInt B = M;
8226   B -= A; // A is the same as N/2.
8227 
8228   // The C coefficient is L.
8229   const APInt& C = L;
8230 
8231   // Compute the B^2-4ac term.
8232   APInt SqrtTerm = B;
8233   SqrtTerm *= B;
8234   SqrtTerm -= 4 * (A * C);
8235 
8236   if (SqrtTerm.isNegative()) {
8237     // The loop is provably infinite.
8238     return None;
8239   }
8240 
8241   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
8242   // integer value or else APInt::sqrt() will assert.
8243   APInt SqrtVal = SqrtTerm.sqrt();
8244 
8245   // Compute the two solutions for the quadratic formula.
8246   // The divisions must be performed as signed divisions.
8247   APInt NegB = -std::move(B);
8248   APInt TwoA = std::move(A);
8249   TwoA <<= 1;
8250   if (TwoA.isNullValue())
8251     return None;
8252 
8253   LLVMContext &Context = SE.getContext();
8254 
8255   ConstantInt *Solution1 =
8256     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
8257   ConstantInt *Solution2 =
8258     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
8259 
8260   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
8261                         cast<SCEVConstant>(SE.getConstant(Solution2)));
8262 }
8263 
8264 ScalarEvolution::ExitLimit
8265 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8266                               bool AllowPredicates) {
8267 
8268   // This is only used for loops with a "x != y" exit test. The exit condition
8269   // is now expressed as a single expression, V = x-y. So the exit test is
8270   // effectively V != 0.  We know and take advantage of the fact that this
8271   // expression only being used in a comparison by zero context.
8272 
8273   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8274   // If the value is a constant
8275   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8276     // If the value is already zero, the branch will execute zero times.
8277     if (C->getValue()->isZero()) return C;
8278     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8279   }
8280 
8281   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
8282   if (!AddRec && AllowPredicates)
8283     // Try to make this an AddRec using runtime tests, in the first X
8284     // iterations of this loop, where X is the SCEV expression found by the
8285     // algorithm below.
8286     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8287 
8288   if (!AddRec || AddRec->getLoop() != L)
8289     return getCouldNotCompute();
8290 
8291   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8292   // the quadratic equation to solve it.
8293   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8294     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
8295       const SCEVConstant *R1 = Roots->first;
8296       const SCEVConstant *R2 = Roots->second;
8297       // Pick the smallest positive root value.
8298       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8299               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
8300         if (!CB->getZExtValue())
8301           std::swap(R1, R2); // R1 is the minimum root now.
8302 
8303         // We can only use this value if the chrec ends up with an exact zero
8304         // value at this index.  When solving for "X*X != 5", for example, we
8305         // should not accept a root of 2.
8306         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
8307         if (Val->isZero())
8308           // We found a quadratic root!
8309           return ExitLimit(R1, R1, false, Predicates);
8310       }
8311     }
8312     return getCouldNotCompute();
8313   }
8314 
8315   // Otherwise we can only handle this if it is affine.
8316   if (!AddRec->isAffine())
8317     return getCouldNotCompute();
8318 
8319   // If this is an affine expression, the execution count of this branch is
8320   // the minimum unsigned root of the following equation:
8321   //
8322   //     Start + Step*N = 0 (mod 2^BW)
8323   //
8324   // equivalent to:
8325   //
8326   //             Step*N = -Start (mod 2^BW)
8327   //
8328   // where BW is the common bit width of Start and Step.
8329 
8330   // Get the initial value for the loop.
8331   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8332   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8333 
8334   // For now we handle only constant steps.
8335   //
8336   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8337   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8338   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8339   // We have not yet seen any such cases.
8340   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8341   if (!StepC || StepC->getValue()->isZero())
8342     return getCouldNotCompute();
8343 
8344   // For positive steps (counting up until unsigned overflow):
8345   //   N = -Start/Step (as unsigned)
8346   // For negative steps (counting down to zero):
8347   //   N = Start/-Step
8348   // First compute the unsigned distance from zero in the direction of Step.
8349   bool CountDown = StepC->getAPInt().isNegative();
8350   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8351 
8352   // Handle unitary steps, which cannot wraparound.
8353   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8354   //   N = Distance (as unsigned)
8355   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8356     APInt MaxBECount = getUnsignedRangeMax(Distance);
8357 
8358     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8359     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
8360     // case, and see if we can improve the bound.
8361     //
8362     // Explicitly handling this here is necessary because getUnsignedRange
8363     // isn't context-sensitive; it doesn't know that we only care about the
8364     // range inside the loop.
8365     const SCEV *Zero = getZero(Distance->getType());
8366     const SCEV *One = getOne(Distance->getType());
8367     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8368     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8369       // If Distance + 1 doesn't overflow, we can compute the maximum distance
8370       // as "unsigned_max(Distance + 1) - 1".
8371       ConstantRange CR = getUnsignedRange(DistancePlusOne);
8372       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8373     }
8374     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8375   }
8376 
8377   // If the condition controls loop exit (the loop exits only if the expression
8378   // is true) and the addition is no-wrap we can use unsigned divide to
8379   // compute the backedge count.  In this case, the step may not divide the
8380   // distance, but we don't care because if the condition is "missed" the loop
8381   // will have undefined behavior due to wrapping.
8382   if (ControlsExit && AddRec->hasNoSelfWrap() &&
8383       loopHasNoAbnormalExits(AddRec->getLoop())) {
8384     const SCEV *Exact =
8385         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8386     const SCEV *Max =
8387         Exact == getCouldNotCompute()
8388             ? Exact
8389             : getConstant(getUnsignedRangeMax(Exact));
8390     return ExitLimit(Exact, Max, false, Predicates);
8391   }
8392 
8393   // Solve the general equation.
8394   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8395                                                getNegativeSCEV(Start), *this);
8396   const SCEV *M = E == getCouldNotCompute()
8397                       ? E
8398                       : getConstant(getUnsignedRangeMax(E));
8399   return ExitLimit(E, M, false, Predicates);
8400 }
8401 
8402 ScalarEvolution::ExitLimit
8403 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8404   // Loops that look like: while (X == 0) are very strange indeed.  We don't
8405   // handle them yet except for the trivial case.  This could be expanded in the
8406   // future as needed.
8407 
8408   // If the value is a constant, check to see if it is known to be non-zero
8409   // already.  If so, the backedge will execute zero times.
8410   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8411     if (!C->getValue()->isZero())
8412       return getZero(C->getType());
8413     return getCouldNotCompute();  // Otherwise it will loop infinitely.
8414   }
8415 
8416   // We could implement others, but I really doubt anyone writes loops like
8417   // this, and if they did, they would already be constant folded.
8418   return getCouldNotCompute();
8419 }
8420 
8421 std::pair<BasicBlock *, BasicBlock *>
8422 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8423   // If the block has a unique predecessor, then there is no path from the
8424   // predecessor to the block that does not go through the direct edge
8425   // from the predecessor to the block.
8426   if (BasicBlock *Pred = BB->getSinglePredecessor())
8427     return {Pred, BB};
8428 
8429   // A loop's header is defined to be a block that dominates the loop.
8430   // If the header has a unique predecessor outside the loop, it must be
8431   // a block that has exactly one successor that can reach the loop.
8432   if (Loop *L = LI.getLoopFor(BB))
8433     return {L->getLoopPredecessor(), L->getHeader()};
8434 
8435   return {nullptr, nullptr};
8436 }
8437 
8438 /// SCEV structural equivalence is usually sufficient for testing whether two
8439 /// expressions are equal, however for the purposes of looking for a condition
8440 /// guarding a loop, it can be useful to be a little more general, since a
8441 /// front-end may have replicated the controlling expression.
8442 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8443   // Quick check to see if they are the same SCEV.
8444   if (A == B) return true;
8445 
8446   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8447     // Not all instructions that are "identical" compute the same value.  For
8448     // instance, two distinct alloca instructions allocating the same type are
8449     // identical and do not read memory; but compute distinct values.
8450     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8451   };
8452 
8453   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8454   // two different instructions with the same value. Check for this case.
8455   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8456     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8457       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8458         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8459           if (ComputesEqualValues(AI, BI))
8460             return true;
8461 
8462   // Otherwise assume they may have a different value.
8463   return false;
8464 }
8465 
8466 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8467                                            const SCEV *&LHS, const SCEV *&RHS,
8468                                            unsigned Depth) {
8469   bool Changed = false;
8470 
8471   // If we hit the max recursion limit bail out.
8472   if (Depth >= 3)
8473     return false;
8474 
8475   // Canonicalize a constant to the right side.
8476   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8477     // Check for both operands constant.
8478     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8479       if (ConstantExpr::getICmp(Pred,
8480                                 LHSC->getValue(),
8481                                 RHSC->getValue())->isNullValue())
8482         goto trivially_false;
8483       else
8484         goto trivially_true;
8485     }
8486     // Otherwise swap the operands to put the constant on the right.
8487     std::swap(LHS, RHS);
8488     Pred = ICmpInst::getSwappedPredicate(Pred);
8489     Changed = true;
8490   }
8491 
8492   // If we're comparing an addrec with a value which is loop-invariant in the
8493   // addrec's loop, put the addrec on the left. Also make a dominance check,
8494   // as both operands could be addrecs loop-invariant in each other's loop.
8495   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8496     const Loop *L = AR->getLoop();
8497     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8498       std::swap(LHS, RHS);
8499       Pred = ICmpInst::getSwappedPredicate(Pred);
8500       Changed = true;
8501     }
8502   }
8503 
8504   // If there's a constant operand, canonicalize comparisons with boundary
8505   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8506   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8507     const APInt &RA = RC->getAPInt();
8508 
8509     bool SimplifiedByConstantRange = false;
8510 
8511     if (!ICmpInst::isEquality(Pred)) {
8512       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8513       if (ExactCR.isFullSet())
8514         goto trivially_true;
8515       else if (ExactCR.isEmptySet())
8516         goto trivially_false;
8517 
8518       APInt NewRHS;
8519       CmpInst::Predicate NewPred;
8520       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8521           ICmpInst::isEquality(NewPred)) {
8522         // We were able to convert an inequality to an equality.
8523         Pred = NewPred;
8524         RHS = getConstant(NewRHS);
8525         Changed = SimplifiedByConstantRange = true;
8526       }
8527     }
8528 
8529     if (!SimplifiedByConstantRange) {
8530       switch (Pred) {
8531       default:
8532         break;
8533       case ICmpInst::ICMP_EQ:
8534       case ICmpInst::ICMP_NE:
8535         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8536         if (!RA)
8537           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8538             if (const SCEVMulExpr *ME =
8539                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8540               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8541                   ME->getOperand(0)->isAllOnesValue()) {
8542                 RHS = AE->getOperand(1);
8543                 LHS = ME->getOperand(1);
8544                 Changed = true;
8545               }
8546         break;
8547 
8548 
8549         // The "Should have been caught earlier!" messages refer to the fact
8550         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8551         // should have fired on the corresponding cases, and canonicalized the
8552         // check to trivially_true or trivially_false.
8553 
8554       case ICmpInst::ICMP_UGE:
8555         assert(!RA.isMinValue() && "Should have been caught earlier!");
8556         Pred = ICmpInst::ICMP_UGT;
8557         RHS = getConstant(RA - 1);
8558         Changed = true;
8559         break;
8560       case ICmpInst::ICMP_ULE:
8561         assert(!RA.isMaxValue() && "Should have been caught earlier!");
8562         Pred = ICmpInst::ICMP_ULT;
8563         RHS = getConstant(RA + 1);
8564         Changed = true;
8565         break;
8566       case ICmpInst::ICMP_SGE:
8567         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8568         Pred = ICmpInst::ICMP_SGT;
8569         RHS = getConstant(RA - 1);
8570         Changed = true;
8571         break;
8572       case ICmpInst::ICMP_SLE:
8573         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8574         Pred = ICmpInst::ICMP_SLT;
8575         RHS = getConstant(RA + 1);
8576         Changed = true;
8577         break;
8578       }
8579     }
8580   }
8581 
8582   // Check for obvious equality.
8583   if (HasSameValue(LHS, RHS)) {
8584     if (ICmpInst::isTrueWhenEqual(Pred))
8585       goto trivially_true;
8586     if (ICmpInst::isFalseWhenEqual(Pred))
8587       goto trivially_false;
8588   }
8589 
8590   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8591   // adding or subtracting 1 from one of the operands.
8592   switch (Pred) {
8593   case ICmpInst::ICMP_SLE:
8594     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8595       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8596                        SCEV::FlagNSW);
8597       Pred = ICmpInst::ICMP_SLT;
8598       Changed = true;
8599     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8600       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8601                        SCEV::FlagNSW);
8602       Pred = ICmpInst::ICMP_SLT;
8603       Changed = true;
8604     }
8605     break;
8606   case ICmpInst::ICMP_SGE:
8607     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8608       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8609                        SCEV::FlagNSW);
8610       Pred = ICmpInst::ICMP_SGT;
8611       Changed = true;
8612     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8613       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8614                        SCEV::FlagNSW);
8615       Pred = ICmpInst::ICMP_SGT;
8616       Changed = true;
8617     }
8618     break;
8619   case ICmpInst::ICMP_ULE:
8620     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8621       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8622                        SCEV::FlagNUW);
8623       Pred = ICmpInst::ICMP_ULT;
8624       Changed = true;
8625     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8626       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8627       Pred = ICmpInst::ICMP_ULT;
8628       Changed = true;
8629     }
8630     break;
8631   case ICmpInst::ICMP_UGE:
8632     if (!getUnsignedRangeMin(RHS).isMinValue()) {
8633       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8634       Pred = ICmpInst::ICMP_UGT;
8635       Changed = true;
8636     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8637       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8638                        SCEV::FlagNUW);
8639       Pred = ICmpInst::ICMP_UGT;
8640       Changed = true;
8641     }
8642     break;
8643   default:
8644     break;
8645   }
8646 
8647   // TODO: More simplifications are possible here.
8648 
8649   // Recursively simplify until we either hit a recursion limit or nothing
8650   // changes.
8651   if (Changed)
8652     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
8653 
8654   return Changed;
8655 
8656 trivially_true:
8657   // Return 0 == 0.
8658   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8659   Pred = ICmpInst::ICMP_EQ;
8660   return true;
8661 
8662 trivially_false:
8663   // Return 0 != 0.
8664   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8665   Pred = ICmpInst::ICMP_NE;
8666   return true;
8667 }
8668 
8669 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
8670   return getSignedRangeMax(S).isNegative();
8671 }
8672 
8673 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
8674   return getSignedRangeMin(S).isStrictlyPositive();
8675 }
8676 
8677 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
8678   return !getSignedRangeMin(S).isNegative();
8679 }
8680 
8681 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
8682   return !getSignedRangeMax(S).isStrictlyPositive();
8683 }
8684 
8685 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
8686   return isKnownNegative(S) || isKnownPositive(S);
8687 }
8688 
8689 std::pair<const SCEV *, const SCEV *>
8690 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
8691   // Compute SCEV on entry of loop L.
8692   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
8693   if (Start == getCouldNotCompute())
8694     return { Start, Start };
8695   // Compute post increment SCEV for loop L.
8696   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
8697   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
8698   return { Start, PostInc };
8699 }
8700 
8701 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
8702                                           const SCEV *LHS, const SCEV *RHS) {
8703   // First collect all loops.
8704   SmallPtrSet<const Loop *, 8> LoopsUsed;
8705   getUsedLoops(LHS, LoopsUsed);
8706   getUsedLoops(RHS, LoopsUsed);
8707 
8708   if (LoopsUsed.empty())
8709     return false;
8710 
8711   // Domination relationship must be a linear order on collected loops.
8712 #ifndef NDEBUG
8713   for (auto *L1 : LoopsUsed)
8714     for (auto *L2 : LoopsUsed)
8715       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
8716               DT.dominates(L2->getHeader(), L1->getHeader())) &&
8717              "Domination relationship is not a linear order");
8718 #endif
8719 
8720   const Loop *MDL =
8721       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
8722                         [&](const Loop *L1, const Loop *L2) {
8723          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
8724        });
8725 
8726   // Get init and post increment value for LHS.
8727   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
8728   // if LHS contains unknown non-invariant SCEV then bail out.
8729   if (SplitLHS.first == getCouldNotCompute())
8730     return false;
8731   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
8732   // Get init and post increment value for RHS.
8733   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
8734   // if RHS contains unknown non-invariant SCEV then bail out.
8735   if (SplitRHS.first == getCouldNotCompute())
8736     return false;
8737   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
8738   // It is possible that init SCEV contains an invariant load but it does
8739   // not dominate MDL and is not available at MDL loop entry, so we should
8740   // check it here.
8741   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
8742       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
8743     return false;
8744 
8745   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
8746          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
8747                                      SplitRHS.second);
8748 }
8749 
8750 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
8751                                        const SCEV *LHS, const SCEV *RHS) {
8752   // Canonicalize the inputs first.
8753   (void)SimplifyICmpOperands(Pred, LHS, RHS);
8754 
8755   if (isKnownViaInduction(Pred, LHS, RHS))
8756     return true;
8757 
8758   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
8759     return true;
8760 
8761   // Otherwise see what can be done with some simple reasoning.
8762   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
8763 }
8764 
8765 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
8766                                               const SCEVAddRecExpr *LHS,
8767                                               const SCEV *RHS) {
8768   const Loop *L = LHS->getLoop();
8769   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
8770          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
8771 }
8772 
8773 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
8774                                            ICmpInst::Predicate Pred,
8775                                            bool &Increasing) {
8776   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
8777 
8778 #ifndef NDEBUG
8779   // Verify an invariant: inverting the predicate should turn a monotonically
8780   // increasing change to a monotonically decreasing one, and vice versa.
8781   bool IncreasingSwapped;
8782   bool ResultSwapped = isMonotonicPredicateImpl(
8783       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
8784 
8785   assert(Result == ResultSwapped && "should be able to analyze both!");
8786   if (ResultSwapped)
8787     assert(Increasing == !IncreasingSwapped &&
8788            "monotonicity should flip as we flip the predicate");
8789 #endif
8790 
8791   return Result;
8792 }
8793 
8794 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
8795                                                ICmpInst::Predicate Pred,
8796                                                bool &Increasing) {
8797 
8798   // A zero step value for LHS means the induction variable is essentially a
8799   // loop invariant value. We don't really depend on the predicate actually
8800   // flipping from false to true (for increasing predicates, and the other way
8801   // around for decreasing predicates), all we care about is that *if* the
8802   // predicate changes then it only changes from false to true.
8803   //
8804   // A zero step value in itself is not very useful, but there may be places
8805   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
8806   // as general as possible.
8807 
8808   switch (Pred) {
8809   default:
8810     return false; // Conservative answer
8811 
8812   case ICmpInst::ICMP_UGT:
8813   case ICmpInst::ICMP_UGE:
8814   case ICmpInst::ICMP_ULT:
8815   case ICmpInst::ICMP_ULE:
8816     if (!LHS->hasNoUnsignedWrap())
8817       return false;
8818 
8819     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
8820     return true;
8821 
8822   case ICmpInst::ICMP_SGT:
8823   case ICmpInst::ICMP_SGE:
8824   case ICmpInst::ICMP_SLT:
8825   case ICmpInst::ICMP_SLE: {
8826     if (!LHS->hasNoSignedWrap())
8827       return false;
8828 
8829     const SCEV *Step = LHS->getStepRecurrence(*this);
8830 
8831     if (isKnownNonNegative(Step)) {
8832       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
8833       return true;
8834     }
8835 
8836     if (isKnownNonPositive(Step)) {
8837       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
8838       return true;
8839     }
8840 
8841     return false;
8842   }
8843 
8844   }
8845 
8846   llvm_unreachable("switch has default clause!");
8847 }
8848 
8849 bool ScalarEvolution::isLoopInvariantPredicate(
8850     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
8851     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
8852     const SCEV *&InvariantRHS) {
8853 
8854   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
8855   if (!isLoopInvariant(RHS, L)) {
8856     if (!isLoopInvariant(LHS, L))
8857       return false;
8858 
8859     std::swap(LHS, RHS);
8860     Pred = ICmpInst::getSwappedPredicate(Pred);
8861   }
8862 
8863   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8864   if (!ArLHS || ArLHS->getLoop() != L)
8865     return false;
8866 
8867   bool Increasing;
8868   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
8869     return false;
8870 
8871   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
8872   // true as the loop iterates, and the backedge is control dependent on
8873   // "ArLHS `Pred` RHS" == true then we can reason as follows:
8874   //
8875   //   * if the predicate was false in the first iteration then the predicate
8876   //     is never evaluated again, since the loop exits without taking the
8877   //     backedge.
8878   //   * if the predicate was true in the first iteration then it will
8879   //     continue to be true for all future iterations since it is
8880   //     monotonically increasing.
8881   //
8882   // For both the above possibilities, we can replace the loop varying
8883   // predicate with its value on the first iteration of the loop (which is
8884   // loop invariant).
8885   //
8886   // A similar reasoning applies for a monotonically decreasing predicate, by
8887   // replacing true with false and false with true in the above two bullets.
8888 
8889   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
8890 
8891   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
8892     return false;
8893 
8894   InvariantPred = Pred;
8895   InvariantLHS = ArLHS->getStart();
8896   InvariantRHS = RHS;
8897   return true;
8898 }
8899 
8900 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
8901     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
8902   if (HasSameValue(LHS, RHS))
8903     return ICmpInst::isTrueWhenEqual(Pred);
8904 
8905   // This code is split out from isKnownPredicate because it is called from
8906   // within isLoopEntryGuardedByCond.
8907 
8908   auto CheckRanges =
8909       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
8910     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
8911         .contains(RangeLHS);
8912   };
8913 
8914   // The check at the top of the function catches the case where the values are
8915   // known to be equal.
8916   if (Pred == CmpInst::ICMP_EQ)
8917     return false;
8918 
8919   if (Pred == CmpInst::ICMP_NE)
8920     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
8921            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
8922            isKnownNonZero(getMinusSCEV(LHS, RHS));
8923 
8924   if (CmpInst::isSigned(Pred))
8925     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
8926 
8927   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
8928 }
8929 
8930 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
8931                                                     const SCEV *LHS,
8932                                                     const SCEV *RHS) {
8933   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
8934   // Return Y via OutY.
8935   auto MatchBinaryAddToConst =
8936       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
8937              SCEV::NoWrapFlags ExpectedFlags) {
8938     const SCEV *NonConstOp, *ConstOp;
8939     SCEV::NoWrapFlags FlagsPresent;
8940 
8941     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
8942         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
8943       return false;
8944 
8945     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
8946     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
8947   };
8948 
8949   APInt C;
8950 
8951   switch (Pred) {
8952   default:
8953     break;
8954 
8955   case ICmpInst::ICMP_SGE:
8956     std::swap(LHS, RHS);
8957     LLVM_FALLTHROUGH;
8958   case ICmpInst::ICMP_SLE:
8959     // X s<= (X + C)<nsw> if C >= 0
8960     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
8961       return true;
8962 
8963     // (X + C)<nsw> s<= X if C <= 0
8964     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
8965         !C.isStrictlyPositive())
8966       return true;
8967     break;
8968 
8969   case ICmpInst::ICMP_SGT:
8970     std::swap(LHS, RHS);
8971     LLVM_FALLTHROUGH;
8972   case ICmpInst::ICMP_SLT:
8973     // X s< (X + C)<nsw> if C > 0
8974     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
8975         C.isStrictlyPositive())
8976       return true;
8977 
8978     // (X + C)<nsw> s< X if C < 0
8979     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
8980       return true;
8981     break;
8982   }
8983 
8984   return false;
8985 }
8986 
8987 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
8988                                                    const SCEV *LHS,
8989                                                    const SCEV *RHS) {
8990   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
8991     return false;
8992 
8993   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
8994   // the stack can result in exponential time complexity.
8995   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
8996 
8997   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
8998   //
8999   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9000   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9001   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9002   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9003   // use isKnownPredicate later if needed.
9004   return isKnownNonNegative(RHS) &&
9005          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9006          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9007 }
9008 
9009 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9010                                         ICmpInst::Predicate Pred,
9011                                         const SCEV *LHS, const SCEV *RHS) {
9012   // No need to even try if we know the module has no guards.
9013   if (!HasGuards)
9014     return false;
9015 
9016   return any_of(*BB, [&](Instruction &I) {
9017     using namespace llvm::PatternMatch;
9018 
9019     Value *Condition;
9020     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9021                          m_Value(Condition))) &&
9022            isImpliedCond(Pred, LHS, RHS, Condition, false);
9023   });
9024 }
9025 
9026 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9027 /// protected by a conditional between LHS and RHS.  This is used to
9028 /// to eliminate casts.
9029 bool
9030 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9031                                              ICmpInst::Predicate Pred,
9032                                              const SCEV *LHS, const SCEV *RHS) {
9033   // Interpret a null as meaning no loop, where there is obviously no guard
9034   // (interprocedural conditions notwithstanding).
9035   if (!L) return true;
9036 
9037   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9038     return true;
9039 
9040   BasicBlock *Latch = L->getLoopLatch();
9041   if (!Latch)
9042     return false;
9043 
9044   BranchInst *LoopContinuePredicate =
9045     dyn_cast<BranchInst>(Latch->getTerminator());
9046   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9047       isImpliedCond(Pred, LHS, RHS,
9048                     LoopContinuePredicate->getCondition(),
9049                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9050     return true;
9051 
9052   // We don't want more than one activation of the following loops on the stack
9053   // -- that can lead to O(n!) time complexity.
9054   if (WalkingBEDominatingConds)
9055     return false;
9056 
9057   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9058 
9059   // See if we can exploit a trip count to prove the predicate.
9060   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9061   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9062   if (LatchBECount != getCouldNotCompute()) {
9063     // We know that Latch branches back to the loop header exactly
9064     // LatchBECount times.  This means the backdege condition at Latch is
9065     // equivalent to  "{0,+,1} u< LatchBECount".
9066     Type *Ty = LatchBECount->getType();
9067     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9068     const SCEV *LoopCounter =
9069       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9070     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9071                       LatchBECount))
9072       return true;
9073   }
9074 
9075   // Check conditions due to any @llvm.assume intrinsics.
9076   for (auto &AssumeVH : AC.assumptions()) {
9077     if (!AssumeVH)
9078       continue;
9079     auto *CI = cast<CallInst>(AssumeVH);
9080     if (!DT.dominates(CI, Latch->getTerminator()))
9081       continue;
9082 
9083     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9084       return true;
9085   }
9086 
9087   // If the loop is not reachable from the entry block, we risk running into an
9088   // infinite loop as we walk up into the dom tree.  These loops do not matter
9089   // anyway, so we just return a conservative answer when we see them.
9090   if (!DT.isReachableFromEntry(L->getHeader()))
9091     return false;
9092 
9093   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9094     return true;
9095 
9096   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9097        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9098     assert(DTN && "should reach the loop header before reaching the root!");
9099 
9100     BasicBlock *BB = DTN->getBlock();
9101     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9102       return true;
9103 
9104     BasicBlock *PBB = BB->getSinglePredecessor();
9105     if (!PBB)
9106       continue;
9107 
9108     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9109     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9110       continue;
9111 
9112     Value *Condition = ContinuePredicate->getCondition();
9113 
9114     // If we have an edge `E` within the loop body that dominates the only
9115     // latch, the condition guarding `E` also guards the backedge.  This
9116     // reasoning works only for loops with a single latch.
9117 
9118     BasicBlockEdge DominatingEdge(PBB, BB);
9119     if (DominatingEdge.isSingleEdge()) {
9120       // We're constructively (and conservatively) enumerating edges within the
9121       // loop body that dominate the latch.  The dominator tree better agree
9122       // with us on this:
9123       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9124 
9125       if (isImpliedCond(Pred, LHS, RHS, Condition,
9126                         BB != ContinuePredicate->getSuccessor(0)))
9127         return true;
9128     }
9129   }
9130 
9131   return false;
9132 }
9133 
9134 bool
9135 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9136                                           ICmpInst::Predicate Pred,
9137                                           const SCEV *LHS, const SCEV *RHS) {
9138   // Interpret a null as meaning no loop, where there is obviously no guard
9139   // (interprocedural conditions notwithstanding).
9140   if (!L) return false;
9141 
9142   // Both LHS and RHS must be available at loop entry.
9143   assert(isAvailableAtLoopEntry(LHS, L) &&
9144          "LHS is not available at Loop Entry");
9145   assert(isAvailableAtLoopEntry(RHS, L) &&
9146          "RHS is not available at Loop Entry");
9147 
9148   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9149     return true;
9150 
9151   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9152   // the facts (a >= b && a != b) separately. A typical situation is when the
9153   // non-strict comparison is known from ranges and non-equality is known from
9154   // dominating predicates. If we are proving strict comparison, we always try
9155   // to prove non-equality and non-strict comparison separately.
9156   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9157   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9158   bool ProvedNonStrictComparison = false;
9159   bool ProvedNonEquality = false;
9160 
9161   if (ProvingStrictComparison) {
9162     ProvedNonStrictComparison =
9163         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9164     ProvedNonEquality =
9165         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9166     if (ProvedNonStrictComparison && ProvedNonEquality)
9167       return true;
9168   }
9169 
9170   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9171   auto ProveViaGuard = [&](BasicBlock *Block) {
9172     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9173       return true;
9174     if (ProvingStrictComparison) {
9175       if (!ProvedNonStrictComparison)
9176         ProvedNonStrictComparison =
9177             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9178       if (!ProvedNonEquality)
9179         ProvedNonEquality =
9180             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9181       if (ProvedNonStrictComparison && ProvedNonEquality)
9182         return true;
9183     }
9184     return false;
9185   };
9186 
9187   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9188   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9189     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9190       return true;
9191     if (ProvingStrictComparison) {
9192       if (!ProvedNonStrictComparison)
9193         ProvedNonStrictComparison =
9194             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9195       if (!ProvedNonEquality)
9196         ProvedNonEquality =
9197             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9198       if (ProvedNonStrictComparison && ProvedNonEquality)
9199         return true;
9200     }
9201     return false;
9202   };
9203 
9204   // Starting at the loop predecessor, climb up the predecessor chain, as long
9205   // as there are predecessors that can be found that have unique successors
9206   // leading to the original header.
9207   for (std::pair<BasicBlock *, BasicBlock *>
9208          Pair(L->getLoopPredecessor(), L->getHeader());
9209        Pair.first;
9210        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9211 
9212     if (ProveViaGuard(Pair.first))
9213       return true;
9214 
9215     BranchInst *LoopEntryPredicate =
9216       dyn_cast<BranchInst>(Pair.first->getTerminator());
9217     if (!LoopEntryPredicate ||
9218         LoopEntryPredicate->isUnconditional())
9219       continue;
9220 
9221     if (ProveViaCond(LoopEntryPredicate->getCondition(),
9222                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
9223       return true;
9224   }
9225 
9226   // Check conditions due to any @llvm.assume intrinsics.
9227   for (auto &AssumeVH : AC.assumptions()) {
9228     if (!AssumeVH)
9229       continue;
9230     auto *CI = cast<CallInst>(AssumeVH);
9231     if (!DT.dominates(CI, L->getHeader()))
9232       continue;
9233 
9234     if (ProveViaCond(CI->getArgOperand(0), false))
9235       return true;
9236   }
9237 
9238   return false;
9239 }
9240 
9241 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9242                                     const SCEV *LHS, const SCEV *RHS,
9243                                     Value *FoundCondValue,
9244                                     bool Inverse) {
9245   if (!PendingLoopPredicates.insert(FoundCondValue).second)
9246     return false;
9247 
9248   auto ClearOnExit =
9249       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9250 
9251   // Recursively handle And and Or conditions.
9252   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9253     if (BO->getOpcode() == Instruction::And) {
9254       if (!Inverse)
9255         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9256                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9257     } else if (BO->getOpcode() == Instruction::Or) {
9258       if (Inverse)
9259         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9260                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9261     }
9262   }
9263 
9264   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9265   if (!ICI) return false;
9266 
9267   // Now that we found a conditional branch that dominates the loop or controls
9268   // the loop latch. Check to see if it is the comparison we are looking for.
9269   ICmpInst::Predicate FoundPred;
9270   if (Inverse)
9271     FoundPred = ICI->getInversePredicate();
9272   else
9273     FoundPred = ICI->getPredicate();
9274 
9275   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9276   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9277 
9278   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9279 }
9280 
9281 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9282                                     const SCEV *RHS,
9283                                     ICmpInst::Predicate FoundPred,
9284                                     const SCEV *FoundLHS,
9285                                     const SCEV *FoundRHS) {
9286   // Balance the types.
9287   if (getTypeSizeInBits(LHS->getType()) <
9288       getTypeSizeInBits(FoundLHS->getType())) {
9289     if (CmpInst::isSigned(Pred)) {
9290       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9291       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9292     } else {
9293       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9294       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9295     }
9296   } else if (getTypeSizeInBits(LHS->getType()) >
9297       getTypeSizeInBits(FoundLHS->getType())) {
9298     if (CmpInst::isSigned(FoundPred)) {
9299       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9300       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9301     } else {
9302       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9303       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9304     }
9305   }
9306 
9307   // Canonicalize the query to match the way instcombine will have
9308   // canonicalized the comparison.
9309   if (SimplifyICmpOperands(Pred, LHS, RHS))
9310     if (LHS == RHS)
9311       return CmpInst::isTrueWhenEqual(Pred);
9312   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9313     if (FoundLHS == FoundRHS)
9314       return CmpInst::isFalseWhenEqual(FoundPred);
9315 
9316   // Check to see if we can make the LHS or RHS match.
9317   if (LHS == FoundRHS || RHS == FoundLHS) {
9318     if (isa<SCEVConstant>(RHS)) {
9319       std::swap(FoundLHS, FoundRHS);
9320       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9321     } else {
9322       std::swap(LHS, RHS);
9323       Pred = ICmpInst::getSwappedPredicate(Pred);
9324     }
9325   }
9326 
9327   // Check whether the found predicate is the same as the desired predicate.
9328   if (FoundPred == Pred)
9329     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9330 
9331   // Check whether swapping the found predicate makes it the same as the
9332   // desired predicate.
9333   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9334     if (isa<SCEVConstant>(RHS))
9335       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9336     else
9337       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9338                                    RHS, LHS, FoundLHS, FoundRHS);
9339   }
9340 
9341   // Unsigned comparison is the same as signed comparison when both the operands
9342   // are non-negative.
9343   if (CmpInst::isUnsigned(FoundPred) &&
9344       CmpInst::getSignedPredicate(FoundPred) == Pred &&
9345       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9346     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9347 
9348   // Check if we can make progress by sharpening ranges.
9349   if (FoundPred == ICmpInst::ICMP_NE &&
9350       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9351 
9352     const SCEVConstant *C = nullptr;
9353     const SCEV *V = nullptr;
9354 
9355     if (isa<SCEVConstant>(FoundLHS)) {
9356       C = cast<SCEVConstant>(FoundLHS);
9357       V = FoundRHS;
9358     } else {
9359       C = cast<SCEVConstant>(FoundRHS);
9360       V = FoundLHS;
9361     }
9362 
9363     // The guarding predicate tells us that C != V. If the known range
9364     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
9365     // range we consider has to correspond to same signedness as the
9366     // predicate we're interested in folding.
9367 
9368     APInt Min = ICmpInst::isSigned(Pred) ?
9369         getSignedRangeMin(V) : getUnsignedRangeMin(V);
9370 
9371     if (Min == C->getAPInt()) {
9372       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9373       // This is true even if (Min + 1) wraps around -- in case of
9374       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9375 
9376       APInt SharperMin = Min + 1;
9377 
9378       switch (Pred) {
9379         case ICmpInst::ICMP_SGE:
9380         case ICmpInst::ICMP_UGE:
9381           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
9382           // RHS, we're done.
9383           if (isImpliedCondOperands(Pred, LHS, RHS, V,
9384                                     getConstant(SharperMin)))
9385             return true;
9386           LLVM_FALLTHROUGH;
9387 
9388         case ICmpInst::ICMP_SGT:
9389         case ICmpInst::ICMP_UGT:
9390           // We know from the range information that (V `Pred` Min ||
9391           // V == Min).  We know from the guarding condition that !(V
9392           // == Min).  This gives us
9393           //
9394           //       V `Pred` Min || V == Min && !(V == Min)
9395           //   =>  V `Pred` Min
9396           //
9397           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9398 
9399           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9400             return true;
9401           LLVM_FALLTHROUGH;
9402 
9403         default:
9404           // No change
9405           break;
9406       }
9407     }
9408   }
9409 
9410   // Check whether the actual condition is beyond sufficient.
9411   if (FoundPred == ICmpInst::ICMP_EQ)
9412     if (ICmpInst::isTrueWhenEqual(Pred))
9413       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9414         return true;
9415   if (Pred == ICmpInst::ICMP_NE)
9416     if (!ICmpInst::isTrueWhenEqual(FoundPred))
9417       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9418         return true;
9419 
9420   // Otherwise assume the worst.
9421   return false;
9422 }
9423 
9424 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9425                                      const SCEV *&L, const SCEV *&R,
9426                                      SCEV::NoWrapFlags &Flags) {
9427   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9428   if (!AE || AE->getNumOperands() != 2)
9429     return false;
9430 
9431   L = AE->getOperand(0);
9432   R = AE->getOperand(1);
9433   Flags = AE->getNoWrapFlags();
9434   return true;
9435 }
9436 
9437 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9438                                                            const SCEV *Less) {
9439   // We avoid subtracting expressions here because this function is usually
9440   // fairly deep in the call stack (i.e. is called many times).
9441 
9442   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9443     const auto *LAR = cast<SCEVAddRecExpr>(Less);
9444     const auto *MAR = cast<SCEVAddRecExpr>(More);
9445 
9446     if (LAR->getLoop() != MAR->getLoop())
9447       return None;
9448 
9449     // We look at affine expressions only; not for correctness but to keep
9450     // getStepRecurrence cheap.
9451     if (!LAR->isAffine() || !MAR->isAffine())
9452       return None;
9453 
9454     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9455       return None;
9456 
9457     Less = LAR->getStart();
9458     More = MAR->getStart();
9459 
9460     // fall through
9461   }
9462 
9463   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9464     const auto &M = cast<SCEVConstant>(More)->getAPInt();
9465     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9466     return M - L;
9467   }
9468 
9469   SCEV::NoWrapFlags Flags;
9470   const SCEV *LLess = nullptr, *RLess = nullptr;
9471   const SCEV *LMore = nullptr, *RMore = nullptr;
9472   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9473   // Compare (X + C1) vs X.
9474   if (splitBinaryAdd(Less, LLess, RLess, Flags))
9475     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9476       if (RLess == More)
9477         return -(C1->getAPInt());
9478 
9479   // Compare X vs (X + C2).
9480   if (splitBinaryAdd(More, LMore, RMore, Flags))
9481     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9482       if (RMore == Less)
9483         return C2->getAPInt();
9484 
9485   // Compare (X + C1) vs (X + C2).
9486   if (C1 && C2 && RLess == RMore)
9487     return C2->getAPInt() - C1->getAPInt();
9488 
9489   return None;
9490 }
9491 
9492 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9493     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9494     const SCEV *FoundLHS, const SCEV *FoundRHS) {
9495   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9496     return false;
9497 
9498   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9499   if (!AddRecLHS)
9500     return false;
9501 
9502   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9503   if (!AddRecFoundLHS)
9504     return false;
9505 
9506   // We'd like to let SCEV reason about control dependencies, so we constrain
9507   // both the inequalities to be about add recurrences on the same loop.  This
9508   // way we can use isLoopEntryGuardedByCond later.
9509 
9510   const Loop *L = AddRecFoundLHS->getLoop();
9511   if (L != AddRecLHS->getLoop())
9512     return false;
9513 
9514   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
9515   //
9516   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9517   //                                                                  ... (2)
9518   //
9519   // Informal proof for (2), assuming (1) [*]:
9520   //
9521   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9522   //
9523   // Then
9524   //
9525   //       FoundLHS s< FoundRHS s< INT_MIN - C
9526   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
9527   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9528   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
9529   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9530   // <=>  FoundLHS + C s< FoundRHS + C
9531   //
9532   // [*]: (1) can be proved by ruling out overflow.
9533   //
9534   // [**]: This can be proved by analyzing all the four possibilities:
9535   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9536   //    (A s>= 0, B s>= 0).
9537   //
9538   // Note:
9539   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9540   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
9541   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
9542   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
9543   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9544   // C)".
9545 
9546   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9547   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9548   if (!LDiff || !RDiff || *LDiff != *RDiff)
9549     return false;
9550 
9551   if (LDiff->isMinValue())
9552     return true;
9553 
9554   APInt FoundRHSLimit;
9555 
9556   if (Pred == CmpInst::ICMP_ULT) {
9557     FoundRHSLimit = -(*RDiff);
9558   } else {
9559     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9560     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9561   }
9562 
9563   // Try to prove (1) or (2), as needed.
9564   return isAvailableAtLoopEntry(FoundRHS, L) &&
9565          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9566                                   getConstant(FoundRHSLimit));
9567 }
9568 
9569 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9570                                         const SCEV *LHS, const SCEV *RHS,
9571                                         const SCEV *FoundLHS,
9572                                         const SCEV *FoundRHS, unsigned Depth) {
9573   const PHINode *LPhi = nullptr, *RPhi = nullptr;
9574 
9575   auto ClearOnExit = make_scope_exit([&]() {
9576     if (LPhi) {
9577       bool Erased = PendingMerges.erase(LPhi);
9578       assert(Erased && "Failed to erase LPhi!");
9579       (void)Erased;
9580     }
9581     if (RPhi) {
9582       bool Erased = PendingMerges.erase(RPhi);
9583       assert(Erased && "Failed to erase RPhi!");
9584       (void)Erased;
9585     }
9586   });
9587 
9588   // Find respective Phis and check that they are not being pending.
9589   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9590     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9591       if (!PendingMerges.insert(Phi).second)
9592         return false;
9593       LPhi = Phi;
9594     }
9595   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9596     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9597       // If we detect a loop of Phi nodes being processed by this method, for
9598       // example:
9599       //
9600       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9601       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9602       //
9603       // we don't want to deal with a case that complex, so return conservative
9604       // answer false.
9605       if (!PendingMerges.insert(Phi).second)
9606         return false;
9607       RPhi = Phi;
9608     }
9609 
9610   // If none of LHS, RHS is a Phi, nothing to do here.
9611   if (!LPhi && !RPhi)
9612     return false;
9613 
9614   // If there is a SCEVUnknown Phi we are interested in, make it left.
9615   if (!LPhi) {
9616     std::swap(LHS, RHS);
9617     std::swap(FoundLHS, FoundRHS);
9618     std::swap(LPhi, RPhi);
9619     Pred = ICmpInst::getSwappedPredicate(Pred);
9620   }
9621 
9622   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
9623   const BasicBlock *LBB = LPhi->getParent();
9624   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9625 
9626   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
9627     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
9628            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
9629            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
9630   };
9631 
9632   if (RPhi && RPhi->getParent() == LBB) {
9633     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
9634     // If we compare two Phis from the same block, and for each entry block
9635     // the predicate is true for incoming values from this block, then the
9636     // predicate is also true for the Phis.
9637     for (const BasicBlock *IncBB : predecessors(LBB)) {
9638       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9639       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
9640       if (!ProvedEasily(L, R))
9641         return false;
9642     }
9643   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
9644     // Case two: RHS is also a Phi from the same basic block, and it is an
9645     // AddRec. It means that there is a loop which has both AddRec and Unknown
9646     // PHIs, for it we can compare incoming values of AddRec from above the loop
9647     // and latch with their respective incoming values of LPhi.
9648     assert(LPhi->getNumIncomingValues() == 2 &&
9649            "Phi node standing in loop header does not have exactly 2 inputs?");
9650     auto *RLoop = RAR->getLoop();
9651     auto *Predecessor = RLoop->getLoopPredecessor();
9652     assert(Predecessor && "Loop with AddRec with no predecessor?");
9653     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
9654     if (!ProvedEasily(L1, RAR->getStart()))
9655       return false;
9656     auto *Latch = RLoop->getLoopLatch();
9657     assert(Latch && "Loop with AddRec with no latch?");
9658     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
9659     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
9660       return false;
9661   } else {
9662     // In all other cases go over inputs of LHS and compare each of them to RHS,
9663     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
9664     // At this point RHS is either a non-Phi, or it is a Phi from some block
9665     // different from LBB.
9666     for (const BasicBlock *IncBB : predecessors(LBB)) {
9667       // Check that RHS is available in this block.
9668       if (!dominates(RHS, IncBB))
9669         return false;
9670       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9671       if (!ProvedEasily(L, RHS))
9672         return false;
9673     }
9674   }
9675   return true;
9676 }
9677 
9678 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
9679                                             const SCEV *LHS, const SCEV *RHS,
9680                                             const SCEV *FoundLHS,
9681                                             const SCEV *FoundRHS) {
9682   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
9683     return true;
9684 
9685   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
9686     return true;
9687 
9688   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
9689                                      FoundLHS, FoundRHS) ||
9690          // ~x < ~y --> x > y
9691          isImpliedCondOperandsHelper(Pred, LHS, RHS,
9692                                      getNotSCEV(FoundRHS),
9693                                      getNotSCEV(FoundLHS));
9694 }
9695 
9696 /// If Expr computes ~A, return A else return nullptr
9697 static const SCEV *MatchNotExpr(const SCEV *Expr) {
9698   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
9699   if (!Add || Add->getNumOperands() != 2 ||
9700       !Add->getOperand(0)->isAllOnesValue())
9701     return nullptr;
9702 
9703   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
9704   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
9705       !AddRHS->getOperand(0)->isAllOnesValue())
9706     return nullptr;
9707 
9708   return AddRHS->getOperand(1);
9709 }
9710 
9711 /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
9712 template<typename MaxExprType>
9713 static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
9714                               const SCEV *Candidate) {
9715   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
9716   if (!MaxExpr) return false;
9717 
9718   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
9719 }
9720 
9721 /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
9722 template<typename MaxExprType>
9723 static bool IsMinConsistingOf(ScalarEvolution &SE,
9724                               const SCEV *MaybeMinExpr,
9725                               const SCEV *Candidate) {
9726   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
9727   if (!MaybeMaxExpr)
9728     return false;
9729 
9730   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
9731 }
9732 
9733 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
9734                                            ICmpInst::Predicate Pred,
9735                                            const SCEV *LHS, const SCEV *RHS) {
9736   // If both sides are affine addrecs for the same loop, with equal
9737   // steps, and we know the recurrences don't wrap, then we only
9738   // need to check the predicate on the starting values.
9739 
9740   if (!ICmpInst::isRelational(Pred))
9741     return false;
9742 
9743   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
9744   if (!LAR)
9745     return false;
9746   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9747   if (!RAR)
9748     return false;
9749   if (LAR->getLoop() != RAR->getLoop())
9750     return false;
9751   if (!LAR->isAffine() || !RAR->isAffine())
9752     return false;
9753 
9754   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
9755     return false;
9756 
9757   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
9758                          SCEV::FlagNSW : SCEV::FlagNUW;
9759   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
9760     return false;
9761 
9762   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
9763 }
9764 
9765 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
9766 /// expression?
9767 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
9768                                         ICmpInst::Predicate Pred,
9769                                         const SCEV *LHS, const SCEV *RHS) {
9770   switch (Pred) {
9771   default:
9772     return false;
9773 
9774   case ICmpInst::ICMP_SGE:
9775     std::swap(LHS, RHS);
9776     LLVM_FALLTHROUGH;
9777   case ICmpInst::ICMP_SLE:
9778     return
9779       // min(A, ...) <= A
9780       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
9781       // A <= max(A, ...)
9782       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
9783 
9784   case ICmpInst::ICMP_UGE:
9785     std::swap(LHS, RHS);
9786     LLVM_FALLTHROUGH;
9787   case ICmpInst::ICMP_ULE:
9788     return
9789       // min(A, ...) <= A
9790       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
9791       // A <= max(A, ...)
9792       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
9793   }
9794 
9795   llvm_unreachable("covered switch fell through?!");
9796 }
9797 
9798 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
9799                                              const SCEV *LHS, const SCEV *RHS,
9800                                              const SCEV *FoundLHS,
9801                                              const SCEV *FoundRHS,
9802                                              unsigned Depth) {
9803   assert(getTypeSizeInBits(LHS->getType()) ==
9804              getTypeSizeInBits(RHS->getType()) &&
9805          "LHS and RHS have different sizes?");
9806   assert(getTypeSizeInBits(FoundLHS->getType()) ==
9807              getTypeSizeInBits(FoundRHS->getType()) &&
9808          "FoundLHS and FoundRHS have different sizes?");
9809   // We want to avoid hurting the compile time with analysis of too big trees.
9810   if (Depth > MaxSCEVOperationsImplicationDepth)
9811     return false;
9812   // We only want to work with ICMP_SGT comparison so far.
9813   // TODO: Extend to ICMP_UGT?
9814   if (Pred == ICmpInst::ICMP_SLT) {
9815     Pred = ICmpInst::ICMP_SGT;
9816     std::swap(LHS, RHS);
9817     std::swap(FoundLHS, FoundRHS);
9818   }
9819   if (Pred != ICmpInst::ICMP_SGT)
9820     return false;
9821 
9822   auto GetOpFromSExt = [&](const SCEV *S) {
9823     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
9824       return Ext->getOperand();
9825     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
9826     // the constant in some cases.
9827     return S;
9828   };
9829 
9830   // Acquire values from extensions.
9831   auto *OrigLHS = LHS;
9832   auto *OrigFoundLHS = FoundLHS;
9833   LHS = GetOpFromSExt(LHS);
9834   FoundLHS = GetOpFromSExt(FoundLHS);
9835 
9836   // Is the SGT predicate can be proved trivially or using the found context.
9837   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
9838     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
9839            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
9840                                   FoundRHS, Depth + 1);
9841   };
9842 
9843   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
9844     // We want to avoid creation of any new non-constant SCEV. Since we are
9845     // going to compare the operands to RHS, we should be certain that we don't
9846     // need any size extensions for this. So let's decline all cases when the
9847     // sizes of types of LHS and RHS do not match.
9848     // TODO: Maybe try to get RHS from sext to catch more cases?
9849     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
9850       return false;
9851 
9852     // Should not overflow.
9853     if (!LHSAddExpr->hasNoSignedWrap())
9854       return false;
9855 
9856     auto *LL = LHSAddExpr->getOperand(0);
9857     auto *LR = LHSAddExpr->getOperand(1);
9858     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
9859 
9860     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
9861     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
9862       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
9863     };
9864     // Try to prove the following rule:
9865     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
9866     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
9867     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
9868       return true;
9869   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
9870     Value *LL, *LR;
9871     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
9872 
9873     using namespace llvm::PatternMatch;
9874 
9875     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
9876       // Rules for division.
9877       // We are going to perform some comparisons with Denominator and its
9878       // derivative expressions. In general case, creating a SCEV for it may
9879       // lead to a complex analysis of the entire graph, and in particular it
9880       // can request trip count recalculation for the same loop. This would
9881       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
9882       // this, we only want to create SCEVs that are constants in this section.
9883       // So we bail if Denominator is not a constant.
9884       if (!isa<ConstantInt>(LR))
9885         return false;
9886 
9887       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
9888 
9889       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
9890       // then a SCEV for the numerator already exists and matches with FoundLHS.
9891       auto *Numerator = getExistingSCEV(LL);
9892       if (!Numerator || Numerator->getType() != FoundLHS->getType())
9893         return false;
9894 
9895       // Make sure that the numerator matches with FoundLHS and the denominator
9896       // is positive.
9897       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
9898         return false;
9899 
9900       auto *DTy = Denominator->getType();
9901       auto *FRHSTy = FoundRHS->getType();
9902       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
9903         // One of types is a pointer and another one is not. We cannot extend
9904         // them properly to a wider type, so let us just reject this case.
9905         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
9906         // to avoid this check.
9907         return false;
9908 
9909       // Given that:
9910       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
9911       auto *WTy = getWiderType(DTy, FRHSTy);
9912       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
9913       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
9914 
9915       // Try to prove the following rule:
9916       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
9917       // For example, given that FoundLHS > 2. It means that FoundLHS is at
9918       // least 3. If we divide it by Denominator < 4, we will have at least 1.
9919       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
9920       if (isKnownNonPositive(RHS) &&
9921           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
9922         return true;
9923 
9924       // Try to prove the following rule:
9925       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
9926       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
9927       // If we divide it by Denominator > 2, then:
9928       // 1. If FoundLHS is negative, then the result is 0.
9929       // 2. If FoundLHS is non-negative, then the result is non-negative.
9930       // Anyways, the result is non-negative.
9931       auto *MinusOne = getNegativeSCEV(getOne(WTy));
9932       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
9933       if (isKnownNegative(RHS) &&
9934           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
9935         return true;
9936     }
9937   }
9938 
9939   // If our expression contained SCEVUnknown Phis, and we split it down and now
9940   // need to prove something for them, try to prove the predicate for every
9941   // possible incoming values of those Phis.
9942   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
9943     return true;
9944 
9945   return false;
9946 }
9947 
9948 bool
9949 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
9950                                            const SCEV *LHS, const SCEV *RHS) {
9951   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
9952          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
9953          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
9954          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
9955 }
9956 
9957 bool
9958 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
9959                                              const SCEV *LHS, const SCEV *RHS,
9960                                              const SCEV *FoundLHS,
9961                                              const SCEV *FoundRHS) {
9962   switch (Pred) {
9963   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
9964   case ICmpInst::ICMP_EQ:
9965   case ICmpInst::ICMP_NE:
9966     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
9967       return true;
9968     break;
9969   case ICmpInst::ICMP_SLT:
9970   case ICmpInst::ICMP_SLE:
9971     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
9972         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
9973       return true;
9974     break;
9975   case ICmpInst::ICMP_SGT:
9976   case ICmpInst::ICMP_SGE:
9977     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
9978         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
9979       return true;
9980     break;
9981   case ICmpInst::ICMP_ULT:
9982   case ICmpInst::ICMP_ULE:
9983     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
9984         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
9985       return true;
9986     break;
9987   case ICmpInst::ICMP_UGT:
9988   case ICmpInst::ICMP_UGE:
9989     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
9990         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
9991       return true;
9992     break;
9993   }
9994 
9995   // Maybe it can be proved via operations?
9996   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
9997     return true;
9998 
9999   return false;
10000 }
10001 
10002 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10003                                                      const SCEV *LHS,
10004                                                      const SCEV *RHS,
10005                                                      const SCEV *FoundLHS,
10006                                                      const SCEV *FoundRHS) {
10007   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10008     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10009     // reduce the compile time impact of this optimization.
10010     return false;
10011 
10012   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10013   if (!Addend)
10014     return false;
10015 
10016   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10017 
10018   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10019   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10020   ConstantRange FoundLHSRange =
10021       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10022 
10023   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10024   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10025 
10026   // We can also compute the range of values for `LHS` that satisfy the
10027   // consequent, "`LHS` `Pred` `RHS`":
10028   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10029   ConstantRange SatisfyingLHSRange =
10030       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10031 
10032   // The antecedent implies the consequent if every value of `LHS` that
10033   // satisfies the antecedent also satisfies the consequent.
10034   return SatisfyingLHSRange.contains(LHSRange);
10035 }
10036 
10037 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10038                                          bool IsSigned, bool NoWrap) {
10039   assert(isKnownPositive(Stride) && "Positive stride expected!");
10040 
10041   if (NoWrap) return false;
10042 
10043   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10044   const SCEV *One = getOne(Stride->getType());
10045 
10046   if (IsSigned) {
10047     APInt MaxRHS = getSignedRangeMax(RHS);
10048     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10049     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10050 
10051     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10052     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10053   }
10054 
10055   APInt MaxRHS = getUnsignedRangeMax(RHS);
10056   APInt MaxValue = APInt::getMaxValue(BitWidth);
10057   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10058 
10059   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10060   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10061 }
10062 
10063 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10064                                          bool IsSigned, bool NoWrap) {
10065   if (NoWrap) return false;
10066 
10067   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10068   const SCEV *One = getOne(Stride->getType());
10069 
10070   if (IsSigned) {
10071     APInt MinRHS = getSignedRangeMin(RHS);
10072     APInt MinValue = APInt::getSignedMinValue(BitWidth);
10073     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10074 
10075     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10076     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10077   }
10078 
10079   APInt MinRHS = getUnsignedRangeMin(RHS);
10080   APInt MinValue = APInt::getMinValue(BitWidth);
10081   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10082 
10083   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10084   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10085 }
10086 
10087 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10088                                             bool Equality) {
10089   const SCEV *One = getOne(Step->getType());
10090   Delta = Equality ? getAddExpr(Delta, Step)
10091                    : getAddExpr(Delta, getMinusSCEV(Step, One));
10092   return getUDivExpr(Delta, Step);
10093 }
10094 
10095 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10096                                                     const SCEV *Stride,
10097                                                     const SCEV *End,
10098                                                     unsigned BitWidth,
10099                                                     bool IsSigned) {
10100 
10101   assert(!isKnownNonPositive(Stride) &&
10102          "Stride is expected strictly positive!");
10103   // Calculate the maximum backedge count based on the range of values
10104   // permitted by Start, End, and Stride.
10105   const SCEV *MaxBECount;
10106   APInt MinStart =
10107       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10108 
10109   APInt StrideForMaxBECount =
10110       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10111 
10112   // We already know that the stride is positive, so we paper over conservatism
10113   // in our range computation by forcing StrideForMaxBECount to be at least one.
10114   // In theory this is unnecessary, but we expect MaxBECount to be a
10115   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10116   // is nothing to constant fold it to).
10117   APInt One(BitWidth, 1, IsSigned);
10118   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10119 
10120   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10121                             : APInt::getMaxValue(BitWidth);
10122   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10123 
10124   // Although End can be a MAX expression we estimate MaxEnd considering only
10125   // the case End = RHS of the loop termination condition. This is safe because
10126   // in the other case (End - Start) is zero, leading to a zero maximum backedge
10127   // taken count.
10128   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10129                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10130 
10131   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10132                               getConstant(StrideForMaxBECount) /* Step */,
10133                               false /* Equality */);
10134 
10135   return MaxBECount;
10136 }
10137 
10138 ScalarEvolution::ExitLimit
10139 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10140                                   const Loop *L, bool IsSigned,
10141                                   bool ControlsExit, bool AllowPredicates) {
10142   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10143 
10144   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10145   bool PredicatedIV = false;
10146 
10147   if (!IV && AllowPredicates) {
10148     // Try to make this an AddRec using runtime tests, in the first X
10149     // iterations of this loop, where X is the SCEV expression found by the
10150     // algorithm below.
10151     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10152     PredicatedIV = true;
10153   }
10154 
10155   // Avoid weird loops
10156   if (!IV || IV->getLoop() != L || !IV->isAffine())
10157     return getCouldNotCompute();
10158 
10159   bool NoWrap = ControlsExit &&
10160                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10161 
10162   const SCEV *Stride = IV->getStepRecurrence(*this);
10163 
10164   bool PositiveStride = isKnownPositive(Stride);
10165 
10166   // Avoid negative or zero stride values.
10167   if (!PositiveStride) {
10168     // We can compute the correct backedge taken count for loops with unknown
10169     // strides if we can prove that the loop is not an infinite loop with side
10170     // effects. Here's the loop structure we are trying to handle -
10171     //
10172     // i = start
10173     // do {
10174     //   A[i] = i;
10175     //   i += s;
10176     // } while (i < end);
10177     //
10178     // The backedge taken count for such loops is evaluated as -
10179     // (max(end, start + stride) - start - 1) /u stride
10180     //
10181     // The additional preconditions that we need to check to prove correctness
10182     // of the above formula is as follows -
10183     //
10184     // a) IV is either nuw or nsw depending upon signedness (indicated by the
10185     //    NoWrap flag).
10186     // b) loop is single exit with no side effects.
10187     //
10188     //
10189     // Precondition a) implies that if the stride is negative, this is a single
10190     // trip loop. The backedge taken count formula reduces to zero in this case.
10191     //
10192     // Precondition b) implies that the unknown stride cannot be zero otherwise
10193     // we have UB.
10194     //
10195     // The positive stride case is the same as isKnownPositive(Stride) returning
10196     // true (original behavior of the function).
10197     //
10198     // We want to make sure that the stride is truly unknown as there are edge
10199     // cases where ScalarEvolution propagates no wrap flags to the
10200     // post-increment/decrement IV even though the increment/decrement operation
10201     // itself is wrapping. The computed backedge taken count may be wrong in
10202     // such cases. This is prevented by checking that the stride is not known to
10203     // be either positive or non-positive. For example, no wrap flags are
10204     // propagated to the post-increment IV of this loop with a trip count of 2 -
10205     //
10206     // unsigned char i;
10207     // for(i=127; i<128; i+=129)
10208     //   A[i] = i;
10209     //
10210     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10211         !loopHasNoSideEffects(L))
10212       return getCouldNotCompute();
10213   } else if (!Stride->isOne() &&
10214              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10215     // Avoid proven overflow cases: this will ensure that the backedge taken
10216     // count will not generate any unsigned overflow. Relaxed no-overflow
10217     // conditions exploit NoWrapFlags, allowing to optimize in presence of
10218     // undefined behaviors like the case of C language.
10219     return getCouldNotCompute();
10220 
10221   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10222                                       : ICmpInst::ICMP_ULT;
10223   const SCEV *Start = IV->getStart();
10224   const SCEV *End = RHS;
10225   // When the RHS is not invariant, we do not know the end bound of the loop and
10226   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10227   // calculate the MaxBECount, given the start, stride and max value for the end
10228   // bound of the loop (RHS), and the fact that IV does not overflow (which is
10229   // checked above).
10230   if (!isLoopInvariant(RHS, L)) {
10231     const SCEV *MaxBECount = computeMaxBECountForLT(
10232         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10233     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10234                      false /*MaxOrZero*/, Predicates);
10235   }
10236   // If the backedge is taken at least once, then it will be taken
10237   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10238   // is the LHS value of the less-than comparison the first time it is evaluated
10239   // and End is the RHS.
10240   const SCEV *BECountIfBackedgeTaken =
10241     computeBECount(getMinusSCEV(End, Start), Stride, false);
10242   // If the loop entry is guarded by the result of the backedge test of the
10243   // first loop iteration, then we know the backedge will be taken at least
10244   // once and so the backedge taken count is as above. If not then we use the
10245   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10246   // as if the backedge is taken at least once max(End,Start) is End and so the
10247   // result is as above, and if not max(End,Start) is Start so we get a backedge
10248   // count of zero.
10249   const SCEV *BECount;
10250   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10251     BECount = BECountIfBackedgeTaken;
10252   else {
10253     End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10254     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10255   }
10256 
10257   const SCEV *MaxBECount;
10258   bool MaxOrZero = false;
10259   if (isa<SCEVConstant>(BECount))
10260     MaxBECount = BECount;
10261   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10262     // If we know exactly how many times the backedge will be taken if it's
10263     // taken at least once, then the backedge count will either be that or
10264     // zero.
10265     MaxBECount = BECountIfBackedgeTaken;
10266     MaxOrZero = true;
10267   } else {
10268     MaxBECount = computeMaxBECountForLT(
10269         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10270   }
10271 
10272   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10273       !isa<SCEVCouldNotCompute>(BECount))
10274     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10275 
10276   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10277 }
10278 
10279 ScalarEvolution::ExitLimit
10280 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10281                                      const Loop *L, bool IsSigned,
10282                                      bool ControlsExit, bool AllowPredicates) {
10283   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10284   // We handle only IV > Invariant
10285   if (!isLoopInvariant(RHS, L))
10286     return getCouldNotCompute();
10287 
10288   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10289   if (!IV && AllowPredicates)
10290     // Try to make this an AddRec using runtime tests, in the first X
10291     // iterations of this loop, where X is the SCEV expression found by the
10292     // algorithm below.
10293     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10294 
10295   // Avoid weird loops
10296   if (!IV || IV->getLoop() != L || !IV->isAffine())
10297     return getCouldNotCompute();
10298 
10299   bool NoWrap = ControlsExit &&
10300                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10301 
10302   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10303 
10304   // Avoid negative or zero stride values
10305   if (!isKnownPositive(Stride))
10306     return getCouldNotCompute();
10307 
10308   // Avoid proven overflow cases: this will ensure that the backedge taken count
10309   // will not generate any unsigned overflow. Relaxed no-overflow conditions
10310   // exploit NoWrapFlags, allowing to optimize in presence of undefined
10311   // behaviors like the case of C language.
10312   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10313     return getCouldNotCompute();
10314 
10315   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10316                                       : ICmpInst::ICMP_UGT;
10317 
10318   const SCEV *Start = IV->getStart();
10319   const SCEV *End = RHS;
10320   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10321     End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10322 
10323   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10324 
10325   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10326                             : getUnsignedRangeMax(Start);
10327 
10328   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10329                              : getUnsignedRangeMin(Stride);
10330 
10331   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10332   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10333                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
10334 
10335   // Although End can be a MIN expression we estimate MinEnd considering only
10336   // the case End = RHS. This is safe because in the other case (Start - End)
10337   // is zero, leading to a zero maximum backedge taken count.
10338   APInt MinEnd =
10339     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10340              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10341 
10342 
10343   const SCEV *MaxBECount = getCouldNotCompute();
10344   if (isa<SCEVConstant>(BECount))
10345     MaxBECount = BECount;
10346   else
10347     MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
10348                                 getConstant(MinStride), false);
10349 
10350   if (isa<SCEVCouldNotCompute>(MaxBECount))
10351     MaxBECount = BECount;
10352 
10353   return ExitLimit(BECount, MaxBECount, false, Predicates);
10354 }
10355 
10356 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10357                                                     ScalarEvolution &SE) const {
10358   if (Range.isFullSet())  // Infinite loop.
10359     return SE.getCouldNotCompute();
10360 
10361   // If the start is a non-zero constant, shift the range to simplify things.
10362   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10363     if (!SC->getValue()->isZero()) {
10364       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10365       Operands[0] = SE.getZero(SC->getType());
10366       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10367                                              getNoWrapFlags(FlagNW));
10368       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10369         return ShiftedAddRec->getNumIterationsInRange(
10370             Range.subtract(SC->getAPInt()), SE);
10371       // This is strange and shouldn't happen.
10372       return SE.getCouldNotCompute();
10373     }
10374 
10375   // The only time we can solve this is when we have all constant indices.
10376   // Otherwise, we cannot determine the overflow conditions.
10377   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10378     return SE.getCouldNotCompute();
10379 
10380   // Okay at this point we know that all elements of the chrec are constants and
10381   // that the start element is zero.
10382 
10383   // First check to see if the range contains zero.  If not, the first
10384   // iteration exits.
10385   unsigned BitWidth = SE.getTypeSizeInBits(getType());
10386   if (!Range.contains(APInt(BitWidth, 0)))
10387     return SE.getZero(getType());
10388 
10389   if (isAffine()) {
10390     // If this is an affine expression then we have this situation:
10391     //   Solve {0,+,A} in Range  ===  Ax in Range
10392 
10393     // We know that zero is in the range.  If A is positive then we know that
10394     // the upper value of the range must be the first possible exit value.
10395     // If A is negative then the lower of the range is the last possible loop
10396     // value.  Also note that we already checked for a full range.
10397     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10398     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10399 
10400     // The exit value should be (End+A)/A.
10401     APInt ExitVal = (End + A).udiv(A);
10402     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10403 
10404     // Evaluate at the exit value.  If we really did fall out of the valid
10405     // range, then we computed our trip count, otherwise wrap around or other
10406     // things must have happened.
10407     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10408     if (Range.contains(Val->getValue()))
10409       return SE.getCouldNotCompute();  // Something strange happened
10410 
10411     // Ensure that the previous value is in the range.  This is a sanity check.
10412     assert(Range.contains(
10413            EvaluateConstantChrecAtConstant(this,
10414            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10415            "Linear scev computation is off in a bad way!");
10416     return SE.getConstant(ExitValue);
10417   } else if (isQuadratic()) {
10418     // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
10419     // quadratic equation to solve it.  To do this, we must frame our problem in
10420     // terms of figuring out when zero is crossed, instead of when
10421     // Range.getUpper() is crossed.
10422     SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
10423     NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
10424     const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap);
10425 
10426     // Next, solve the constructed addrec
10427     if (auto Roots =
10428             SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) {
10429       const SCEVConstant *R1 = Roots->first;
10430       const SCEVConstant *R2 = Roots->second;
10431       // Pick the smallest positive root value.
10432       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
10433               ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
10434         if (!CB->getZExtValue())
10435           std::swap(R1, R2); // R1 is the minimum root now.
10436 
10437         // Make sure the root is not off by one.  The returned iteration should
10438         // not be in the range, but the previous one should be.  When solving
10439         // for "X*X < 5", for example, we should not return a root of 2.
10440         ConstantInt *R1Val =
10441             EvaluateConstantChrecAtConstant(this, R1->getValue(), SE);
10442         if (Range.contains(R1Val->getValue())) {
10443           // The next iteration must be out of the range...
10444           ConstantInt *NextVal =
10445               ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
10446 
10447           R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10448           if (!Range.contains(R1Val->getValue()))
10449             return SE.getConstant(NextVal);
10450           return SE.getCouldNotCompute(); // Something strange happened
10451         }
10452 
10453         // If R1 was not in the range, then it is a good return value.  Make
10454         // sure that R1-1 WAS in the range though, just in case.
10455         ConstantInt *NextVal =
10456             ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
10457         R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
10458         if (Range.contains(R1Val->getValue()))
10459           return R1;
10460         return SE.getCouldNotCompute(); // Something strange happened
10461       }
10462     }
10463   }
10464 
10465   return SE.getCouldNotCompute();
10466 }
10467 
10468 const SCEVAddRecExpr *
10469 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10470   assert(getNumOperands() > 1 && "AddRec with zero step?");
10471   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10472   // but in this case we cannot guarantee that the value returned will be an
10473   // AddRec because SCEV does not have a fixed point where it stops
10474   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10475   // may happen if we reach arithmetic depth limit while simplifying. So we
10476   // construct the returned value explicitly.
10477   SmallVector<const SCEV *, 3> Ops;
10478   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10479   // (this + Step) is {A+B,+,B+C,+...,+,N}.
10480   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10481     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10482   // We know that the last operand is not a constant zero (otherwise it would
10483   // have been popped out earlier). This guarantees us that if the result has
10484   // the same last operand, then it will also not be popped out, meaning that
10485   // the returned value will be an AddRec.
10486   const SCEV *Last = getOperand(getNumOperands() - 1);
10487   assert(!Last->isZero() && "Recurrency with zero step?");
10488   Ops.push_back(Last);
10489   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10490                                                SCEV::FlagAnyWrap));
10491 }
10492 
10493 // Return true when S contains at least an undef value.
10494 static inline bool containsUndefs(const SCEV *S) {
10495   return SCEVExprContains(S, [](const SCEV *S) {
10496     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10497       return isa<UndefValue>(SU->getValue());
10498     else if (const auto *SC = dyn_cast<SCEVConstant>(S))
10499       return isa<UndefValue>(SC->getValue());
10500     return false;
10501   });
10502 }
10503 
10504 namespace {
10505 
10506 // Collect all steps of SCEV expressions.
10507 struct SCEVCollectStrides {
10508   ScalarEvolution &SE;
10509   SmallVectorImpl<const SCEV *> &Strides;
10510 
10511   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10512       : SE(SE), Strides(S) {}
10513 
10514   bool follow(const SCEV *S) {
10515     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10516       Strides.push_back(AR->getStepRecurrence(SE));
10517     return true;
10518   }
10519 
10520   bool isDone() const { return false; }
10521 };
10522 
10523 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10524 struct SCEVCollectTerms {
10525   SmallVectorImpl<const SCEV *> &Terms;
10526 
10527   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10528 
10529   bool follow(const SCEV *S) {
10530     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10531         isa<SCEVSignExtendExpr>(S)) {
10532       if (!containsUndefs(S))
10533         Terms.push_back(S);
10534 
10535       // Stop recursion: once we collected a term, do not walk its operands.
10536       return false;
10537     }
10538 
10539     // Keep looking.
10540     return true;
10541   }
10542 
10543   bool isDone() const { return false; }
10544 };
10545 
10546 // Check if a SCEV contains an AddRecExpr.
10547 struct SCEVHasAddRec {
10548   bool &ContainsAddRec;
10549 
10550   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10551     ContainsAddRec = false;
10552   }
10553 
10554   bool follow(const SCEV *S) {
10555     if (isa<SCEVAddRecExpr>(S)) {
10556       ContainsAddRec = true;
10557 
10558       // Stop recursion: once we collected a term, do not walk its operands.
10559       return false;
10560     }
10561 
10562     // Keep looking.
10563     return true;
10564   }
10565 
10566   bool isDone() const { return false; }
10567 };
10568 
10569 // Find factors that are multiplied with an expression that (possibly as a
10570 // subexpression) contains an AddRecExpr. In the expression:
10571 //
10572 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
10573 //
10574 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10575 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10576 // parameters as they form a product with an induction variable.
10577 //
10578 // This collector expects all array size parameters to be in the same MulExpr.
10579 // It might be necessary to later add support for collecting parameters that are
10580 // spread over different nested MulExpr.
10581 struct SCEVCollectAddRecMultiplies {
10582   SmallVectorImpl<const SCEV *> &Terms;
10583   ScalarEvolution &SE;
10584 
10585   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10586       : Terms(T), SE(SE) {}
10587 
10588   bool follow(const SCEV *S) {
10589     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10590       bool HasAddRec = false;
10591       SmallVector<const SCEV *, 0> Operands;
10592       for (auto Op : Mul->operands()) {
10593         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10594         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10595           Operands.push_back(Op);
10596         } else if (Unknown) {
10597           HasAddRec = true;
10598         } else {
10599           bool ContainsAddRec;
10600           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10601           visitAll(Op, ContiansAddRec);
10602           HasAddRec |= ContainsAddRec;
10603         }
10604       }
10605       if (Operands.size() == 0)
10606         return true;
10607 
10608       if (!HasAddRec)
10609         return false;
10610 
10611       Terms.push_back(SE.getMulExpr(Operands));
10612       // Stop recursion: once we collected a term, do not walk its operands.
10613       return false;
10614     }
10615 
10616     // Keep looking.
10617     return true;
10618   }
10619 
10620   bool isDone() const { return false; }
10621 };
10622 
10623 } // end anonymous namespace
10624 
10625 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10626 /// two places:
10627 ///   1) The strides of AddRec expressions.
10628 ///   2) Unknowns that are multiplied with AddRec expressions.
10629 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10630     SmallVectorImpl<const SCEV *> &Terms) {
10631   SmallVector<const SCEV *, 4> Strides;
10632   SCEVCollectStrides StrideCollector(*this, Strides);
10633   visitAll(Expr, StrideCollector);
10634 
10635   DEBUG({
10636       dbgs() << "Strides:\n";
10637       for (const SCEV *S : Strides)
10638         dbgs() << *S << "\n";
10639     });
10640 
10641   for (const SCEV *S : Strides) {
10642     SCEVCollectTerms TermCollector(Terms);
10643     visitAll(S, TermCollector);
10644   }
10645 
10646   DEBUG({
10647       dbgs() << "Terms:\n";
10648       for (const SCEV *T : Terms)
10649         dbgs() << *T << "\n";
10650     });
10651 
10652   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
10653   visitAll(Expr, MulCollector);
10654 }
10655 
10656 static bool findArrayDimensionsRec(ScalarEvolution &SE,
10657                                    SmallVectorImpl<const SCEV *> &Terms,
10658                                    SmallVectorImpl<const SCEV *> &Sizes) {
10659   int Last = Terms.size() - 1;
10660   const SCEV *Step = Terms[Last];
10661 
10662   // End of recursion.
10663   if (Last == 0) {
10664     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
10665       SmallVector<const SCEV *, 2> Qs;
10666       for (const SCEV *Op : M->operands())
10667         if (!isa<SCEVConstant>(Op))
10668           Qs.push_back(Op);
10669 
10670       Step = SE.getMulExpr(Qs);
10671     }
10672 
10673     Sizes.push_back(Step);
10674     return true;
10675   }
10676 
10677   for (const SCEV *&Term : Terms) {
10678     // Normalize the terms before the next call to findArrayDimensionsRec.
10679     const SCEV *Q, *R;
10680     SCEVDivision::divide(SE, Term, Step, &Q, &R);
10681 
10682     // Bail out when GCD does not evenly divide one of the terms.
10683     if (!R->isZero())
10684       return false;
10685 
10686     Term = Q;
10687   }
10688 
10689   // Remove all SCEVConstants.
10690   Terms.erase(
10691       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
10692       Terms.end());
10693 
10694   if (Terms.size() > 0)
10695     if (!findArrayDimensionsRec(SE, Terms, Sizes))
10696       return false;
10697 
10698   Sizes.push_back(Step);
10699   return true;
10700 }
10701 
10702 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
10703 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
10704   for (const SCEV *T : Terms)
10705     if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
10706       return true;
10707   return false;
10708 }
10709 
10710 // Return the number of product terms in S.
10711 static inline int numberOfTerms(const SCEV *S) {
10712   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
10713     return Expr->getNumOperands();
10714   return 1;
10715 }
10716 
10717 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
10718   if (isa<SCEVConstant>(T))
10719     return nullptr;
10720 
10721   if (isa<SCEVUnknown>(T))
10722     return T;
10723 
10724   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
10725     SmallVector<const SCEV *, 2> Factors;
10726     for (const SCEV *Op : M->operands())
10727       if (!isa<SCEVConstant>(Op))
10728         Factors.push_back(Op);
10729 
10730     return SE.getMulExpr(Factors);
10731   }
10732 
10733   return T;
10734 }
10735 
10736 /// Return the size of an element read or written by Inst.
10737 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
10738   Type *Ty;
10739   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
10740     Ty = Store->getValueOperand()->getType();
10741   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
10742     Ty = Load->getType();
10743   else
10744     return nullptr;
10745 
10746   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
10747   return getSizeOfExpr(ETy, Ty);
10748 }
10749 
10750 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
10751                                           SmallVectorImpl<const SCEV *> &Sizes,
10752                                           const SCEV *ElementSize) {
10753   if (Terms.size() < 1 || !ElementSize)
10754     return;
10755 
10756   // Early return when Terms do not contain parameters: we do not delinearize
10757   // non parametric SCEVs.
10758   if (!containsParameters(Terms))
10759     return;
10760 
10761   DEBUG({
10762       dbgs() << "Terms:\n";
10763       for (const SCEV *T : Terms)
10764         dbgs() << *T << "\n";
10765     });
10766 
10767   // Remove duplicates.
10768   array_pod_sort(Terms.begin(), Terms.end());
10769   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
10770 
10771   // Put larger terms first.
10772   llvm::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
10773     return numberOfTerms(LHS) > numberOfTerms(RHS);
10774   });
10775 
10776   // Try to divide all terms by the element size. If term is not divisible by
10777   // element size, proceed with the original term.
10778   for (const SCEV *&Term : Terms) {
10779     const SCEV *Q, *R;
10780     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
10781     if (!Q->isZero())
10782       Term = Q;
10783   }
10784 
10785   SmallVector<const SCEV *, 4> NewTerms;
10786 
10787   // Remove constant factors.
10788   for (const SCEV *T : Terms)
10789     if (const SCEV *NewT = removeConstantFactors(*this, T))
10790       NewTerms.push_back(NewT);
10791 
10792   DEBUG({
10793       dbgs() << "Terms after sorting:\n";
10794       for (const SCEV *T : NewTerms)
10795         dbgs() << *T << "\n";
10796     });
10797 
10798   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
10799     Sizes.clear();
10800     return;
10801   }
10802 
10803   // The last element to be pushed into Sizes is the size of an element.
10804   Sizes.push_back(ElementSize);
10805 
10806   DEBUG({
10807       dbgs() << "Sizes:\n";
10808       for (const SCEV *S : Sizes)
10809         dbgs() << *S << "\n";
10810     });
10811 }
10812 
10813 void ScalarEvolution::computeAccessFunctions(
10814     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
10815     SmallVectorImpl<const SCEV *> &Sizes) {
10816   // Early exit in case this SCEV is not an affine multivariate function.
10817   if (Sizes.empty())
10818     return;
10819 
10820   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
10821     if (!AR->isAffine())
10822       return;
10823 
10824   const SCEV *Res = Expr;
10825   int Last = Sizes.size() - 1;
10826   for (int i = Last; i >= 0; i--) {
10827     const SCEV *Q, *R;
10828     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
10829 
10830     DEBUG({
10831         dbgs() << "Res: " << *Res << "\n";
10832         dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
10833         dbgs() << "Res divided by Sizes[i]:\n";
10834         dbgs() << "Quotient: " << *Q << "\n";
10835         dbgs() << "Remainder: " << *R << "\n";
10836       });
10837 
10838     Res = Q;
10839 
10840     // Do not record the last subscript corresponding to the size of elements in
10841     // the array.
10842     if (i == Last) {
10843 
10844       // Bail out if the remainder is too complex.
10845       if (isa<SCEVAddRecExpr>(R)) {
10846         Subscripts.clear();
10847         Sizes.clear();
10848         return;
10849       }
10850 
10851       continue;
10852     }
10853 
10854     // Record the access function for the current subscript.
10855     Subscripts.push_back(R);
10856   }
10857 
10858   // Also push in last position the remainder of the last division: it will be
10859   // the access function of the innermost dimension.
10860   Subscripts.push_back(Res);
10861 
10862   std::reverse(Subscripts.begin(), Subscripts.end());
10863 
10864   DEBUG({
10865       dbgs() << "Subscripts:\n";
10866       for (const SCEV *S : Subscripts)
10867         dbgs() << *S << "\n";
10868     });
10869 }
10870 
10871 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
10872 /// sizes of an array access. Returns the remainder of the delinearization that
10873 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
10874 /// the multiples of SCEV coefficients: that is a pattern matching of sub
10875 /// expressions in the stride and base of a SCEV corresponding to the
10876 /// computation of a GCD (greatest common divisor) of base and stride.  When
10877 /// SCEV->delinearize fails, it returns the SCEV unchanged.
10878 ///
10879 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
10880 ///
10881 ///  void foo(long n, long m, long o, double A[n][m][o]) {
10882 ///
10883 ///    for (long i = 0; i < n; i++)
10884 ///      for (long j = 0; j < m; j++)
10885 ///        for (long k = 0; k < o; k++)
10886 ///          A[i][j][k] = 1.0;
10887 ///  }
10888 ///
10889 /// the delinearization input is the following AddRec SCEV:
10890 ///
10891 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
10892 ///
10893 /// From this SCEV, we are able to say that the base offset of the access is %A
10894 /// because it appears as an offset that does not divide any of the strides in
10895 /// the loops:
10896 ///
10897 ///  CHECK: Base offset: %A
10898 ///
10899 /// and then SCEV->delinearize determines the size of some of the dimensions of
10900 /// the array as these are the multiples by which the strides are happening:
10901 ///
10902 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
10903 ///
10904 /// Note that the outermost dimension remains of UnknownSize because there are
10905 /// no strides that would help identifying the size of the last dimension: when
10906 /// the array has been statically allocated, one could compute the size of that
10907 /// dimension by dividing the overall size of the array by the size of the known
10908 /// dimensions: %m * %o * 8.
10909 ///
10910 /// Finally delinearize provides the access functions for the array reference
10911 /// that does correspond to A[i][j][k] of the above C testcase:
10912 ///
10913 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
10914 ///
10915 /// The testcases are checking the output of a function pass:
10916 /// DelinearizationPass that walks through all loads and stores of a function
10917 /// asking for the SCEV of the memory access with respect to all enclosing
10918 /// loops, calling SCEV->delinearize on that and printing the results.
10919 void ScalarEvolution::delinearize(const SCEV *Expr,
10920                                  SmallVectorImpl<const SCEV *> &Subscripts,
10921                                  SmallVectorImpl<const SCEV *> &Sizes,
10922                                  const SCEV *ElementSize) {
10923   // First step: collect parametric terms.
10924   SmallVector<const SCEV *, 4> Terms;
10925   collectParametricTerms(Expr, Terms);
10926 
10927   if (Terms.empty())
10928     return;
10929 
10930   // Second step: find subscript sizes.
10931   findArrayDimensions(Terms, Sizes, ElementSize);
10932 
10933   if (Sizes.empty())
10934     return;
10935 
10936   // Third step: compute the access functions for each subscript.
10937   computeAccessFunctions(Expr, Subscripts, Sizes);
10938 
10939   if (Subscripts.empty())
10940     return;
10941 
10942   DEBUG({
10943       dbgs() << "succeeded to delinearize " << *Expr << "\n";
10944       dbgs() << "ArrayDecl[UnknownSize]";
10945       for (const SCEV *S : Sizes)
10946         dbgs() << "[" << *S << "]";
10947 
10948       dbgs() << "\nArrayRef";
10949       for (const SCEV *S : Subscripts)
10950         dbgs() << "[" << *S << "]";
10951       dbgs() << "\n";
10952     });
10953 }
10954 
10955 //===----------------------------------------------------------------------===//
10956 //                   SCEVCallbackVH Class Implementation
10957 //===----------------------------------------------------------------------===//
10958 
10959 void ScalarEvolution::SCEVCallbackVH::deleted() {
10960   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10961   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
10962     SE->ConstantEvolutionLoopExitValue.erase(PN);
10963   SE->eraseValueFromMap(getValPtr());
10964   // this now dangles!
10965 }
10966 
10967 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
10968   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
10969 
10970   // Forget all the expressions associated with users of the old value,
10971   // so that future queries will recompute the expressions using the new
10972   // value.
10973   Value *Old = getValPtr();
10974   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
10975   SmallPtrSet<User *, 8> Visited;
10976   while (!Worklist.empty()) {
10977     User *U = Worklist.pop_back_val();
10978     // Deleting the Old value will cause this to dangle. Postpone
10979     // that until everything else is done.
10980     if (U == Old)
10981       continue;
10982     if (!Visited.insert(U).second)
10983       continue;
10984     if (PHINode *PN = dyn_cast<PHINode>(U))
10985       SE->ConstantEvolutionLoopExitValue.erase(PN);
10986     SE->eraseValueFromMap(U);
10987     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
10988   }
10989   // Delete the Old value.
10990   if (PHINode *PN = dyn_cast<PHINode>(Old))
10991     SE->ConstantEvolutionLoopExitValue.erase(PN);
10992   SE->eraseValueFromMap(Old);
10993   // this now dangles!
10994 }
10995 
10996 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
10997   : CallbackVH(V), SE(se) {}
10998 
10999 //===----------------------------------------------------------------------===//
11000 //                   ScalarEvolution Class Implementation
11001 //===----------------------------------------------------------------------===//
11002 
11003 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11004                                  AssumptionCache &AC, DominatorTree &DT,
11005                                  LoopInfo &LI)
11006     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11007       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11008       LoopDispositions(64), BlockDispositions(64) {
11009   // To use guards for proving predicates, we need to scan every instruction in
11010   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11011   // time if the IR does not actually contain any calls to
11012   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11013   //
11014   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11015   // to _add_ guards to the module when there weren't any before, and wants
11016   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11017   // efficient in lieu of being smart in that rather obscure case.
11018 
11019   auto *GuardDecl = F.getParent()->getFunction(
11020       Intrinsic::getName(Intrinsic::experimental_guard));
11021   HasGuards = GuardDecl && !GuardDecl->use_empty();
11022 }
11023 
11024 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11025     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11026       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11027       ValueExprMap(std::move(Arg.ValueExprMap)),
11028       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11029       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11030       PendingMerges(std::move(Arg.PendingMerges)),
11031       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11032       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11033       PredicatedBackedgeTakenCounts(
11034           std::move(Arg.PredicatedBackedgeTakenCounts)),
11035       ConstantEvolutionLoopExitValue(
11036           std::move(Arg.ConstantEvolutionLoopExitValue)),
11037       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11038       LoopDispositions(std::move(Arg.LoopDispositions)),
11039       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11040       BlockDispositions(std::move(Arg.BlockDispositions)),
11041       UnsignedRanges(std::move(Arg.UnsignedRanges)),
11042       SignedRanges(std::move(Arg.SignedRanges)),
11043       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11044       UniquePreds(std::move(Arg.UniquePreds)),
11045       SCEVAllocator(std::move(Arg.SCEVAllocator)),
11046       LoopUsers(std::move(Arg.LoopUsers)),
11047       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11048       FirstUnknown(Arg.FirstUnknown) {
11049   Arg.FirstUnknown = nullptr;
11050 }
11051 
11052 ScalarEvolution::~ScalarEvolution() {
11053   // Iterate through all the SCEVUnknown instances and call their
11054   // destructors, so that they release their references to their values.
11055   for (SCEVUnknown *U = FirstUnknown; U;) {
11056     SCEVUnknown *Tmp = U;
11057     U = U->Next;
11058     Tmp->~SCEVUnknown();
11059   }
11060   FirstUnknown = nullptr;
11061 
11062   ExprValueMap.clear();
11063   ValueExprMap.clear();
11064   HasRecMap.clear();
11065 
11066   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11067   // that a loop had multiple computable exits.
11068   for (auto &BTCI : BackedgeTakenCounts)
11069     BTCI.second.clear();
11070   for (auto &BTCI : PredicatedBackedgeTakenCounts)
11071     BTCI.second.clear();
11072 
11073   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11074   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11075   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11076   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11077   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11078 }
11079 
11080 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11081   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11082 }
11083 
11084 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11085                           const Loop *L) {
11086   // Print all inner loops first
11087   for (Loop *I : *L)
11088     PrintLoopInfo(OS, SE, I);
11089 
11090   OS << "Loop ";
11091   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11092   OS << ": ";
11093 
11094   SmallVector<BasicBlock *, 8> ExitBlocks;
11095   L->getExitBlocks(ExitBlocks);
11096   if (ExitBlocks.size() != 1)
11097     OS << "<multiple exits> ";
11098 
11099   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11100     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
11101   } else {
11102     OS << "Unpredictable backedge-taken count. ";
11103   }
11104 
11105   OS << "\n"
11106         "Loop ";
11107   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11108   OS << ": ";
11109 
11110   if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
11111     OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
11112     if (SE->isBackedgeTakenCountMaxOrZero(L))
11113       OS << ", actual taken count either this or zero.";
11114   } else {
11115     OS << "Unpredictable max backedge-taken count. ";
11116   }
11117 
11118   OS << "\n"
11119         "Loop ";
11120   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11121   OS << ": ";
11122 
11123   SCEVUnionPredicate Pred;
11124   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11125   if (!isa<SCEVCouldNotCompute>(PBT)) {
11126     OS << "Predicated backedge-taken count is " << *PBT << "\n";
11127     OS << " Predicates:\n";
11128     Pred.print(OS, 4);
11129   } else {
11130     OS << "Unpredictable predicated backedge-taken count. ";
11131   }
11132   OS << "\n";
11133 
11134   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11135     OS << "Loop ";
11136     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11137     OS << ": ";
11138     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11139   }
11140 }
11141 
11142 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11143   switch (LD) {
11144   case ScalarEvolution::LoopVariant:
11145     return "Variant";
11146   case ScalarEvolution::LoopInvariant:
11147     return "Invariant";
11148   case ScalarEvolution::LoopComputable:
11149     return "Computable";
11150   }
11151   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11152 }
11153 
11154 void ScalarEvolution::print(raw_ostream &OS) const {
11155   // ScalarEvolution's implementation of the print method is to print
11156   // out SCEV values of all instructions that are interesting. Doing
11157   // this potentially causes it to create new SCEV objects though,
11158   // which technically conflicts with the const qualifier. This isn't
11159   // observable from outside the class though, so casting away the
11160   // const isn't dangerous.
11161   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11162 
11163   OS << "Classifying expressions for: ";
11164   F.printAsOperand(OS, /*PrintType=*/false);
11165   OS << "\n";
11166   for (Instruction &I : instructions(F))
11167     if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11168       OS << I << '\n';
11169       OS << "  -->  ";
11170       const SCEV *SV = SE.getSCEV(&I);
11171       SV->print(OS);
11172       if (!isa<SCEVCouldNotCompute>(SV)) {
11173         OS << " U: ";
11174         SE.getUnsignedRange(SV).print(OS);
11175         OS << " S: ";
11176         SE.getSignedRange(SV).print(OS);
11177       }
11178 
11179       const Loop *L = LI.getLoopFor(I.getParent());
11180 
11181       const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11182       if (AtUse != SV) {
11183         OS << "  -->  ";
11184         AtUse->print(OS);
11185         if (!isa<SCEVCouldNotCompute>(AtUse)) {
11186           OS << " U: ";
11187           SE.getUnsignedRange(AtUse).print(OS);
11188           OS << " S: ";
11189           SE.getSignedRange(AtUse).print(OS);
11190         }
11191       }
11192 
11193       if (L) {
11194         OS << "\t\t" "Exits: ";
11195         const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11196         if (!SE.isLoopInvariant(ExitValue, L)) {
11197           OS << "<<Unknown>>";
11198         } else {
11199           OS << *ExitValue;
11200         }
11201 
11202         bool First = true;
11203         for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11204           if (First) {
11205             OS << "\t\t" "LoopDispositions: { ";
11206             First = false;
11207           } else {
11208             OS << ", ";
11209           }
11210 
11211           Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11212           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11213         }
11214 
11215         for (auto *InnerL : depth_first(L)) {
11216           if (InnerL == L)
11217             continue;
11218           if (First) {
11219             OS << "\t\t" "LoopDispositions: { ";
11220             First = false;
11221           } else {
11222             OS << ", ";
11223           }
11224 
11225           InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11226           OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11227         }
11228 
11229         OS << " }";
11230       }
11231 
11232       OS << "\n";
11233     }
11234 
11235   OS << "Determining loop execution counts for: ";
11236   F.printAsOperand(OS, /*PrintType=*/false);
11237   OS << "\n";
11238   for (Loop *I : LI)
11239     PrintLoopInfo(OS, &SE, I);
11240 }
11241 
11242 ScalarEvolution::LoopDisposition
11243 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11244   auto &Values = LoopDispositions[S];
11245   for (auto &V : Values) {
11246     if (V.getPointer() == L)
11247       return V.getInt();
11248   }
11249   Values.emplace_back(L, LoopVariant);
11250   LoopDisposition D = computeLoopDisposition(S, L);
11251   auto &Values2 = LoopDispositions[S];
11252   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11253     if (V.getPointer() == L) {
11254       V.setInt(D);
11255       break;
11256     }
11257   }
11258   return D;
11259 }
11260 
11261 ScalarEvolution::LoopDisposition
11262 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11263   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11264   case scConstant:
11265     return LoopInvariant;
11266   case scTruncate:
11267   case scZeroExtend:
11268   case scSignExtend:
11269     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11270   case scAddRecExpr: {
11271     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11272 
11273     // If L is the addrec's loop, it's computable.
11274     if (AR->getLoop() == L)
11275       return LoopComputable;
11276 
11277     // Add recurrences are never invariant in the function-body (null loop).
11278     if (!L)
11279       return LoopVariant;
11280 
11281     // Everything that is not defined at loop entry is variant.
11282     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11283       return LoopVariant;
11284     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11285            " dominate the contained loop's header?");
11286 
11287     // This recurrence is invariant w.r.t. L if AR's loop contains L.
11288     if (AR->getLoop()->contains(L))
11289       return LoopInvariant;
11290 
11291     // This recurrence is variant w.r.t. L if any of its operands
11292     // are variant.
11293     for (auto *Op : AR->operands())
11294       if (!isLoopInvariant(Op, L))
11295         return LoopVariant;
11296 
11297     // Otherwise it's loop-invariant.
11298     return LoopInvariant;
11299   }
11300   case scAddExpr:
11301   case scMulExpr:
11302   case scUMaxExpr:
11303   case scSMaxExpr: {
11304     bool HasVarying = false;
11305     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11306       LoopDisposition D = getLoopDisposition(Op, L);
11307       if (D == LoopVariant)
11308         return LoopVariant;
11309       if (D == LoopComputable)
11310         HasVarying = true;
11311     }
11312     return HasVarying ? LoopComputable : LoopInvariant;
11313   }
11314   case scUDivExpr: {
11315     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11316     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11317     if (LD == LoopVariant)
11318       return LoopVariant;
11319     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11320     if (RD == LoopVariant)
11321       return LoopVariant;
11322     return (LD == LoopInvariant && RD == LoopInvariant) ?
11323            LoopInvariant : LoopComputable;
11324   }
11325   case scUnknown:
11326     // All non-instruction values are loop invariant.  All instructions are loop
11327     // invariant if they are not contained in the specified loop.
11328     // Instructions are never considered invariant in the function body
11329     // (null loop) because they are defined within the "loop".
11330     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11331       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11332     return LoopInvariant;
11333   case scCouldNotCompute:
11334     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11335   }
11336   llvm_unreachable("Unknown SCEV kind!");
11337 }
11338 
11339 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11340   return getLoopDisposition(S, L) == LoopInvariant;
11341 }
11342 
11343 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11344   return getLoopDisposition(S, L) == LoopComputable;
11345 }
11346 
11347 ScalarEvolution::BlockDisposition
11348 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11349   auto &Values = BlockDispositions[S];
11350   for (auto &V : Values) {
11351     if (V.getPointer() == BB)
11352       return V.getInt();
11353   }
11354   Values.emplace_back(BB, DoesNotDominateBlock);
11355   BlockDisposition D = computeBlockDisposition(S, BB);
11356   auto &Values2 = BlockDispositions[S];
11357   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11358     if (V.getPointer() == BB) {
11359       V.setInt(D);
11360       break;
11361     }
11362   }
11363   return D;
11364 }
11365 
11366 ScalarEvolution::BlockDisposition
11367 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11368   switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11369   case scConstant:
11370     return ProperlyDominatesBlock;
11371   case scTruncate:
11372   case scZeroExtend:
11373   case scSignExtend:
11374     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11375   case scAddRecExpr: {
11376     // This uses a "dominates" query instead of "properly dominates" query
11377     // to test for proper dominance too, because the instruction which
11378     // produces the addrec's value is a PHI, and a PHI effectively properly
11379     // dominates its entire containing block.
11380     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11381     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11382       return DoesNotDominateBlock;
11383 
11384     // Fall through into SCEVNAryExpr handling.
11385     LLVM_FALLTHROUGH;
11386   }
11387   case scAddExpr:
11388   case scMulExpr:
11389   case scUMaxExpr:
11390   case scSMaxExpr: {
11391     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11392     bool Proper = true;
11393     for (const SCEV *NAryOp : NAry->operands()) {
11394       BlockDisposition D = getBlockDisposition(NAryOp, BB);
11395       if (D == DoesNotDominateBlock)
11396         return DoesNotDominateBlock;
11397       if (D == DominatesBlock)
11398         Proper = false;
11399     }
11400     return Proper ? ProperlyDominatesBlock : DominatesBlock;
11401   }
11402   case scUDivExpr: {
11403     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11404     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11405     BlockDisposition LD = getBlockDisposition(LHS, BB);
11406     if (LD == DoesNotDominateBlock)
11407       return DoesNotDominateBlock;
11408     BlockDisposition RD = getBlockDisposition(RHS, BB);
11409     if (RD == DoesNotDominateBlock)
11410       return DoesNotDominateBlock;
11411     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11412       ProperlyDominatesBlock : DominatesBlock;
11413   }
11414   case scUnknown:
11415     if (Instruction *I =
11416           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11417       if (I->getParent() == BB)
11418         return DominatesBlock;
11419       if (DT.properlyDominates(I->getParent(), BB))
11420         return ProperlyDominatesBlock;
11421       return DoesNotDominateBlock;
11422     }
11423     return ProperlyDominatesBlock;
11424   case scCouldNotCompute:
11425     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11426   }
11427   llvm_unreachable("Unknown SCEV kind!");
11428 }
11429 
11430 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11431   return getBlockDisposition(S, BB) >= DominatesBlock;
11432 }
11433 
11434 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11435   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11436 }
11437 
11438 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11439   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11440 }
11441 
11442 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11443   auto IsS = [&](const SCEV *X) { return S == X; };
11444   auto ContainsS = [&](const SCEV *X) {
11445     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11446   };
11447   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11448 }
11449 
11450 void
11451 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11452   ValuesAtScopes.erase(S);
11453   LoopDispositions.erase(S);
11454   BlockDispositions.erase(S);
11455   UnsignedRanges.erase(S);
11456   SignedRanges.erase(S);
11457   ExprValueMap.erase(S);
11458   HasRecMap.erase(S);
11459   MinTrailingZerosCache.erase(S);
11460 
11461   for (auto I = PredicatedSCEVRewrites.begin();
11462        I != PredicatedSCEVRewrites.end();) {
11463     std::pair<const SCEV *, const Loop *> Entry = I->first;
11464     if (Entry.first == S)
11465       PredicatedSCEVRewrites.erase(I++);
11466     else
11467       ++I;
11468   }
11469 
11470   auto RemoveSCEVFromBackedgeMap =
11471       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11472         for (auto I = Map.begin(), E = Map.end(); I != E;) {
11473           BackedgeTakenInfo &BEInfo = I->second;
11474           if (BEInfo.hasOperand(S, this)) {
11475             BEInfo.clear();
11476             Map.erase(I++);
11477           } else
11478             ++I;
11479         }
11480       };
11481 
11482   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11483   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11484 }
11485 
11486 void
11487 ScalarEvolution::getUsedLoops(const SCEV *S,
11488                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11489   struct FindUsedLoops {
11490     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11491         : LoopsUsed(LoopsUsed) {}
11492     SmallPtrSetImpl<const Loop *> &LoopsUsed;
11493     bool follow(const SCEV *S) {
11494       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11495         LoopsUsed.insert(AR->getLoop());
11496       return true;
11497     }
11498 
11499     bool isDone() const { return false; }
11500   };
11501 
11502   FindUsedLoops F(LoopsUsed);
11503   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11504 }
11505 
11506 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11507   SmallPtrSet<const Loop *, 8> LoopsUsed;
11508   getUsedLoops(S, LoopsUsed);
11509   for (auto *L : LoopsUsed)
11510     LoopUsers[L].push_back(S);
11511 }
11512 
11513 void ScalarEvolution::verify() const {
11514   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11515   ScalarEvolution SE2(F, TLI, AC, DT, LI);
11516 
11517   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11518 
11519   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11520   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11521     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11522 
11523     const SCEV *visitConstant(const SCEVConstant *Constant) {
11524       return SE.getConstant(Constant->getAPInt());
11525     }
11526 
11527     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11528       return SE.getUnknown(Expr->getValue());
11529     }
11530 
11531     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11532       return SE.getCouldNotCompute();
11533     }
11534   };
11535 
11536   SCEVMapper SCM(SE2);
11537 
11538   while (!LoopStack.empty()) {
11539     auto *L = LoopStack.pop_back_val();
11540     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11541 
11542     auto *CurBECount = SCM.visit(
11543         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11544     auto *NewBECount = SE2.getBackedgeTakenCount(L);
11545 
11546     if (CurBECount == SE2.getCouldNotCompute() ||
11547         NewBECount == SE2.getCouldNotCompute()) {
11548       // NB! This situation is legal, but is very suspicious -- whatever pass
11549       // change the loop to make a trip count go from could not compute to
11550       // computable or vice-versa *should have* invalidated SCEV.  However, we
11551       // choose not to assert here (for now) since we don't want false
11552       // positives.
11553       continue;
11554     }
11555 
11556     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11557       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11558       // not propagate undef aggressively).  This means we can (and do) fail
11559       // verification in cases where a transform makes the trip count of a loop
11560       // go from "undef" to "undef+1" (say).  The transform is fine, since in
11561       // both cases the loop iterates "undef" times, but SCEV thinks we
11562       // increased the trip count of the loop by 1 incorrectly.
11563       continue;
11564     }
11565 
11566     if (SE.getTypeSizeInBits(CurBECount->getType()) >
11567         SE.getTypeSizeInBits(NewBECount->getType()))
11568       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11569     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11570              SE.getTypeSizeInBits(NewBECount->getType()))
11571       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11572 
11573     auto *ConstantDelta =
11574         dyn_cast<SCEVConstant>(SE2.getMinusSCEV(CurBECount, NewBECount));
11575 
11576     if (ConstantDelta && ConstantDelta->getAPInt() != 0) {
11577       dbgs() << "Trip Count Changed!\n";
11578       dbgs() << "Old: " << *CurBECount << "\n";
11579       dbgs() << "New: " << *NewBECount << "\n";
11580       dbgs() << "Delta: " << *ConstantDelta << "\n";
11581       std::abort();
11582     }
11583   }
11584 }
11585 
11586 bool ScalarEvolution::invalidate(
11587     Function &F, const PreservedAnalyses &PA,
11588     FunctionAnalysisManager::Invalidator &Inv) {
11589   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11590   // of its dependencies is invalidated.
11591   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11592   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11593          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11594          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11595          Inv.invalidate<LoopAnalysis>(F, PA);
11596 }
11597 
11598 AnalysisKey ScalarEvolutionAnalysis::Key;
11599 
11600 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11601                                              FunctionAnalysisManager &AM) {
11602   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11603                          AM.getResult<AssumptionAnalysis>(F),
11604                          AM.getResult<DominatorTreeAnalysis>(F),
11605                          AM.getResult<LoopAnalysis>(F));
11606 }
11607 
11608 PreservedAnalyses
11609 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11610   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11611   return PreservedAnalyses::all();
11612 }
11613 
11614 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11615                       "Scalar Evolution Analysis", false, true)
11616 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11617 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11618 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11619 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11620 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11621                     "Scalar Evolution Analysis", false, true)
11622 
11623 char ScalarEvolutionWrapperPass::ID = 0;
11624 
11625 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11626   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11627 }
11628 
11629 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11630   SE.reset(new ScalarEvolution(
11631       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
11632       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11633       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11634       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11635   return false;
11636 }
11637 
11638 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11639 
11640 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11641   SE->print(OS);
11642 }
11643 
11644 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
11645   if (!VerifySCEV)
11646     return;
11647 
11648   SE->verify();
11649 }
11650 
11651 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
11652   AU.setPreservesAll();
11653   AU.addRequiredTransitive<AssumptionCacheTracker>();
11654   AU.addRequiredTransitive<LoopInfoWrapperPass>();
11655   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
11656   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
11657 }
11658 
11659 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
11660                                                         const SCEV *RHS) {
11661   FoldingSetNodeID ID;
11662   assert(LHS->getType() == RHS->getType() &&
11663          "Type mismatch between LHS and RHS");
11664   // Unique this node based on the arguments
11665   ID.AddInteger(SCEVPredicate::P_Equal);
11666   ID.AddPointer(LHS);
11667   ID.AddPointer(RHS);
11668   void *IP = nullptr;
11669   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11670     return S;
11671   SCEVEqualPredicate *Eq = new (SCEVAllocator)
11672       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
11673   UniquePreds.InsertNode(Eq, IP);
11674   return Eq;
11675 }
11676 
11677 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
11678     const SCEVAddRecExpr *AR,
11679     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11680   FoldingSetNodeID ID;
11681   // Unique this node based on the arguments
11682   ID.AddInteger(SCEVPredicate::P_Wrap);
11683   ID.AddPointer(AR);
11684   ID.AddInteger(AddedFlags);
11685   void *IP = nullptr;
11686   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
11687     return S;
11688   auto *OF = new (SCEVAllocator)
11689       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
11690   UniquePreds.InsertNode(OF, IP);
11691   return OF;
11692 }
11693 
11694 namespace {
11695 
11696 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
11697 public:
11698 
11699   /// Rewrites \p S in the context of a loop L and the SCEV predication
11700   /// infrastructure.
11701   ///
11702   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
11703   /// equivalences present in \p Pred.
11704   ///
11705   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
11706   /// \p NewPreds such that the result will be an AddRecExpr.
11707   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
11708                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11709                              SCEVUnionPredicate *Pred) {
11710     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
11711     return Rewriter.visit(S);
11712   }
11713 
11714   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11715     if (Pred) {
11716       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
11717       for (auto *Pred : ExprPreds)
11718         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
11719           if (IPred->getLHS() == Expr)
11720             return IPred->getRHS();
11721     }
11722     return convertToAddRecWithPreds(Expr);
11723   }
11724 
11725   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
11726     const SCEV *Operand = visit(Expr->getOperand());
11727     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11728     if (AR && AR->getLoop() == L && AR->isAffine()) {
11729       // This couldn't be folded because the operand didn't have the nuw
11730       // flag. Add the nusw flag as an assumption that we could make.
11731       const SCEV *Step = AR->getStepRecurrence(SE);
11732       Type *Ty = Expr->getType();
11733       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
11734         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
11735                                 SE.getSignExtendExpr(Step, Ty), L,
11736                                 AR->getNoWrapFlags());
11737     }
11738     return SE.getZeroExtendExpr(Operand, Expr->getType());
11739   }
11740 
11741   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
11742     const SCEV *Operand = visit(Expr->getOperand());
11743     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
11744     if (AR && AR->getLoop() == L && AR->isAffine()) {
11745       // This couldn't be folded because the operand didn't have the nsw
11746       // flag. Add the nssw flag as an assumption that we could make.
11747       const SCEV *Step = AR->getStepRecurrence(SE);
11748       Type *Ty = Expr->getType();
11749       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
11750         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
11751                                 SE.getSignExtendExpr(Step, Ty), L,
11752                                 AR->getNoWrapFlags());
11753     }
11754     return SE.getSignExtendExpr(Operand, Expr->getType());
11755   }
11756 
11757 private:
11758   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
11759                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
11760                         SCEVUnionPredicate *Pred)
11761       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
11762 
11763   bool addOverflowAssumption(const SCEVPredicate *P) {
11764     if (!NewPreds) {
11765       // Check if we've already made this assumption.
11766       return Pred && Pred->implies(P);
11767     }
11768     NewPreds->insert(P);
11769     return true;
11770   }
11771 
11772   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
11773                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
11774     auto *A = SE.getWrapPredicate(AR, AddedFlags);
11775     return addOverflowAssumption(A);
11776   }
11777 
11778   // If \p Expr represents a PHINode, we try to see if it can be represented
11779   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
11780   // to add this predicate as a runtime overflow check, we return the AddRec.
11781   // If \p Expr does not meet these conditions (is not a PHI node, or we
11782   // couldn't create an AddRec for it, or couldn't add the predicate), we just
11783   // return \p Expr.
11784   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
11785     if (!isa<PHINode>(Expr->getValue()))
11786       return Expr;
11787     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
11788     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
11789     if (!PredicatedRewrite)
11790       return Expr;
11791     for (auto *P : PredicatedRewrite->second){
11792       // Wrap predicates from outer loops are not supported.
11793       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
11794         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
11795         if (L != AR->getLoop())
11796           return Expr;
11797       }
11798       if (!addOverflowAssumption(P))
11799         return Expr;
11800     }
11801     return PredicatedRewrite->first;
11802   }
11803 
11804   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
11805   SCEVUnionPredicate *Pred;
11806   const Loop *L;
11807 };
11808 
11809 } // end anonymous namespace
11810 
11811 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
11812                                                    SCEVUnionPredicate &Preds) {
11813   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
11814 }
11815 
11816 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
11817     const SCEV *S, const Loop *L,
11818     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
11819   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
11820   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
11821   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
11822 
11823   if (!AddRec)
11824     return nullptr;
11825 
11826   // Since the transformation was successful, we can now transfer the SCEV
11827   // predicates.
11828   for (auto *P : TransformPreds)
11829     Preds.insert(P);
11830 
11831   return AddRec;
11832 }
11833 
11834 /// SCEV predicates
11835 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
11836                              SCEVPredicateKind Kind)
11837     : FastID(ID), Kind(Kind) {}
11838 
11839 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
11840                                        const SCEV *LHS, const SCEV *RHS)
11841     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
11842   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
11843   assert(LHS != RHS && "LHS and RHS are the same SCEV");
11844 }
11845 
11846 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
11847   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
11848 
11849   if (!Op)
11850     return false;
11851 
11852   return Op->LHS == LHS && Op->RHS == RHS;
11853 }
11854 
11855 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
11856 
11857 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
11858 
11859 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
11860   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
11861 }
11862 
11863 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
11864                                      const SCEVAddRecExpr *AR,
11865                                      IncrementWrapFlags Flags)
11866     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
11867 
11868 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
11869 
11870 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
11871   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
11872 
11873   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
11874 }
11875 
11876 bool SCEVWrapPredicate::isAlwaysTrue() const {
11877   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
11878   IncrementWrapFlags IFlags = Flags;
11879 
11880   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
11881     IFlags = clearFlags(IFlags, IncrementNSSW);
11882 
11883   return IFlags == IncrementAnyWrap;
11884 }
11885 
11886 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
11887   OS.indent(Depth) << *getExpr() << " Added Flags: ";
11888   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
11889     OS << "<nusw>";
11890   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
11891     OS << "<nssw>";
11892   OS << "\n";
11893 }
11894 
11895 SCEVWrapPredicate::IncrementWrapFlags
11896 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
11897                                    ScalarEvolution &SE) {
11898   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
11899   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
11900 
11901   // We can safely transfer the NSW flag as NSSW.
11902   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
11903     ImpliedFlags = IncrementNSSW;
11904 
11905   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
11906     // If the increment is positive, the SCEV NUW flag will also imply the
11907     // WrapPredicate NUSW flag.
11908     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
11909       if (Step->getValue()->getValue().isNonNegative())
11910         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
11911   }
11912 
11913   return ImpliedFlags;
11914 }
11915 
11916 /// Union predicates don't get cached so create a dummy set ID for it.
11917 SCEVUnionPredicate::SCEVUnionPredicate()
11918     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
11919 
11920 bool SCEVUnionPredicate::isAlwaysTrue() const {
11921   return all_of(Preds,
11922                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
11923 }
11924 
11925 ArrayRef<const SCEVPredicate *>
11926 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
11927   auto I = SCEVToPreds.find(Expr);
11928   if (I == SCEVToPreds.end())
11929     return ArrayRef<const SCEVPredicate *>();
11930   return I->second;
11931 }
11932 
11933 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
11934   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
11935     return all_of(Set->Preds,
11936                   [this](const SCEVPredicate *I) { return this->implies(I); });
11937 
11938   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
11939   if (ScevPredsIt == SCEVToPreds.end())
11940     return false;
11941   auto &SCEVPreds = ScevPredsIt->second;
11942 
11943   return any_of(SCEVPreds,
11944                 [N](const SCEVPredicate *I) { return I->implies(N); });
11945 }
11946 
11947 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
11948 
11949 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
11950   for (auto Pred : Preds)
11951     Pred->print(OS, Depth);
11952 }
11953 
11954 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
11955   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
11956     for (auto Pred : Set->Preds)
11957       add(Pred);
11958     return;
11959   }
11960 
11961   if (implies(N))
11962     return;
11963 
11964   const SCEV *Key = N->getExpr();
11965   assert(Key && "Only SCEVUnionPredicate doesn't have an "
11966                 " associated expression!");
11967 
11968   SCEVToPreds[Key].push_back(N);
11969   Preds.push_back(N);
11970 }
11971 
11972 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
11973                                                      Loop &L)
11974     : SE(SE), L(L) {}
11975 
11976 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
11977   const SCEV *Expr = SE.getSCEV(V);
11978   RewriteEntry &Entry = RewriteMap[Expr];
11979 
11980   // If we already have an entry and the version matches, return it.
11981   if (Entry.second && Generation == Entry.first)
11982     return Entry.second;
11983 
11984   // We found an entry but it's stale. Rewrite the stale entry
11985   // according to the current predicate.
11986   if (Entry.second)
11987     Expr = Entry.second;
11988 
11989   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
11990   Entry = {Generation, NewSCEV};
11991 
11992   return NewSCEV;
11993 }
11994 
11995 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
11996   if (!BackedgeCount) {
11997     SCEVUnionPredicate BackedgePred;
11998     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
11999     addPredicate(BackedgePred);
12000   }
12001   return BackedgeCount;
12002 }
12003 
12004 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12005   if (Preds.implies(&Pred))
12006     return;
12007   Preds.add(&Pred);
12008   updateGeneration();
12009 }
12010 
12011 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12012   return Preds;
12013 }
12014 
12015 void PredicatedScalarEvolution::updateGeneration() {
12016   // If the generation number wrapped recompute everything.
12017   if (++Generation == 0) {
12018     for (auto &II : RewriteMap) {
12019       const SCEV *Rewritten = II.second.second;
12020       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12021     }
12022   }
12023 }
12024 
12025 void PredicatedScalarEvolution::setNoOverflow(
12026     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12027   const SCEV *Expr = getSCEV(V);
12028   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12029 
12030   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12031 
12032   // Clear the statically implied flags.
12033   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12034   addPredicate(*SE.getWrapPredicate(AR, Flags));
12035 
12036   auto II = FlagsMap.insert({V, Flags});
12037   if (!II.second)
12038     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12039 }
12040 
12041 bool PredicatedScalarEvolution::hasNoOverflow(
12042     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12043   const SCEV *Expr = getSCEV(V);
12044   const auto *AR = cast<SCEVAddRecExpr>(Expr);
12045 
12046   Flags = SCEVWrapPredicate::clearFlags(
12047       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12048 
12049   auto II = FlagsMap.find(V);
12050 
12051   if (II != FlagsMap.end())
12052     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12053 
12054   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12055 }
12056 
12057 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12058   const SCEV *Expr = this->getSCEV(V);
12059   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12060   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12061 
12062   if (!New)
12063     return nullptr;
12064 
12065   for (auto *P : NewPreds)
12066     Preds.add(P);
12067 
12068   updateGeneration();
12069   RewriteMap[SE.getSCEV(V)] = {Generation, New};
12070   return New;
12071 }
12072 
12073 PredicatedScalarEvolution::PredicatedScalarEvolution(
12074     const PredicatedScalarEvolution &Init)
12075     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12076       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12077   for (const auto &I : Init.FlagsMap)
12078     FlagsMap.insert(I);
12079 }
12080 
12081 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12082   // For each block.
12083   for (auto *BB : L.getBlocks())
12084     for (auto &I : *BB) {
12085       if (!SE.isSCEVable(I.getType()))
12086         continue;
12087 
12088       auto *Expr = SE.getSCEV(&I);
12089       auto II = RewriteMap.find(Expr);
12090 
12091       if (II == RewriteMap.end())
12092         continue;
12093 
12094       // Don't print things that are not interesting.
12095       if (II->second.second == Expr)
12096         continue;
12097 
12098       OS.indent(Depth) << "[PSE]" << I << ":\n";
12099       OS.indent(Depth + 2) << *Expr << "\n";
12100       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12101     }
12102 }
12103